Send JSON data via POST PHP instead of Ajax version

Refresh

April 2019

Views

75 time

1

I have to create a JSON object that is the equivalent of a JSON object created with this Ajax code snippet:

$.ajax({
    type    : "POST",
    url     : "?",
    dataType: "json",
    data    : "username=" + encodeURIComponent($('input[name="username"]').val()) + "&password=" + encodeURIComponent($('input[name="password"]').val()) + "&antiForgeryToken=d98188e0f56bafa75180591e38d189ee",
    success : function(json) {
        if(json.status == 'success') {
            window.parent.location.href = json.returnUrl;
            window.parent.$.fancybox.close();
        } else {
            $('#slfErrorAlert').show();
            $('.spispinner').hide();
            $maindiv.removeAttr("disabled");
            $maindiv.removeClass("instaclass31");
        }
    }
});
});

I can only use PHP, and this is what I produced so far, using the SimpleBrowser library from SimpleTest:

$browser = new SimpleBrowser();
$str = '?username=aaa&password=bbb&antiForgeryToken=d98188e0f56bafa75180591e38d189ee';
$json = json_encode($str);
$browser->post($httpsPage, $json);

I specify that I don't have to use necessarily this library and its methods, but for example I know that this can also be done using cURL, although I don't know how.
When I launch the script, I get as output a generic {"status":"error"} from the POST server I think.
What have I been missing?

Correct syntax using json_encode according to @Andy: (still same error message):

$data = array('username' => 'aaa', 'password' => 'bbb');
$json = json_encode($data);

2 answers

0

Try with curl:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $httpsPage);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.rawurlencode('aaa').'&password='.rawurlencode('bbb').'&antiForgeryToken=d98188e0f56bafa75180591e38d189ee');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$server_output = curl_exec ($ch); 
curl_close ($ch);
print_r($server_output);

Or try with your code without encoding to json the post vars:

$browser = new SimpleBrowser();
$str = '?username='.rawurlencode('aaa').'&password='.rawurlencode('bbb').'&antiForgeryToken=d98188e0f56bafa75180591e38d189ee';
$browser->post($httpsPage, $str);

The response is going to be in json format, but the post vars I don't think they should be. From jQuery .ajax help: dataType (default: Intelligent Guess (xml, json, script, or html)) The type of data that you're expecting back from the server.

0

According to the PHP documentation page of json_encode you have to bypass an array into this method. More details you can find here: http://php.net/manual/en/function.json-encode.php

In your case you probably need to build something like this:

$reqData = array('user' => 'foo', 'eamil' => '[email protected]');
// {"user":"foo","email":"[email protected]"}
json_encode($reData);