I have a variable in the success part of ajax and I want to reuse it in another function (which executed every 3 seconds), I tried to declare it global, but it does not work; Tdata is not known.
I know that $.ajax is an asynchronous function and I saw some posts similar to mine but it did not help me.
Help me please. Thank you.
This is a part of my code:
<script language='Javascript'>
var Tdata;
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
////
}
});
window.setInterval(function() {
$(window).load(function() {
$.each(Tdata, function(variable) {
/////////////
});
});
}, 3000);
</script>
Why not wait until the AJAX request has successfully returned data before starting your interval? Since any executions of the interval's function aren't going to do anything (due to no data) before that point waiting isn't going to change the way the page would function in any way.
$.ajax({
method: "GET",
url: "load-data.php",
dataType: "json"
success: function(data) {
var Tdata = data;
// do some more stuff with the response of the AJAX request
var interval = setInterval(function() {
$.each(Tdata, function(variable) {
// do something with variable
});
}, 3000);
}
});
Note that I've removed the binding of the load event to the window every time the interval runs because doing so really doesn't seem to make any sense. I've also added a dataType property with a value of json to the options object passed to $.ajax() so you don't have to parse the response as JSON yourself.
try this,
<script language='Javascript'>
var Tdata;
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
////
}
});
$(window).load(function() {
window.setInterval(function() {
$.each(Tdata, function(variable) {
/////////////
});
}, 3000);
});
</script>
Function that uses the variable from AJAX call should be called from inside AJAX success, like this:
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.each(Tdata, function(variable) {
/////////////
});
}, 3000);
}
is callback tdataAjax function ajax success method run; #param parseJSON
var tdataAjax = function(callback) {
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
var Tdata=jQuery.parseJSON(data);
setInterval(function() {
callback(Tdata);
}, 3000);
}
});
};
is Callback function #param data in tdataAjax function
tdataAjax(function(data) {
$.each(data, function(variable) {
// code
});
});
tdataAjax ++ :)
tdataAjax(function(data) {
$.each(data, function(variable) {
// cla bla
});
});
Related
in a $.each() I do a AJAX-request:
$.each(all, function(i,v) {
$.ajax({
url: "/mycontroller/"+encodeURIComponent(v),
success: function(data){
$('#inner').append(data);
}
});
});
now I would like to show a message if every AJAX-request in the $.each() is complete. But how can I do this, As AJAX is asynchronous?
You can utilize jQuery.when(). This method
provides a way to execute callback functions based on zero or more objects, usually Deferred objects that represent asynchronous events.
var ajaxRequests = all.map(function(x) {
return $.ajax({
url: "/mycontroller/"+encodeURIComponent(x),
success: function(data){
$('#inner').append(data);
}
});
jQuery.when.apply(this, ajaxRequests).then(function() {
// do what you want
});
With simple javascript you can do it in following way:
var counter = 0;
$.each(all, function(i,v) {
$.ajax({
url: "/mycontroller/"+encodeURIComponent(v),
success: function(data){
$('#inner').append(data);
counter++; //increment the counter
},
error: function(){
counter++; //increment the counter
},
complete : function(){
//check whether all requests been processed or not
if(counter == all.length)
{
alert("All request processed");
}
}
});
});
use async :false to make ajax request to be completed before the browser passes to other codes
$.each(all, function(i,v) {
$.ajax({
type: 'POST',
url: "/mycontroller/"+encodeURIComponent(v),
data: row,
success: function(data){
$('#inner').append(data);
}
error: function() {
console.log("Error")
}
}); });
I have an issue with calling ajax request with jquery.
The order that I'm doing this in is:
click the button
do ajax post
when the ajax request is finished I call a function that is out side the scope.
For some reason and supecting that it has to do with the fact that i am in the on click callback that the load function is out of scope. But I don't even see the console.log message either. But I do see the ajax call.
Any ideas? Maybe I'm doing this the wrong way???
Here's the prototype code that resembles what I'm trying to do:
$(document).ready(function(){
$('#button').on('click',function(evt){
var data = {};
ajax('index.html', data).done(function(){
console.log('Fire Please'); // this does not fire after the ajax call!!!
load(); // this does not fire after the ajax call!!!
});
});
function load(){
// do another ajax call and add to the dom
}
function ajax(url, data){
return $.ajax({
url: url,
type: 'post',
dataType: 'json',
data: data
});
}
});
And Here's the Actual Code I'm trying to use
$(document).ready(function(){
// add onclick event to the Add Unit Button
addUnitButt.on('click', function(evt){
var data = {
id: id,
dept_no: dept_no.val(),
dept: dept.val()
};
evt.preventDefault();
dept.val('');
dept_no.val('');
$(this).prop('disabled', true);
ajax('index.html', data).done(function(){
load();
});
});
function load(){
var data = {
id: 575
};
// show loading
showLoading();
// reset the table dom
$("#listTable").find("tr:gt(0)").remove();
// do initial load of the list data
ajax('index.html', data)
.done(function(units){
var data = toJSONObject(units);
for(var x = 0; x < data.length; x++){
if((x & 1) == 0){
addRow(data[x], data.length, 'odd');
}else{
addRow(data[x], data.length, 'even');
}
}
// hide loading
hideLoading();
});
}
// ajax function to call for data
function ajax(url, data){
return $.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: url
});
}
});
Thanks in advance!
Maybe the code of your index.html is not valid JSON
.always() must be called.
Make sure your server response have the right headers like Content-Type. And the response body is valid JSON.
I'm trying to use setInterval to execute the php script update.php every 10 seconds and refresh div id = verification. For some reason setInterval is preventing the script from functioning. Any suggestions on where to place\change setInterval would be appreciate as I'm stumped (sorry entry level javascript user here). For clarity I omitted all the non-relevant details, such as vars.
<div id="verification"></div>
<script id="verification" language="javascript" type="text/javascript">
$(function() {
$.ajax({
url: 'update.php', //php
data: "", //the data "caller=name1&&callee=name2"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
var foobar = data[2]; //foobar
$('#verification').html("(<b>" + foobar + "</b>)"); //output to html
}
});
});
setInterval(10000); //every 5 secs
</script>
Suggestions/Steps/Bugs:
Create a separate function to perform ajax request
Call this function on page load to run it when page is loaded
Use setInterval() to call the function every n seconds
id should always be unique. You're now using verification as if for <div> and <script>
You can remove id and language attributes of <script>. Those are not required.
Code:
function update() {
$.ajax({
url: 'update.php', //php
data: "", //the data "caller=name1&&callee=name2"
dataType: 'json', //data format
success: function (data) {
//on receive of reply
var foobar = data[2]; //foobar
$('#verification').html("(<b>" + foobar + "</b>)"); //output to html
}
});
}
$(document).ready(update); // Call on page load
// ^^^^^^
setInterval(update, 10000); //every 10 secs
// ^^^^^^
setInterval() takes a function (that it should execute) as it's first argument.
Try this:
setInterval(function(){
$.ajax({
url: 'update.php', //php
data: "", //the data "caller=name1&&callee=name2"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
var foobar = data[2]; //foobar
$('#verification').html("(<b>"+foobar+"</b>)"); //output to html
}
});
}, 10000);
you are using setInterval in a wrong way - you can read about it here:
http://www.w3schools.com/js/js_timing.asp
Also please notice that AJAX calls are asynchronous - when program is going forward it doesn't mean that previous AJAX call has ended. You can "wait" for AJAX completition using some jQuery mechanisms like binding ajaxComplete or using when
You are missing the function block:
setInterval(function() {
// to do
}, 5000);
My suggestion is to go for setTimeout as you are running ajax it is not certain that it would complete within 5 seconds. In case if you wana go for it:
var dispatchUpdates = function() {
setTimeout(pullUpdates, 5000);
};
var pullUpdates = function() {
$.ajax({
url: 'update.php',
data: "",
dataType: 'json',
success: function(data) {
var foobar = data[2];
$('#verification').html("(<b>" + foobar + "</b>)");
dispatchUpdates(); // next updates
},
error: function() {
dispatchUpdates(); // retry
}
});
};
$(dispatchUpdates); //page load
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I know there are many question like this but i didn't found a proper solution for me.
I am calling API using ajax so my problem is my web page gets unresponsive so some where I have found that this is just because of the improper ajax handling can you please help to know where do I put my ajax.I need ajax to be called on the load of the page.
I have tried calling ajax without any function like..
show('ajax Call start for player');
$('#loading').show();
$.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
// show(playerData);
showPlayers(1);
show('ajax Call complete for player');
flag = 1;
}
});
show('ajax Call start for loadplayeronpitch');
$.ajax({
url: '/home/checkUserTeam',
success: function (data) {
while (true) {
if (flag) {
loadUserTeampitch(data);
break;
}
}
show('ajax Call complete for loadplayeronpitch');
}
});
This is not working which cause the unresponsive page.
then from other questions I have tried calling the ajax in following functions
$(document).load(function(){
});
$(function(){
});
$(document).bind("load", function () {
});
but this all are also not working properly can you help me for this?
Thank you.
The unresponsiveness is caused by your while(true) loop, so never ever do this again :-)
What you want to do is: Run the second ajax call only after the first one finishes. So you should put both ajax calls into separate functions, then call the first function on page load.
In the success part of the first ajax (inside the first function), call the second function. Done.
function firstAjax() {
$.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
//show(playerData);
showPlayers(1);
show('ajax Call complete for player');
secondAjax();
}
});
}
function secondAjax() {
$.ajax({
url: '/home/checkUserTeam',
success: function (data) {
loadUserTeampitch(data);
}
});
}
$(function() {
firstAjax();
});
This should work like you want to, but I can't test it right now.
$('#loading').show();
var deferedA = $.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
// show(playerData);
showPlayers(1);
show('ajax Call complete for player');
}
});
show('ajax Call start for loadplayeronpitch');
var deferedB = $.ajax({
url: '/home/checkUserTeam'
});
//wait until both request are finished
$.when(deferedA, deferedB)
.done( function (dataA, dataB) {
loadUserTeampitch(dataB);
show('ajax Call complete for loadplayeronpitch');
});
EDIT I would suggest to use Promise instead $.when (the Promise like implementation of jQuery is a bit strange), but the problem with Promise is that it is only available with the newer browser, for older one you need a library like bluebird or when
EDIT : If you want to go simple than you can use below approach..
<script type="text/javascript">
$(function() {
var flag = 0;
var data1;
$('#loading').show();
$.ajax({
beforeSend: function() {
show('ajax Call start for player');
},
url: '/home/getPlayers',
success: function(data) {
flag++;
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
showPlayers(1);
show('ajax Call complete for player');
checkFlag();
}
});
$.ajax({
beforeSend: function() {
show('ajax Call start for loadplayeronpitch');
},
url: '/home/checkUserTeam',
success: function(data) {
flag++;
data1 = data;
show('ajax Call complete for loadplayeronpitch');
checkFlag();
}
});
function checkFlag()
{
if (parseInt(flag) == parseInt(2))
{
loadUserTeampitch(data1);
}
}
});
</script>
In my app, a displays available timeslots (for appointment). I want to add a class 'taken' to the slots () which are already taken. For this I wrote the following code.
$("td").each(function(){
var send = $(this).text();
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get',
success: function(result){
console.log(result);
if (result.status === "taken") {
$(this).addClass('taken');
};
}
});
});
It's supposed to perform an ajax call, and if the result for a slot is 'taken', add the class 'taken' to corresponding . It does the ajax call part, but adds the class to all td elements in the table, not just the taken ones.
the check-availability.php, returns 'taken' when called it in browser but nothing happens. Also, when the condition is changed into result.status === "notTaken", all the s are added the class 'taken'
How do I fix this?
$("td").each(function(){
var that = this;
var send = $(this).text();
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get',
success: function(result){
console.log(result);
if (result.status === "taken") {
$(that).addClass('taken');
};
}
});
});
see this for more reference:
$(this) inside of AJAX success not working
Ajax jquery success scope
instead of success, try using .done()
example
`
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get'
}).done(function(result) {
console.log(result);
if (result.status === "taken") {
$(this).addClass('taken');
};
});
`