2

I'm having trouble with the following JavaScript, where data is a JavaScript object:

var ajax_send = function(data) {
        var httpRequest;

        makeRequest('/prototype/test.php', data);

        function makeRequest(url, data) {
            if (window.XMLHttpRequest) {
                httpRequest = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                try {
                    httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } 
                catch (e) {
                    try {
                        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    } 
                    catch (e) {}
                }
            }

            if (!httpRequest) {
                alert('Giving up :( Cannot create an XMLHTTP instance');
                return false;
            }

            httpRequest.onreadystatechange = alertContents;
            httpRequest.open('POST', url);
            httpRequest.setRequestHeader('Content-Type', 'application/json');
            httpRequest.send(JSON.stringify(data));
        }

        function alertContents() {
            if (httpRequest.readyState === 4) {
                if (httpRequest.status === 200) {
                    alert(httpRequest.responseText);
                } else {
                    alert('There was a problem with the request.');
                }
            }
        }
    };

The PHP is:

$data = $_POST['data'];
$obj = json_decode($data);
echo $obj;

In dev tools the request payload looks ok but it doesn't seem to be what the PHP is looking for. Nothing gets through to the PHP script and the response is empty.

What am I doing wrong?

5
  • 1
    It is impossible to tell what the PHP is looking for since you didn't show us the PHP code. Commented Nov 11, 2014 at 14:01
  • Share with us prototype/test.php page codes please Commented Nov 11, 2014 at 14:07
  • Sorry, updated the question. Commented Nov 11, 2014 at 14:09
  • Not directly related, but using jquery to do ajax calls is quite a lot nicer imo. Commented Nov 11, 2014 at 14:24
  • Damn, I forgot the "no use jQuery replies"! You're right of course, it is much easier and nicer. This is a learning exercise for me as much as anything else and I like to understand the vanilla. Commented Nov 11, 2014 at 14:27

2 Answers 2

3

When you send POST requests with Content-Type: application/json, things work a bit differently with PHP.

You are going to need to access it like so:

$postData = json_decode(file_get_contents('php://input'));

Instead of the usual $_POST.

If you want to send it as a regular form that will be populated to $_POST, you need to set your header like so:

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

And populate your fields like so:

key=value&key2=value2&key3=value3

etc

Sign up to request clarification or add additional context in comments.

8 Comments

I updated the answer, try setting the request header differently. You'll see how the data looks then. Also, what does your error say exactly?
Yep, that works, thank you very much :) I would still be interested in knowing how to post JSON without converting to form values though.
If you could tell me more in detail about your error, I can help you figure out why it's not working. Did you try look at the contents of file_get_contents('php://input') before trying to parse it?
Hmm. Not much details on the error, just 500 internal server error. The contents of file_get_content('php://input') is valid JSON though.
Ok, things go wrong when I use the json_decode() function. Is this likely to be a localhost setup problem?
|
0

On Symfony you can use $request->getContent(); which internally makes file_get_contents('php://input')). Then decode the result.

$requestData = $request->getContent(); // this makes file_get_contents('php://input')
$data = json_decode($requestData, true);

Comments

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.