jQuery + AJAX + PHP: Part 1: Getting a Response

jQuery + AJAX + PHP


Some Terms

jQuery: a client-side JavaScript library for DOM tree traversal, event handling, and using AJAX.

AJAX (sometimes written as Ajax): Originally “Asynchronous JavaScript And XML,” the term has come to encompass all asynchronous requests and reactions by web applications.

PHP (PHP: Hypertext Preprocessor): a generic programming language designed and frequently used for sever-side web development.

Development Recommendations

While external hosting can certainly be used for going through these materials, it is highly recommended to either setup a local, testing PHP web server or using something like the php-server package in Atom for creating a developmental server.

Loading jQuery

jQuery provides a $.ajax() function that serves as a shorthand for browser functionality to send asynchronous requests to a server. Depending on the options used, different responses can be received, parsed, or used in various ways. However, by default, all responses are assumed to be text.

As a JavaScript library, jQuery can also be loaded as part of the HTML HEAD or, as is more common, at the bottom of the BODY. (In this example, it is loaded as part of the HEAD for convenience.)

Calling $.ajax()

Once loaded, the $.ajax() function can be called. (The options used will be covered in more depth in the next part.)

Server PHP

On the server side, a file named “response.php” (matching the file requested in the Ajax call) is created. For this example, it merely echos back one of the values passed to it from the same call.

Getting a Response

Assuming everything worked correctly, the function .done() as part of the $.ajax() call will receive the message sent by the server. (Echoing the values passed to it.)

Finally, it will change the text content of the element with the ID “log”.

Example Code