Explain Codes LogoExplain Codes Logo

Jquery Ajax POST example with PHP

javascript
ajax
post
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 16, 2024
TLDR

Perform a jQuery Ajax POST request by setting up $.ajax() with object properties comprising type: 'POST', your server script's URL, and a data object. Make use of the success or error callbacks to handle the response from your server.

Here is a bare-bones example:

$.ajax({ url: 'submit.php', type: 'POST', data: { name: 'John', age: 30 }, success: function(res) { console.log(res); }, // When PHP says ok. error: function(err) { console.error(err); } // When PHP says nope. });

Note:

  • Replace name and age with your own field names.
  • In your PHP file, retrieve these data with $_POST['name'], $_POST['age'].

Submitting form data: Who needs page reloads anyway?

Traditional form submission leads to a page reload—yikes. Fortunately, there's event.preventDefault(). This works together with $form.serialize() to bundle up your form's data and hand it over to our Ajax request. And oh, while we’re at it, we disable user inputs during the Ajax request ($inputs.prop("disabled", true)), preventing trigger-happy users from flooding your server.

$('form').on('submit', function(event) { event.preventDefault(); // Stop! In the name of UX! var $form = $(this); // Our form... var $inputs = $form.find('input, select, button, textarea'); // and its children inputs. var serializedData = $form.serialize(); // Bundle them up... $inputs.prop('disabled', true); // Kids, don't touch anything. $.ajax({ url: $form.attr('action'), type: 'POST', data: serializedData, success: function(response) { // Only doing success, because we're optimists ;) }, complete: function() { $inputs.prop('disabled', false); // Alright, playtime! } }); });

Never forget to sanitize posted data in your PHP script using, for instance, filter_input_array(). Better safe than SQL injected!

Making conversation with the server

Interaction needs feedback. $.ajax() allows chaining of the callbacks .done(), .fail(), and .always() for different scenarios—like a virtual handshake between client and server.

$.ajax({ // Your usual settings }).done(function(response) { // JSON says "Welcome Home!" }).fail(function(jqXHR, textStatus, errorThrown) { // JSON says "Wrong door, mate." }).always(function() { // JSON says "It's the journey, not the destination." });

The exchanges with the server are best done in JSON. It's like the Esperanto of data. And while client-side validation is good, having server-side validation is the bouncer who assures only the right folks get in.

We do POST, even with files

Posting file data? Use FormData with $.ajax(), plus, set processData and contentType to false. It’s like sending a parcel instead of a letter.

$('form').on('submit', function(event) { event.preventDefault(); var formData = new FormData(this); $.ajax({ url: 'upload.php', // Your trusted PHP file receiver type: 'POST', data: formData, processData: false, // Don't let jQuery alter your precious FormData contentType: false, // Don't mess with the natural Content-Type either success: function(data) { // The file is in the server! 🎉 }, error: function(data) { // User probably tried to upload a kitchen sink... } }); });

In your PHP script, you catch these uploaded files from the $_FILES array. Validate and sanitize these server-side, because you don't want anyone to upload their "PetRock.jpeg.exe".

Ajax POST best practices

Remember, secure your application by

  • Sending data over HTTPS always to keep sensitive data safe.
  • Defending the application with CSRF tokens. It’s like a secret handshake.
  • Simplify your code and life by favoring $.post() for straightforward requests.
  • Utilizing cache features to repay the user’s patience.