AJAX stands for Asynchronous JavaScript and XML. AJAX Post used to create faster, and more interactive web applications using javascript, XML. Alternatively we can say that, using ajax, we can exchange data or update of a small portion of web page without reloading the page.

In AJAX post , when we hit submit button, JavaScript makes a request to the server and interpret the results.After manipulating the result it updates the current screen.

Basic Ajax post format

$.ajax({
    url: 'url of the function to intract ',
    dataType: 'json',
    type: 'post',
    contentType: 'application/json',
    data: JSON.stringify( { "nae": $('#name').val(), "mobile": $('#mobile').val() } ),
    processData: false,
    success: function( data, textStatus, jQxhr ){
        $('#response').html( JSON.stringify( data ) );
    },
    error: function( jqXhr, textStatus, errorThrown ){
        console.log( errorThrown );
    }
});

In the below example, we are going to describe, how to make Ajax post  with PHP.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<style>

.success{
border: 1px solid #06ab31;
padding: 5px;
margin-bottom: 1em;
background: #d1e2c4;
text-align: center;
}
.error{
border: 1px solid #ba5e00;
padding: 5px;
margin-bottom: 1em;
background: #ffc0ae;
text-align: center;
}
#form-block{
margin-left: 40%;
margin-top: 10%;
border: 1px solid;
width: 25%;
text-align: center;
padding:1%;
}
.element-block{
margin-bottom:10px;
}
</style>
</head>
<body>

<div id="form-block">
<div id="msg"></div>
<form method="post" name="postForm">
<div class="element-block">
<label>User name</label>
<input type="text" name="username" id="username" placeholder="Type user name">
</div>
<input type="button" value="Submit" id="submit" />
</form>
</div>
<script>
$(document).ready(function() {
$('#submit').click(function(event) {
$('#username').empty();
$('#msg').text('');
var postForm = {
'username' : $('input[name=username]').val()
};
$.ajax({
type : 'POST',
url : 'execute.php',
data : postForm,
dataType : 'json',
success : function(data) {

if(data.success==true){
$('#msg').removeClass('error');
$('#msg').addClass('success');
$('#msg').text(data.msg);

}else{
$('#msg').removeClass('success');
$('#msg').addClass('error');
$('#msg').text(data.msg);
}

},error: function(data) {
alert(data);
}

});
});
});
</script>
</body>
</html>


The execute.php file

<?php

$errors = array();
$data = array();

if (empty($_POST['username'])) {
$errors = 'User name cannot be blank';
}

if (!empty($errors)) {
$data['success'] = false;
$data['msg'] = $errors;
}

else {
$data['success'] = true;
$data['msg'] = 'Record inserted Successfully';
}

echo json_encode($data);
?>

Leave comment

Your email address will not be published. Required fields are marked with *.