views:

454

answers:

5

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.

+3  A: 

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);
RageZ
+2  A: 

The easiest method would be the command line tool curl, especially if you have a sample of the data you want to post.

brianegge
+2  A: 

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());
just somebody
@just somebody: +1 really like the nice snippet. if you add the cdb of google for jquery I would be really happy. http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
RageZ
I want to implement the client using PHP, not javascript.
tputkonen
Yup nice snippet. Would be better to add a <pre> to the body and then $('pre').append(data); inside the callback function.
phidah
A: 

An even quicker guide with example to use jQuery.post(): http://docs.jquery.com/Post

Joy Dutta
+2  A: 

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.

Boldewyn