This question already has answers here:
Jquery call another function after ajax in loop is done
(1 answer)
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am writing a code in which user checks multiple check boxes and those users assign to the selected division. I am using $.post function in a loop of check boxes. Everything is working fine and checked users are being assigned to the selected division. Now, the issue is that I want to print a response after $.post function but everything I write after this post function, javascript executes it before that function and that's why, I am unable to print the response. Please check the below code for your convenience and suggest a possible solution.
Thanks a lot
function assign_user(div_id){
//alert(div_id);
var favorite = [];
$.each($("input[name='user']:checked"), function(){
value = $(this).val();
$.post("../db/assign_user.php",{div_id:div_id,value:value},
function(x){
});
// I want to print final response here but it executes before post function
});
}
Ajax requests are asynchronous. They are sent to the server, then the javascript continues on without waiting for a response. If you type your Ajax request like:
$.ajax({
url: "../db/assign_user.php",
type: 'POST',
data: {div_id:div_id,value:value},
success: function(data){
alert(data);
}
});
then in the success function, you can handle or alert the response.
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I want to store the value of x in js variable into php variable on the same page.
Short answer is: you can not.
The reason for this: PHP is executed on the server side, and the response is sent to the browser, and (usually) generated as HTML. The javascript is rendered after this, so at this point, the PHP code no longer exists.
Long answer:
You can send a javascript variable to PHP using an XHR request (or more commonly known as an AJAX call). This will be a different request from the one that loads your initial page though. For more information see this: https://www.w3schools.com/Php/php_ajax_php.asp
you can use ajax or
add input hidden with this value and when submit form sent a value
i think in most cast ajax in best.
$.ajax({
url: 'url',
method: 'POST',
data: 'data',
cache: false,
success:function(data){
},
error: function(data){
}
}); // end ajax
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
In basic terms I am trying to make a cross domain AJAX call using JSONP. The JS and PHP files need to be on a different domain. I can't seem to get the returned data back to the original function.
To explain how the page works. A user will enter something into an input box. e.g. Surname.
Input and search.
After the user clicks search a the searchClick() function is called. This function takes the text the user has inserted into the input box and calls another function called getInfo().
function searchClick() {
var jsonOfData = getInfo($('#searchInput').val());
console.log(jsonOfData );
}
The getInfo() function has to be in a JS file on a different domain.
function getInfo(surname) {
$.ajax({
url: "https://www.otherdomain.com/api/lookup.php",
dataType: 'jsonp',
crossDomain: true,
data: {
surname: surname
},
success: (data) => {
console.log(data); // This works
return data; // This doesn't
}
});
}
This ajax call goes off to my PHP page and does a search on the database. It then created a JSON array and sends it back. From my research instead of ending the file with the usual echo json_encode($array); I ended the file with:
echo $_GET['callback'] . "(" . json_encode($responseArr) . ")";
This is the point at which I have my problem. As you can see, in the AJAX success function, the data is successfully displayed and logged to the console but I can't return it back to the original jsonOfData variable.
I hope this makes sense and i'll be so thankful to anyone who can help me out.
What you're trying to do won't work, because the $.ajax calls works asynchronously.
Instead of work with the return of the function call at this point:
var jsonOfData = getInfo($('#searchInput').val());
Try to build your logic inside the success function of your $.ajax call.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I try to get some info from external php with ajax and use the data but my global var return undefined.I try with async false but is deprecated.If i console in success function it has value outside is undefined.
var pkz;
$(function(){
$.ajax({
type:'GET',
url: '/user/cred',
success: function (data){
pkz=data;
}
});
console.log(pkz);
The problem with your code is that the execution is asyncronous. When you run console.log, the ajax did not finished. Put it inside the ajax callback.
The ajax do not block the execution. It continue without finished. You SHOULD use callbacks.
If you want to use ajax syncronous:
$.ajax({
type: "GET",
url: remote_url,
async: false
})
This is a horrible solution.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Im having issues getting my data passed back to an external variable. I know the ajax request works but its not passing it in the manner that i need.
here is a exact method in my class
function(amount,symbol=''){
var current_rate = '';
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'https%3A%2F%2Fwww.google.com%2Ffinance%2Fconverter%3Fa%3D"+ amount +"%26from%3DNGN%26to%3D"+ symbol +"'%20and%20xpath%3D'%2F%2Fdiv%5B%40id%5D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var get_rate = $.ajax({
url: url,
method: "GET"
}).complete(function(data){
current_rate = data.responseJSON.query.results.div.span.content;
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
return current_rate;
}
Ive edited the code for simplicity. but heres the full script . I just need to know how to pass the data from the request back into the 'Current_rate' variable
Your function returns current_rate = '' because that's the value of current_rate when the function ends. It ends before the asynchronous call completes!
This part:
$.ajax({
url: url,
method: "GET"
}).complete(function(data){
current_rate = data.responseJSON.query.results.div.span.content;
})
Will set current_rate when the AJAX call returns, which will be long after your function returns. You have to think of $.ajax() as scheduling the request (and the code that runs when the request is complete). It doesn't block or wait for that to happen - your function just continues on.
The best solution here is to return the promise that $.ajax() returns, so your calling function can wait on it:
function(amount,symbol=''){
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'https%3A%2F%2Fwww.google.com%2Ffinance%2Fconverter%3Fa%3D"+ amount +"%26from%3DNGN%26to%3D"+ symbol +"'%20and%20xpath%3D'%2F%2Fdiv%5B%40id%5D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
return $.ajax({
url: url,
method: "GET"
});
}
In order to use this, call the function like this:
get_current_rate(1000,'CAD').complete(function(data) {
// do something with the returned data
});
See the documentation for the jQuery Deferred object. See also this post, which contains an excellent (long!) explanation of the problem and various solutions: How do I return the response from an asynchronous call?
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have to display element on mouseover.
There are details in this element which are brough through ajax.
The problem that the UI is not "smooth" due to ajax issue.
The return false is executed before success. Why?
var companyInfoHeight = $("#company-info").outerHeight();
$('.notifications-container .notification .notification-info .notification-from-user').on('mouseover', function(event){
var base = $(this)
jQuery.ajax({
url: tooltipUrl,
type:'POST',
data: {userId : $(this).attr('data-userid')},
success:function(data,textStatus){
$("#personInfo").html(data)
$("#personInfo").css({'top':base.offset().top-userInfoHeight-115,'left':base.offset().left}).show();
}
});
return false;
})
function onMouseOut(){
$('.user-info').on('mouseleave', function(event){
$(this).hide();
})
}
onMouseOut();
Because success is a delayed event(Asynchronous).
It takes a bit of time for your computer to send a message to the server. Success is the function run once your computer has sent the message to the server
If i ran this code than you would be alerted "2" before "1":
setTimeout(function(){alert("1")}, 100);
alert("2")
Because setTimeout is a delayed event, an ajax call works the same way.
What you might be looking for is html get functions that wait until they recieved server information before completing:
HTTP GET request in JavaScript?