jQuery ajax call json example

<form name="myForm">
    <label>Name* <input type="text" name="name" value="" /></label>
    <label>Location <input type="text" name="location" value="" /></label>
    <label>Email* <input type="text" name="email" value="" /></label>
    <label>Phone <input type="text" name="phone" value="" /></label>
    <div id="return_message" class="error" style="display:none;"></div>
    <label><input type="submit" value="Submit" /></label>
    </form>

<script type="text/javascript">

$('form[name=myForm]').submit(function(){
    $('#return_message').css('display', 'none');
    var url = 'http://www.example.com/ajax.php';
    $.ajax({
        url: url,
        type: 'POST',
        crossDomain: true,
        dataType: 'json',
        data: $("form[name=myForm]").serialize(),
        success: function(data){
            if(data.errors == 'empty_fields') {
                $('#return_message').html(data.message);
                // mark required fields
                $('input[name=name]').addClass('mandatory');
                $('input[name=email]').addClass('mandatory');
                $('#return_message').css('display', 'block');
            }
            else if(data.errors == 'invalid_email') {
                $('#return_message').html(data.message);
                // mark email field
                $('input[name=email]').addClass('mandatory');
                $('#return_message').css('display', 'block');
            }
            else {
                $('form[name=myForm]').html(data.message);
                $('form[name=myForm]').addClass('confirmation');
            }
        }
    });
    return false;
});
</script>

 

Ajax file

<?php
$errors = 'no';

if(empty($_POST['name']) or empty($_POST['email'])) {
    $errors = 'empty_fields';
    $message = "Mandatory fields empty";
}
else if(check_email($_POST['email'])) {
    $errors = 'invalid_email';
    $message = "Email not valid";
}
else {
        $message = "You have successfully subscribed";
}
echo '{
  "errors": "'.$errors.'",
  "message": "'.$message.'"
}';