Skip to content

Instantly share code, notes, and snippets.

@rohankhudedev
Last active October 6, 2020 18:02
Show Gist options
  • Save rohankhudedev/efb813ce6b8204dc86c5841f615ae530 to your computer and use it in GitHub Desktop.
Save rohankhudedev/efb813ce6b8204dc86c5841f615ae530 to your computer and use it in GitHub Desktop.
submit form using simple ajax using post method
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).on('submit','form#smsform',function(e){
e.preventDefault();
var formID = $( this ).attr( 'action' );
$.ajax({
type: 'POST',
url: formID,
data: $(this).serialize(),
beforeSend: function () {
// show that something is loading
$('.modal-header').removeClass('alert alert-success alert-danger alert-warning');
$('.modal-title').html(loaderTxt);
$('.close-btn').css('display', 'none');
$(".modal").modal('show');
},
success: function (response) {
$('.modal-header').addClass('alert alert-success');
$('.modal-title').html(successTitle);
$('.close-btn').css('display', 'none');
$(".modal").modal('show');
//reload active datatable
},
error: function (response) { // if error occured
$('.modal-header').addClass('alert alert-danger');
$('.modal-body').html(response.responseJSON);
$(".modal").modal('show');
},
complete: function () {
},
});
// to prevent refreshing the whole page page
return false;
});
</script>
</head>
<body>
<form id="smsform" action="process_ajax_request.php">
<input type="tel" id="mobile_no" name="mobile_no" pattern="\d{10}$" title="XXXXXXXXXX" required/>
<input type='submit' name="submit" value='Submit' />
<div id='response'></div>
</form>
</body>
</html>
<?php
if( $_SERVER['REQUEST_METHOD'] === "POST" )
{
if( isset($_POST['submit']) )
{
//process request
// this will be response to ajax
echo "success";
//200 will invoke success() part of ajax
http_response_code(200);
}
else
{
// this will be response to ajax
echo "this is bad request";
//200 will invoke fail() part of ajax
http_response_code(400);
}
}
else
{
// this will be response to ajax
echo "not authorized for this";
//200 will invoke fail() part of ajax
http_response_code(403);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment