InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Responding to an Ajax Request in PHP
PHP

Responding to an Ajax Request in PHP

InfinityCoder December 17, 2016

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

Set an appropriate Content-Type header and then emit properly formatted data. Example 13-16 sends a small XML document as a response.
Example 13-16. Sending an XML response

1
2
3
4
5
<?php header('Content-Type: text/xml'); ?>
<menu>
<dish type="appetizer">Chicken Soup</dish>
<dish type="main course">Fried Monkey Brains</dish>
</menu>

Example 13-17 uses the json_encode() function to send a JSON response.
Example 13-17. Sending a JSON response

1
2
3
4
5
6
7
$menu = array();
$menu[] = array('type' => 'appetizer',
                'dish' => 'Chicken Soup');
$menu[] = array('type' => 'main course',
                'dish' => 'Fried Monkey Brains');
header('Content-Type: application/json');
print json_encode($menu);

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 responses, because it’s super easy to deal with the JSON-formatted data from within JavaScript.

The output from Example 13-17 looks like this:

1
2
[{"type":"appetizer","dish":"Chicken Soup"},
{"type":"main course","dish":"Fried Monkey Brains"}]

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 responses, it’s also important to pay attention to caching. Different browsers have a creative variety of caching strategies when it comes to requests made 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 are headers and URL poisoning.

Example 13-18 shows the full complement of anti-caching headers you can issue from PHP to prevent a browser from caching a response.
Example 13-18. Anti-caching headers

1
2
3
4
5
6
7
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
// Add some IE-specific options
header("Cache-Control: post-check=0, pre-check=0", false);
// For HTTP/1.0
header("Pragma: no-cache");

The other anti-caching tool, URL poisoning, requires cooperation from the JavaScript that is making the request. It adds 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 Java‐ Script Math.random() function is useful for generating these values.

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Retrieving Rows Without a Loop in PHP
You want a concise way to execute a query and …

Retrieving Rows Without a Loop in PHP

Requiring Multiple Classes to Behave Similarly in PHP
You want multiple classes to use the same methods, but …

Requiring Multiple Classes to Behave Similarly in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

    Categories

    • Bash
    • PHP
    • Python
    • Uncategorized

    InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

    About Us

    Start learning your desired programming language with InfinityQuest.com.

    On our website you can access any tutorial that you want with video and code examples.

    We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

    Popular Tags

    binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

    Archives

    • June 2017
    • April 2017
    • February 2017
    • January 2017
    • December 2016
    • November 2016
    Copyright © 2019 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
    Programming Tutorials | Sitemap