jQuery Ajax POST example with PHP

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

1
2
3
4
5
6
7
8
9
10
11
<form method="post" name="postForm">
    <ul>
        <li>
            <label>Name</label>
            <input type="text" name="name" id="name" placeholder="Bruce Wayne">
            <span class="throw_error"></span>
            <span id="success"></span>
       </li>
   </ul>
   <input type="submit" value="Send">
</form>

Validate the form using jQuery client-side validation and pass the data to process.php.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$(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('<p>' + data.posted + '</p>'); //If successful, than throw a success message
                                }
                            }
        });
        event.preventDefault(); //Prevent the default submit
    });
});

Now we will take a look at process.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$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