I'm looking for an example how to emulate XMLHttpRequest client using PHP.
In other words, send the request over HTTP POST message, and receive and process the callback message.
I'm looking for an example how to emulate XMLHttpRequest client using PHP.
In other words, send the request over HTTP POST message, and receive and process the callback message.
you can use curl for that purpose
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// set the post
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,array( 'foo' => 'bar'));
// grab URL and pass it to the browser
$result = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
var_dump($result);
The easiest method would be the command line tool curl
, especially if you have a sample of the data you want to post.
server.php:
<?php var_dump($_POST);
client.html:
<html>
<head>
<title>omg</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function ()
$.post(
"server.php"
, {omg: "wtf"}
, function (data) { alert(data); }
);
);
</script>
</head>
<body></body>
</html>
edit: ok, so it's http client written in PHP!
<?php
$r = new HTTPRequest("server.php", HTTP_METH_POST);
$r->addPostFields(array('omg' => 'wtf'));
$r->send();
var_dump($r->getResponseCode());
var_dump($r->getResponseBody());
An even quicker guide with example to use jQuery.post()
: http://docs.jquery.com/Post
If you want to 'really' simulate an AJAX request, you should, together with all of the above solutions, consider sending this header with your request:
X-Requested-With: XMLHttpRequest
(check the manuals to the solutions how to set custom headers). Prototype, jQuery, mootools and the such all send this header when they request data via AJAX.