Simulate jQuery.ajax request in PHP
I have to simulate AJAX request in PHP, exactly as is in jQuery. My current code is here:
Original AJAX call (mustn't be modified)
$.ajax({
type: "POST",
url: "/someFile.php",
data: data,
success: function(response) {
some_code_here;
},
error: functi开发者_StackOverflow社区on() {
some_code_here;
}
});
Current PHP code - trying to simulate JS's code behaviour above
function _misc_test() {
$data = json_decode("xxx"); // The "xxx" is placeholder for the same string, as is in data var in JS above
$ajaxResponse = _make_post_request('/someFile.php', $data);
print_r($ajaxResponse);
}
function _make_post_request($url, $data) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
And unfortunatelly, the PHP code doesn't seems to generate exactly the same packets like JS code - that's what I need. Can anyone give me a hand please?
EDIT: maybe it's important, that data
variable in JS holds complex JS object like this one:
{"options":{"userIP":"89.102.122.16","playerType":"flash","playlistItems":[{"Type":"Archive","Format":"MP4_Web","Identifier":"209 452 80139\/0042","Title":"Nezn\u00e1m\u00ed hrdinov\u00e9","Region":"","SubtitlesUrl":"http:\/\/img2.ceskatelevize.cz\/ivysilani\/subtitles\/209\/209452801390042\/subtitles-1.txt","Indexes":null,"Gemius":{"Param":[{"Name":"materialIdentifier","Value":"209 452 80139\/0042"},{"Name":"testParam","Value":"testValue"}]}}],"previewImageURL":null}}
in js : data: $('form').serialize();
in php : How to post data in PHP using file_get_contents?
$jsonstr = '{"options":{"userIP":"89.102.122.16","playerType":"flash","playlistItems":[{"Type":"Archive","Format":"MP4_Web","Identifier":"209 452 80139\/0042","Title":"Nezn\u00e1m\u00ed hrdinov\u00e9","Region":"","SubtitlesUrl":"http:\/\/img2.ceskatelevize.cz\/ivysilani\/subtitles\/209\/209452801390042\/subtitles-1.txt","Indexes":null,"Gemius":{"Param":[{"Name":"materialIdentifier","Value":"209 452 80139\/0042"},{"Name":"testParam","Value":"testValue"}]}}],"previewImageURL":null}}';
print_r(
$data = json_decode($jsonstr ,true)
);
$data_url = http_build_query ($data);
$data_url = str_replace("amp;","",$data_url); //fix for & to &
$data_len = strlen ($data_url);
$url = 'http://domain.com/returnPost.php';
$result = file_get_contents ($url, false,
stream_context_create (
array ('http'=>
array ('method'=>'POST'
, 'header'=>"Connection: close\r\nContent-Length: $data_len\r\n"
, 'content'=>$data_url
))
)
);
print_r(
$result
);
in returnPost.php
print_r($_POST);
精彩评论