Website Scripts And Cloud Tutorials

Jquery display loading image during ajax call

Byadmin

Sep 30, 2014 , ,

Last updated on February 26th, 2022 at 03:59 pm

Click to rate this tutorial!
[Total: 1 Average: 3]

Simple script that 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

<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">Loading Please Wait....</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>

The div tag above 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>

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="http://code.jquery.com/jquery-1.9.1.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.

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

Click to rate this tutorial!
[Total: 1 Average: 3]

Leave a Reply

Your email address will not be published.