Ajax program is not running as I expect - php

Ajax program is not running as I expect. See the code
$(document).ready(function(){
$("input").keyup(function() {
for(var i=400;i<421;i++){
(function(counter){
counter=String(counter);
$.ajax({
type: "GET",
url: "results/result_html.php?usn="+txt+counter+"&resultType="+resultType,
dataType:"JSON",
success:function(result){
$("#info").hide();
$("#result").html(result);
$("#usn").attr("placeholder", "Class USN");
}
});
})(i);
}
alert("hai");
});});
In this code I want to show the alert after completing all Ajax request which is in that for loop. But when I run this code alert is showing first. I'm new to Ajax please can anyone help me to run as I expected.

Ajax is Asynchronous which means, it will continue running the code in parallel. The success function is called after the Ajax request is complete. What you can do is this:
$(document).ready(function(){
$("input").keyup(function() {
var loopsToDo = 20, done=0;
for(var i=400;i<421;i++){
var counter=String(i);
$.ajax({
type: "GET",
url: "results/result_html.php?usn="+txt+counter+"&resultType="+resultType,
dataType:"JSON",
success:function(result){
$("#info").hide();
$("#result").html(result);
$("#usn").attr("placeholder", "Class USN");
},
complete : function(){
done++;
if( done == loopsToDo)
{
alert("DONE")
}
}
});
}
});});

Your code is weird. Why does it go
for(var i=400;i<421;i++)
Also, the alert will display first before any of the Ajax calls, because ajax is Asynchronous, meaning it runs seperately to the rest of the code. Since you are running 20 Ajax requests, the alert does not wait for all 20 to complete. What you need to do is keep a count of the Ajax calls in your success part and when that equals 20 then display an alert.

Because AJAX calls are asynchronous, it will set up the AJAX call, then continue to execute the script. The 'success' parameter specifies the callback to use once a response is received - which could happen at any time (hence, asynchronous).
$(document).ready(function(){
$("input").keyup(function() {
for(var i=400;i<421;i++){
(function(counter){
counter=String(counter);
$.ajax({
type: "GET",
url: "results/result_html.php?usn="+txt+counter+"&resultType="+resultType,
dataType:"JSON",
success:function(result){
$("#info").hide();
$("#result").html(result);
$("#usn").attr("placeholder", "Class USN");
alert("hai");
}
});
})(i);
}
});
});
That should solve your problems.

Related

Block ajax script execution before the previous call succeeded

I have a button that executes an ajax function.
Sometimes the server lags so maybe an user presses it more times, thinking the first time it didn't work...
The main ajax function looks like this:
$.ajax({
type: "POST",
url: "page.php",
dataType: "html",
data:"data=data",
success: function(){
ajax2();
ajax3();
}
});
Since that ajax function updates db and makes others 2 ajax functions i need to block the button from remake the main ajax func...
Only when ajax2() and ajax3() are finished, the button, if pressed, must remake the ajax function.
Hope to have explained well my problem!
disable the button and then reenable it when the 2 ajax are finished
/// the click event
$('yourbutton').prop("disabled",true);
/// show a loading or something....
$.ajax({
type: "POST",
url: "page.php",
dataType: "html",
data:"data=data",
success: function(){
var ajax1 = ajax2();
var ajax2 = ajax3();
$.when(ajax1,ajax2).done(function(risp1,risp2){
console.log(risp1,risp2);
$('yourbutton').prop("disabled",false);
/// hide the loading
});
}
});
read this for more info
Try this
//before this ajax call disable button
$.ajax({
type: "POST",
url: "page.php",
dataType: "html",
data: "data=data",
success: makeAjaxCalls
});
function makeAjaxCalls() {
var a1 = ajax2();
var a2 = ajax3();
$.when(a1, a2).done(function () {
//enable your button here
});
}
Unbind the event listener when it's activated the first time :
custom_ajax_handler = function(){
$('#mybutton').unbind('click'); //won't intercept event from now on.
//here is your ajax call.
ajax2();
ajax3();
}
$('#mybutton').click(custom_ajax_handler);
Then in ajax3 success rebind it :
success : function(){
$('#mybutton').click(custom_ajax_handler);
}
Note that you probably shouldn't make that much ajax calls.
Or at least that doing so won't help your server with its lags.

Jquery Stop Load and Clear Interval

I'm using jquery to load an external page and display it in a DIV called View.
I have 2 buttons Go & Stop.
This is working, but when I click stop it can take a few seconds.
Any way to make it stop straight away ?
$("#Go").click(function () {
$("#view").load("test.php");
refreshId = setInterval(function() {
$("#view").load("test.php"); }, 1000);
});
$("#Stop").click(function () {
clearInterval(refreshId); $("#view").stop();
$.ajax({ url : 'new.php' });
} });
Thanks :)
you can try:
var xhr = $.ajax({
type: "POST",
url: "test.php",
data: "name=John&location=Boston",
success: function(msg){
$("#view").html(msg);
}
});
and stop call:
//kill the request
xhr.abort()

How to show Loading message instantly while using jquery ajax?

Below is my Ajax code I have made using jQuery Ajax method.
$(".loading_msg").show();
$.ajax({
type: "POST",
url: "submit_ops.php?action=submit_form",
data: $( "#frmMyForm" ).serialize(),
success: function(result){
if(result=='Success'){
$("#msgContainer").html('<div style="color:#3CA322;font-weight:bold;font-size:14px;padding:10px;">Thank you.</div>');
$("#msgContainer").fadeIn();
}
else{
$("#msgContainer").html('<div style="color:red;font-size:12px;padding:10px;">' + result + '</div>');
$("#msgContainer").fadeIn();
}
},
error: function(){
//console.log('error');
},
complete: function(){
//console.log('complete');
$(".loading_msg").hide();
$("#submit").attr("disabled", false);
}
});
So the logic is, whenever the Ajax request is about to made,
the .login_msg container is displayed first
then ajax call made
and when it is completed, again the .loading_msg is hidden.
Now the problem, it is not working smoothly as it should be. So when the ajax call is made, the browser hangs for a seconds but it doesn't show the loading message. But when the request is completed, the login message appears like for half a second and then it goes away as I have set it hidden on request completion.
So I want that the .login_msg should be shown before the request is made.
Any suggestions for this? Thanks in advance.
try using beforeSend and complete settings of $.ajax:
$.ajax({
type: "POST",
url: "submit_ops.php?action=submit_form",
data: $( "#frmMyForm" ).serialize(),
beforeSend:function(){
$(".loading_msg").show();
}
complete:function(){
$(".loading_msg").hide();
}
....
....
});

jquery setinterval time with ajax

I want to auto refresh "result" div with ajax & setInterval function.
But there is a one problem. I want auto-refresh in 500ms but sometimes ajax loading more than 500ms. In this cases consists problem. I want to if ajax loading time 750ms then interval time 750 (or any time longer 500ms) else 500. How can I do this ?
var refreshId = setInterval(function()
{
var number=$("#number").html();
$.ajax({
type: 'GET',
url: 'ajax.php',
data: 'num='+number,
success: function(ajaxResult) {
$('#result').html(ajaxResult);
}
});
if(number<100){
number++;
$("#number").html(number);
}
}, 500);
Use setTimeout instead of setInterval. Set timeout function inside ajax response function, and you won't have problems with syncronizing server calls.
(function pollStep(){
var number=$("#number").html();
$.ajax({
type: 'GET',
url: 'ajax.php',
data: 'num='+number,
success: function(ajaxResult) {
$('#result').html(ajaxResult);
setTimeout(pollStep, 500);
}
});
if(number<100){
number++;
$("#number").html(number);
}
})();
Try the condition within success function.
success: function(ajaxResult) {
$('#result').html(ajaxResult);
if(number<100){
number++;
$("#number").html(number);
}
}

Calling AJAX from jQuery and displaying a waiting message

I'm very new at AJAX calls from jQuery and I'm a bit stuck trying do to this; I have an AJAX call from jQuery like this:
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {//the_output_here}});
});
});
This script is inside a web page triggered when the user hits a particular row (<tr></tr>) from a table. stats-render.php outputs HTML text with some info and graphics. This answer some times takes a while (15 seconds), so I would like to show the user a waiting message when he/she triggers the script and when the call returns an answer show the output text in a div (lets call it <div id="render-div">).
So the questions are, how can I show a waiting message? If you know a good script for showing this in a modal, I would appreciate it.
How can I output the result from stats-render.php into a div?. Thank you so munch for any help!
Just display a loading message in the div where the results go in the interim.
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) { $('div.for-results').html( /* d... */ ); });
$('div.for-results').html('loading...');
});
});
Or for even more fun:
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {
clearInterval(loading);
$('div.for-results').html( /* d... */ );
});
$('div.for-results').html('loading');
var loading = setInterval(function() { $('div.for-results')[0].innerHTML += '.' }, 1000);
});
});
The easiest option is probably to check out the jquery-loading plugin.
I just do a simple show the message before the call, and hide it on the success callback like this:
However I think jquery might have a callback option when the ajax call starts, and when it stops.
$(document).ready(function() {
$('tr.table-row').click(function(){
//Show the loading message, or chage a css class, or what have you.
$('#loadingmessagetext').show();
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {
//Hide the loading message
$('#loadingmessagetext').hide();
//the_output_here
}
});
});
});

Categories