Ajax form submission with PHP.

This is a basic tutorial on how to create an Ajax form that submits POST data to a PHP script. For this example, we will setup two files:

  1. The web page that displays our form.
  2. The PHP script that receives our form data via Ajax.

Note: If you are completely new to the concept of Ajax requests, then you should probably check out my tutorial on Ajax requests with JQuery, as it provides a basic introduction to the topic.

Our example web page, which contains the form and Ajax submission script:

An explanation of the code above:

  1. We created a basic HTML form that allows users to submit their email address. Note that we gave our form element the ID “my_form_id” and that we gave our text field the ID “email”. When you are using JavaScript and JQuery, it is extremely beneficial to give your HTML elements a unique ID, simply because it makes it easier to access them.
  2. We included the JQuery library from the JQuery CDN.
  3. In our custom JavaScript, we place our code inside the document ready function, simply because we do not want our JS to be executed until the page has been properly loaded.
  4. We attach an event handler onto our form element. This event handler will be called whenever the user attempts to submit the form (when they hit enter or click on the submit button). Note how we referenced our form by its ID, which is “my_form_id”.
  5. Once the user has attempted to submit the form, we prevent the default event / behavior from taking place. Remember that the default behavior of a web form is to direct itself to the action URL. When the action URL is not specified (like in our example), it will attempt to submit itself to the current page. We do not want to this happen, as it will reload the page and prevent our Ajax request from being executed.
  6. We grab the value that the user has entered into the email text field (we reference this text field by its ID).
  7. We execute a POST Ajax request to our submission script, which is aptly-named submission.php

If you run the example above, you’ll see that the form is submitted via Ajax and that our JavaScript alerts the output that it received from our PHP script.

Our PHP file.

Our PHP file (we called it submission.php) that processes the form data is pretty straight forward:

Basically, it takes in the POST value that we submitted via Ajax before printing it out. Our Ajax script will receive this output as soon as the request has been completed.

Obviously, your PHP script will probably be a little more complex, as it could be sending an email or inserting data into a database.

Hopefully, this tutorial has pointed you in the right direction!

Comments

comments