Responding to an Ajax Request

You're using JavaScript to make in-page requests with XMLHTTPRequest and need to send data in reply to one of those requests.

Posted on February 3, 2016 in PHP

From a purely PHP perspective, sending a response to an XMLHTTPRequest-based request is no different than any other response. You send any necessary headers and then spit out some text. What’s different, however, is what those headers are and, usually, what the text looks like.

JSON is a particularly useful format for these sorts of response, because it’s super easy to deal with the JSON-formatted data from within JavaScript. Some example JSON contents like:

[{"type":"appetizer", "dish":"Chicken Soup"}, {"type":"main course", "dish":"France Fries"}]

This encodes a two-element JavaScript array of hashes. The json_encode() function is an easy way to turn PHP data structures (scalars, arrays, and objects) into JSON strings and vice versa. This function and the complementary json_decode() function turn PHP data structures to JSON strings and back again.

With these types of response, it’s also important to pay attention to caching. Different browsers have a creative variety of caching strategies when it comes to requests mad from within JavaScript. If your responses are sending dynamic data (which they usually are), you probably don’t want them to be cached. The two tools in your anti-caching toolbox area headers and URL poisoning. Following code shows the full complement of anti-caching headers you can issue from PHP to prevent a browser from caching a response.

header("Last-Modified: ". gmdate("D, d M Y H:i:s"). " GMT");<br>
header("Cache-Control: no-store, no-cache, must-revalidate");<br>
header('Cache-Control: post-check=0,pre-chech=0", false);<br>
header('Pragma: no-cache");<br>

The other anti-caching tool, URL poisoning, requires cooperation from the JavaScript that is making the request. It add a name/value pair to the query string of each request it makes using an arbitrary value. This makes the request URL different each time the request is made, preventing any misbehaving caches from getting in the way. The JavaScript Math.random() function is useful for generating these values.

comments powered by Disqus