Full jQuery Ajax Post PHP Example

Welcome to a quick and easy demonstration of using JQuery Ajax Post With PHP

Objective: Send data to a MySQL database using jQuery Ajax Post method, and receive data back from the PHP page.

First we setup a basic bootstrap HTML page, although for this example, were not really getting into designing a great website. By keeping it simple, we should be able to see a clearer picture of the techniques used.

HTML PAGE (index.html or index.php)

Next comes our Javascript & jQuery, because we want our Ajax post to happen after the DOM has loaded we wrap our code in the jQuery document ready function as below.

For this example our data is just a static object containing  name and age properties but this data could come from anything such as a form input.

Notice: The .success(), .error(), and .complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, we use .done(), .fail(), and .always() instead.

Line: 14 stores our response to our request in the variable ‘returnedData’ which is parsed with JSON.parse. This response comes back from our PHP page.

lines 15 & 16 simply show how we can then access that data using javascript objects. This output is then sent to the console purely for demonstration.

Javascript (file Name: ajax.js)

CSS Optional (styles.css)

Our PHP page first opens a connection to the MySQL database using the PDO method & then prepares an INSERT MySQL statement using bindValue and bindParam.

We can access our Ajax data using the $_POST array with the keys given in our object (name & age).

Whatever is echoed out from our PHP page to the screen is what will be returned to our Ajax call in the response parameter. We encode this output as JSON so we can easily extract the data back in our javascript page.

PHP Processing Page (ajaxPost.php)

To help setup our ‘users’ database, here is the SQL needed to create the ‘people’ table that holds our data.
To create it simply run the following code in an sql window within phpMyAdmin.

SQL to create backend database

Now when ever we refresh the page, our data in our javascript page is sent via Ajax to the php page, and the php page stores the name and age in our database, the PHP page also returns the same data and we access that data  using JSON and send it to the console for demonstration purposes.

Hope you enjoyed the tutorial.

Please follow and like us:

Paul Brown

43 Year Old Web Developer

Leave a Reply

Your email address will not be published. Required fields are marked *