jQuery global variable problem - javascript

var id = $(this).children().html(); // id is 5
$.ajax({
url: 'ajax.php?id=' + id,
success: function(data) {
id = data; // id is 1
}
});
if(id == 1){ // id is again 5
...
}
Why in the following example I can't reinitialize the id variable? What is wrong?
Thanks.

The $.ajax() function has to go and get the data, it hasn't done this and executed your success callback by the time it reached the code immediately after.
Your code order actually happens like this:
var id = $(this).children().html();
//Ajax start
if(id == 1){ }
//Ajax end (sometime later, not immediately after)
function(data) { id = data; }
If you are depending on this value to continue, stick it in the success callback:
var id = $(this).children().html(); // id is 5
$.ajax({
url: 'ajax.php?id=' + id,
success: function(data) {
id = data; // id is 1
if(id == 1){ // id is now 1
...
}
}
});

Refactoring the code like this would work:
function by_id() {
if(id == 1) {
... do something ...
}
}
var id = $(this).children().html();
$.ajax({
url: 'ajax.php?id=' + id,
success: function(data) {
id = data;
by_id(); // call on successful ajax load
}
});
The advantage of wrapping your id logic in a function allows you to call it anywhere - be it at the end of an AJAX request, at page load, on a button press, etc.

your if statement executes before your .ajax call completes

The A in Ajax is for Asynchronous. From within the 'success' callback you can call another function or execute post-ajax code.

Hey a better solution is using the async: false property, something like this:
var id = $(this).children().html(); // id is 5
$.ajax({
url: 'ajax.php?id=' + id,
async: false,
success: function(data) {
id = data; // id is 1
}
});
if(id == 1){ // id is again 5
...
}
;)

The AJAX function is asynchronous. It will run in the background and when it is done getting the ajax.php page it will run the success function.

Related

Using a javascript variable from outside the function to pass through to my AJAX function

I have an AJAX function which gets called every time the enter key is pressed. I have a set of javascript variables that get passed into the data of the AJAX function. Previously, these JS variables were equal to elements in the HTML (the contents of a text area). Now I want these JS variables to be equal to the values of JS variables outside the function.
function stream()
{
var line_Number = $('#lineNumber').val();
var post_code = '#lineText';
var post_id = $('#Streamid').val();
if (post_code != ''){
$.ajax({
url: "post-code.php",
method: "POST",
data: {lineText: post_code, lineNumber: line_Number},
dataType: "text",
success: function(data){
if(data != ''){
$('#Streamid').val(data);
}
$('#autoStream').text("Sending data");
setInterval(function(){
$('#autoStream').text('');
}, 100);
}
});
}
}
Another function then calls the AJAX function
And here are the JS variables which I want to access and pass into the AJAX function
var text;
var lineNumber;
var lineText;
var numOfSpaces;
function update(e) {
text = //code
lineNumber = //code
lineText = //code
I didn't show the code for each variable as I felt it might unneccesarily complicate this.
If I understand your question, you have these options:
1- Use a hidden HTML element:
<input type="hidden" id="someVariable">
where yout want to initialize in your script (JQuery):
$('#someVariable').val(myVar)
and in script in ajax function (JQuery):
var myVar = $('#someVariable').val()
2- You know var scope if it is declared outside a function in javascript, is hole document (window).
3- Pass the arguments to your ajax functio. e.g:
function stream(firstVariable, secondOne, ...)
Hi you can create a json array and pass it as parameter of your ajax function,
this way you avoid to write unnecessary code, example:
let params = {
"line_number": $('#lineNumber').val(),
"post_code" : '#lineText',
"post_id" : $('#Streamid').val()
};
function stream(params)
{
if (params.post_code != ''){
$.ajax({
url: "post-code.php",
method: "POST",
data: data,
dataType: "text",
success: function(data){
if(data != ''){
$('#Streamid').val(data);
}
$('#autoStream').text("Sending data");
setInterval(function(){
$('#autoStream').text('');
}, 100);
}
});
}
}
Hope it helps

What is the best place to call ajax which is calling an API?

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>

Jquery AJAX calls in a loop

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');
};
});
`

Waiting for Ajax called DOM manipulation to finish

Sorry for the title but I had no idea how to call it.
I got some ajax call function that on success adds some HTML elements to the page:
function ajax_submit_append(form_data, url, result, complete) {
$.ajax({
url: url,
type: 'POST',
data: form_data,
success: function(msg) {
var res = $(msg).filter('span.redirect');
if($(res).html() != null){
window.location.replace($(res).html());
return false;
}
$(result).append(msg);
},
complete: complete()
});
};
Function does something on success where the most important is the .append and then this ajax function is called in some button .click function like this:
$(function() {
$("#product_list_add_btn").click(function(e){
ajax_submit_append(
form_data = {
product_name: $('.selectpicker option:selected').val(),
amount: $('#amount').val()},
"<?php echo site_url('admin_panel/new_order/add_product'); ?>",
'#add_product_result',
calculateSum
);
return false;
});
});
What I want to achieve is that calculateSum function (sums table columns) is called after .append is done via ajax.
For now, when I add calculateSum to ajax complete event it is still called before new row is added to the table with .append
Edit: I present You calculateSum, but I believe there is nothing faulty there.
function calculateSum() {
var sum = 0;
// iterate through each td based on class and add the values
$(".countit").each(function() {
var value = $(this).text();
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
$('#total_price').text(sum);
alert("test");
};
If I had to guess, I would say its something with click event?
How to fix this?
Try using jqXHR's done() method:
function ajax_submit_append(form_data, url, result, complete) {
$.ajax({
url: url,
type: 'POST',
data: form_data,
success: function(msg) {
var res = $(msg).filter('span.redirect');
if($(res).html() != null){
window.location.replace($(res).html());
return false;
}
$(result).append(msg);
}
}).done(complete);
};

Getting variable from success function ajax

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
});
});

Categories