Last updated on January 10th, 2023 at 12:21 pm

Simple script whicg uses jquery and ajax to submit form values from a basic HTML to a php server side script using jquery.ajax(),
For that we need to create HTML web page with a simple login form

Table of Contents

HTML Form

The div tag has a message stating “Loading Please Wait“, You can even add a gif image with loading animation instead of this text message inside the div. It will look something like this, div with the id response will get updated with value returned from the php web page.

<div id="loading" style="display:none;border: 1px dashed black; width: 800px; height: 100px;font-family: Times New Roman, Times, serif;color:#D3D3D3;font-size:70px;text-align:center"><img src="loading.gif"></div>
 
<input id="username" type="text" value="test" />
<input id="password" type="password" value="testpass123" />
<input id="mysubmit" type="submit" value="submit">
<div id="response"></div>

Add Jquery with Ajax

Next step is to add the jquery details so that when the user click Submit button it will initiate the respective function and send the request to the PHP web page using Ajax.

<script
  src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#mysubmit").click(function(){
var loading = $("#loading");
 
$(document).ajaxStart(function () {
loading.show();
});
 
$(document).ajaxStop(function () {
loading.hide();
});
var name = $("#username").val();
var password = $("#password").val();
var uploadFormData = "username="+name+"&password="+password;
alert(uploadFormData)
$.ajax({
type: "POST",
url: "/jquery_ajax_show_value.php",
data: uploadFormData,
success:function(ret)
{
document.getElementById("response").innerHTML = ret;
},
error: function(ret)
{
alert("Error"+ret);
}
});
});
});
</script>

The value from input tag with the id USERNAME and PASSWORD will be passed to the variable named uploadFormData when a user hit submit button.

More details on ajaxStart and ajaxStop. As the name suggests ajaxStart is called when the Ajax requests begin and ajaxStop is called when the Ajax request is completed.

$("#mysubmit").click(function(){
var loading = $("#loading");
  
$(document).ajaxStart(function () {
loading.show();
});
$(document).ajaxStop(function () {
loading.hide();
});

Using these methods we are displaying and hiding Loading image / String while the Ajax request is in progress. As you can see above we are getting the div id named loading and manipulating it accordingly using the ajaxStart and ajaxStop function .

My php code is very simple and it displays the username and password.

<?php
echo "Passed UserName is $_POST['username'] & Password is $_POST['password']";
?>

This is returned back to the main webpage and is displayed using

document.getElementById("response").innerHTML = ret;

DEMO

Leave a Reply

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