Display 'loading' image when AJAX call is in progress - javascript

I have the following jQuery Ajax call:
$.ajax({
type: "POST",
url: "addtobasket.php",
data: "sid=<?= $sid ?>&itemid=" + itemid + "&boxsize=" + boxsize + "&ext=" + extraval,
success: function(msg){
$.post("preorderbasket.php", { sid: "<?= $sid ?>", type: "pre" },
function(data){
$('.preorder').empty();
$('.preorder').append(data);
});
}
});
I want to display an image when the ajax call is in progress. How can I do that?
Thanks,

try this :
<script type="text/javascript">
$(document).ready(function()
{
$('#loading')
.hide()
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
});
</script>
<div id="loading">
Loading....
</div>
This will show the loading image each time you are doing an ajax request, I have implented this div at the top of my pages, so it does not obstruct with the page, but you can always see when an ajax call is going on.

Something along these lines (showLoadingImage and hideLoadingImage are up to you):
// show the loading image before calling ajax.
showLoadingImage();
$.ajax({
// url, type, etc. go here
success: function() {
// handle success. this only fires if the call was successful.
},
error: function() {
// handle error. this only fires if the call was unsuccessful.
},
complete: function() {
// no matter the result, complete will fire, so it's a good place
// to do the non-conditional stuff, like hiding a loading image.
hideLoadingImage();
}
});

You can display the image just before this call to $.ajax() and then hide/remove the image in the post handler function (just before your .empty()/.append(data) calls.

It works. I have tested it.
<script type='text/javascript'>
$(document).ready(function(){
$("#but_search").click(function(){
var search = $('#search').val();
$.ajax({
url: 'fetch_deta.php',
type: 'post',
data: {search:search},
beforeSend: function(){
// Show image container
$("#loader").show();
},
success: function(response){
$('.response').empty();
$('.response').append(response);
},
complete:function(data){
// Hide image container
$("#loader").hide();
}
});
});
});
</script>
<input type='text' id='search'>
<input type='button' id='but_search' value='Search'><br/>
<!-- Image loader -->
<div id='loader' style='display: none;'>
<img src='reload.gif' width='32px' height='32px'>
</div>
<!-- Image loader -->
<div class='response'></div>

Related

ajax is loading both divs on the page instead of specified div

I have a PHP page with the following two divs, and I am trying to load the content with a click event here and then conditional:
if (ballResult == 'W') { // processing wide
$.ajax({
url: "loads/scorer_soft_load.php #extrWideLoad",
cache: false,
success: function(html) {
$("#scoreBt").html("");
$('#scoreBt').append(html);
}, // call back function after ajax request complete
complete: function() {
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="extraScoreLoad">
<h3 class="g-m-u-heading" id="extrHeading"><span class="badge badge-secondary">Any extra</span></h3>
<button>nb</button>
</div>
<!------load for wide-------->
<div id="extrWideLoad">
<h3 class="g-m-u-heading" id="extrHeading"><span class="badge badge-secondary">Any extra</span></h3>
<button>w</button>
</div>
I am doing the same for the other div just changing the URL to loads/scorer_soft_load.php #extraScoreLoad.
url: "loads/scorer_soft_load.php #extrWideLoad"
You're trying to apply a selector in the URL. (Not to be confused with a fragment identifier.) URLs don't really work like that. It's going to return all of the content, you'd need to apply a selector after you receive the content. For example:
$.ajax({
url: "loads/scorer_soft_load.php",
cache: false,
success: function(html){
$("#scoreBt").html("");
var filteredHtml = $('#extrWideLoad', html); // <--- here
$('#scoreBt').append(filteredHtml);
}
});
i have use this technique with .load and it have worked in past.
That's because .load() does this client-side selector logic for you.

Add javascript function to wordpress page

I have a page that locates a link inside it and when that link is clicked it should save some data in database.
Besides, I have a file named "add.php" that communicates with the DB and operates well.
In my wordpress page I have added below codes for accessing the add.php file and send some parameters to it.
<a href="javascript:add(true);" >Click Me</a>
<script type="text/javascript">
function add(b){
$(document).ready(function(){
var result = $.ajax({
type: "POST",
url: "add.php",
data: { add: b }
});
result.done(function(msg) {
alert(msg);
});
result.fail(function(jqXHR, textStatus) {
alert( "No such data exists: " + textStatus );
});
});
}
</script>
I had this exact code in an html file and it worked smoothly. but it doesn't work on wordpress page like that.
Plus, the problem is that when I click the link -Click Me- it doesn't do anything.
please tell me where the problem is and how to solve it ?
I would recommend you to use this:
<a href="#" data-add="true" class='hitClick'>Click Me</a>
<!--use data* attributes to pass specific data -->
now in your function:
function add() {
event.preventDefault(); //<------make sure to add it.
var result = jQuery.ajax({
type: "POST",
url: "add.php",
data: {
add: jQuery(this).data('add')
}
});
result.done(function(msg) {
alert(msg);
});
result.fail(function(jqXHR, textStatus) {
alert("No such data exists: " + textStatus);
});
}
jQuery(document).ready(function(){
jQuery('.hitClick').on('click', add); // bind the click and use as callback
});

Images does not show immediately after ajax load

I'm using an Ajax for partial loading my website. Content of GET data has images but these images appear after few seconds on page. Image size is about 20kB, so this is not a bottleneck.
I'm using php page which returns some content. This page loads in a while with images immediately but with ajax it loads text, but images after few seconds. How can I achieve quick load?
I'm using this function:
function loadMainEvents(resultDiv, cat, limit){
var spinner = new Spinner().spin(mainPageEvents);
$.ajax({
url: "/getMainPageEvents.php?category=" + cat + "&limit=" + limit,
type: "GET",
success: function(data){
resultDiv.innerHTML = data;
spinner.stop();
}
});
};
EDIT:
I created a test.php which is doing same thing
<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js' type="text/javascript"></script>
</head>
<body>
<div id="div" style="float:left;">wait</div>
<div id="div2">wait</div>
<script>
$(function () {
$.ajax({
url: "/getMainPageEvents.php?category=&limit=10&from=29.11.2015&to=29.11.2015&pno=1",
type: "GET",
success: function (data) {
$("#div").html(data).on('load', function () {
$(this).fadeIn(250);
});
}
});
$.ajax({
url: "/getMainPageEvents.php?category=&limit=10&from=29.11.2015&to=29.11.2015&pno=1",
type: "GET",
success: function (data) {
$("#div2").html(data).on('load', function () {
$(this).fadeIn(250);
});
}
});
});
</script>
</body>
getMainPageEvents.php returns only web content.
Network from developer tools:
You may want to try something like this in the success function. Hide the result div first and foremost, then after the data is loaded, show the div.
$(resultDiv).html(data).promise().done(function(){
spinner.stop();
$(this).fadeIn(250);
});
Possible second solution
$(resultDiv).html(data).on('load', function(){
spinner.stop();
$(this).fadeIn(250);
});

Jquery method executed several time

I'm trying to implement simple Comet chat example and for this I implemented Long polling which calls itself recursively every 30 seconds.
When pressing on button I want another ajax request to send new data on Server using POST.
For now I just put alert to this function to trigger click event
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
var polling = function poll(){
$("#postMessage").click(function () {
alert("request");
});
$.ajax({ dataType: 'json',url: "CometServlet", success: function(data){
if (data !=null){
$('#message').append(data.sender+" : " + data.message+"<br />");
}
}, complete: poll, timeout: 30000 });
}
$(document).ready(polling)
</script>
And my HTML is like this:
<div>
<input type="button" id="postMessage" value="post Message">
</div>
<div id ="message" name="message"></div>
When I click on button my alert is shown several times. Why? How can I solve it?
As Dave mentions, that's not what the timeout option is for. Try something using setTimeout instead. Also, you're mixing your polling logic and your click handler (I think). Here's how you would separate them:
function poll() {
$.ajax({
dataType: 'json',
url: "CometServlet",
success: function(data){
if (data !=null){
$('#message').append(data.sender+" : " + data.message+"<br />");
}
},
complete: function () {
setTimeout(poll, 30000);
}
});
}
$(document).ready(function () {
$("#postMessage").click(function () {
alert("request");
});
poll();
});
Example: http://jsfiddle.net/VyGTh/
In your code after every Ajax call you re-bind click event to #postMessage and that's why you had couple of alert messages. You need to bind click only once in page load. You can fix it by doing something like:
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
var polling = function poll(){
$.ajax({ dataType: 'json',url: "CometServlet",
success: function(data){
if (data !=null){
$('#message').append(data.sender+" : " + data.message+"<br />");
}
},
complete: poll,
timeout: 30000
});
}
$(document).ready(function(){
// Now Click only binds one time
$("#postMessage").click(function () {
alert("request");
});
polling();
});
</script>

Search box in a jQuery ajax success page - issues in loop

Firstly, there have some tag links in my main page. click each one, post value to b.php with jquery.ajax and turn back value in div#result.
b.php have a search box. when search something in it. the result data will still show in the div#result.
my problem is: I know if I will do jQuery ajax in the b.php, I shall write the jQuery code in the first success part. but this only can control one time, when I continue search in the search box, the jQuery not work. I think I met a loop problem. How to solve it?
a.php
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.click').click(function(){
var value1 = $(this).text();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value1,
success: function(data){
$("#result").html(data);
$('#search').click(function(){
var value = $('#search1').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value,
success: function(data){
$("#result").html(data);
}
});
});
}
});
});
});
</script>
<a rel="aa" class="click">aa</a>
<a rel="aa" class="click">bb</a>
<div id="result"></div>
b.php
<?php
echo $_POST['data'];
?>
<form name="form">
<input type="text" value="" id="search1">
<a name="nfSearch" id="search">search</a>
</form>
When a new element is introduced to the page the jQuery .click() method becomes useless because it can only see elements that were part of the original DOM. What you need to use instead is the jQuery .live() method which allows you to bind events to elements that were created after the DOM was loaded. You can read more about how to use it at the below link.
.live() – jQuery API
$('#search').live('click', function(e) {
// Prevent the default action
e.preventDefault();
// Your code here....
});
First of all i think you should attach the ajax call to the click on the link: the way you are doing right now just execute an ajax call as soon as the page is loaded.
$(document).ready(function(){
//when you click a link call b.php
$('a.yourclass').click(function(){
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data = something",
success: function(data){
$("#result").html(data);
var value = $('#search').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data =" + value,
success: function(data){
$("#result").html(data);
}
});
}
});
});
});
In this way, each time a link with the class of "yourclass" is clicked an ajax call to b.php is sent and if it succed, another call is made (always to b.php). I don't understand if this is what you are looking fo, if you post your html my answer can be better.
In b.php of course you need to echo some html that can be used in the callback
It's strange how your attempting to do two ajax requests like that, surely one is enough. If you need to support multiple text boxes then you just adjust your selectors.
Your whole code can be shortended down to something like this:
$(document).ready(function() {
$('#result').load('b.php', { data: $('#search').val() });
});
So if you wanted to search for the value when clicking on a link (for links within #container):
$('#container').delegate('a', 'click', function() {
// .text() will get what's inside the <a> tag
$('#result').load('b.php', { data: $(this).text() });
});

Categories