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);
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' => 'bar@baz');
// {"user":"foo","email":"bar@baz"}
json_encode($reData);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.