0

I am trying to send some JSON data to a PHP file using Ajax. Here is my JavaScript code:

function updateJSON(){
    var xmlhttpa;
    if (window.XMLHttpRequest){
        xmlhttpa = new XMLHttpRequest();
    } else {
        xmlhttpa = new ActiveXObject("Microsoft.XMLHTTP");
    };
    xmlhttpa.onreadystatechange = function(){
        if (xmlhttpa.readyState==4 && xmlhttpa.status==200){
            console.log("Sent")
        }
    };
    xmlhttpa.open("POST", "update.php", true);
    xmlhttpa.send("json=" + JSON.stringify(json));
};

And here is the PHP file that processes the request:

<?php
    $json = $_POST["json"];
    file_put_contents('data.json', $json);

Unfortunately this isn't working. How can I repair my code?

Please, no jQuery.

Thanks!

Also, if you vote down, please tell me why so I can improve this question.

3
  • In my JavaScript, that is the data I am trying to send. Commented Apr 24, 2014 at 12:49
  • 2
    what's not working? what error do you get? Commented Apr 24, 2014 at 12:50
  • @Touchpad Surprisingly, I get no errors exempt for the fact that the JSON file is wiped clean. Commented Apr 24, 2014 at 12:51

1 Answer 1

2

You should add line with setting Content-type when you POST your data.Try this:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Also :

xmlhttp.send("json=" + encodeURIComponent(JSON.stringify(json)));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. I am not very familiar with Ajax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.