Jquery Ajax POST example with PHP
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:
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.
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.
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.
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.
Was this article helpful?