Solution for : jQuery Ajax POST example with PHP
I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.
First of all, create two files, for example form.php
and process.php
.
We will first create a form
which will be then submitted using the jQuery
.ajax()
method. The rest will be explained in the comments.
form.php
Validate the form using jQuery client-side validation and pass the data to process.php
.
$(document).ready(function() { $('form').submit(function(event) { //Trigger on form submit $('#name + .throw_error').empty(); //Clear the messages first $('#success').empty(); //Validate fields if required using jQuery var postForm = { //Fetch form data 'name' : $('input[name=name]').val() //Store name fields value }; $.ajax({ //Process the form using $.ajax() type : 'POST', //Method type url : 'process.php', //Your form processing file URL data : postForm, //Forms name dataType : 'json', success : function(data) { if (!data.success) { //If fails if (data.errors.name) { //Returned if any error from process.php $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error } } else { $('#success').fadeIn(1000).append('' + data.posted + '
'); //If successful, than throw a success message } } }); event.preventDefault(); //Prevent the default submit }); });
Now we will take a look at process.php
$errors = array(); //To store errors $form_data = array(); //Pass back the data to `form.php` /* Validate the form on the server side */ if (empty($_POST['name'])) { //Name cannot be empty $errors['name'] = 'Name cannot be blank'; } if (!empty($errors)) { //If errors in validation $form_data['success'] = false; $form_data['errors'] = $errors; } else { //If not, process the form, and return true on success $form_data['success'] = true; $form_data['posted'] = 'Data Was Posted Successfully'; } //Return the data back to form.php echo json_encode($form_data);
No comments:
Post a Comment