how to create an ajax post with a response with php code example
Example 1: jquery ajax post
var request;
$("#foo").submit(function(event){
event.preventDefault();
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
console.log("Hooray, it worked!");
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
request.always(function () {
$inputs.prop("disabled", false);
});
});
Example 2: ajax project using php and jquery
<script>
var objXMLHttpRequest = new XMLHttpRequest();
objXMLHttpRequest.onreadystatechange = function() {
if(objXMLHttpRequest.readyState === 4) {
if(objXMLHttpRequest.status === 200) {
alert(objXMLHttpRequest.responseText);
} else {
alert('Error Code: ' + objXMLHttpRequest.status);
alert('Error Message: ' + objXMLHttpRequest.statusText);
}
}
}
objXMLHttpRequest.open('GET', 'request_ajax_data.php');
objXMLHttpRequest.send();
</script>