Return ajax data [duplicate] - ajax

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have an ajax call in a function and I did not find a solution how to return the data:
function get_blog_post(id){
var info="id="+id;
$.ajax({
type: 'POST',
url: 'get_blog_post.php',
data: info,
success: function(data){
return data;
}
});
}
The code above doesn't works. The data contains the right answer but I can't use it if I callthe get_blog_post() function.
:\

function get_blog_post(id, callback){
var info="id="+id;
$.ajax({
type: 'POST',
url: 'get_blog_post.php',
data: info,
success: function(data){
callback(data);
}
});
}
get_blog_post(5, function(data){
// use data here
});
OR set async = false (not recommended):
$.ajax({
type: 'POST',
url: 'get_blog_post.php',
data: info,
async: false,
success: function(data){
return data;
}
});

The success function runs some time after the ajax call completes. That's the nature of asynchronous calls--like ajax in javascript.
That means you cant return it and have to do something with the data in that function. Perhaps it is text and you put it into a text area like:
success: function(data){
$('textarea').val(data);
}

Provide a callback method and do what ever you want to do inside it
function get_blog_post(id, callback){
var info="id="+id;
$.ajax({
type: 'POST',
url: 'get_blog_post.php',
data: info,
success: callback
});
}

Related

why unload and beforeunload not working on firefox? is there any solution?

On Chrome its working properly but on firefox its not working
function myfoo(){
// Write your logic here
$.ajax({
type: "POST",
url: "update.php",
dataType: 'json',
data: {Eventid: 'Eventid',Seats:'Seats'},
success: function (r) {}
});
}
When unloading window
$(window).on('beforeunload', function () {
return 'Are you sure you want to leave?';
});
when unloading call function
$(window).on('unload', function () {
console.log('calling ajax');
myfoo();
});
Both "onbeforeunload" and "unload" is working but in your scenario you are expecting to send ajax call. so try changing ajax asynchronous to false.
function myfoo(){
// Write your logic here
$.ajax({
type: "POST",
url: "update.php",
dataType: 'json',
async: false,
data: {Eventid: 'Eventid',Seats:'Seats'},
success: function (r) {}
});
}

Weird object returned from AJAX request

I have this method:
var chineseCurrency = getChinese();
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
});
}
That is what printed when console.log(chineseCurrency);:
I am not able to make chineseCurrency equal to "price", so it would be "6.80071377". How can I do that? Tried chineseCurrency.responseText, nope, chineseCurrency['responseText'], nope. Tried to JSON.parse(chineseCurrency), nope. Nothing works!
Sorry if repeated, couldn't find any answer at Stackoverflow.
How do I return the response from an asynchronous call?
Data that is received as response to asynchronous ajax call cannot be returned from the function that calls $.ajax. What you are returning is XMLHttpRequest object (see http://api.jquery.com/jquery.ajax/) that is far from the desired data.
var chineseCurrency = null;
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny",
success: function(data) {
alert("success1: chineseCurrency=" + chineseCurrency);
chineseCurrency = data.ticker.price;
alert("success2: chineseCurrency=" + chineseCurrency);
// do what you need with chineseCurrency
}
});
}
You are not taking the data from that is returned from the Ajax call. instead you are just returning the ajax object.
Change your code to :
$.ajax(
{
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
data :{},
error : function(data)
{
console.log('error occured when trying to find the from city');
},
success : function(data)
{
console.log(data); //This is what you should return from the function.
}
});

Keep loading AJAX request

I have an AJAX request which gets data from the database and then populates the page with the data collected. The problem I am having is that currently the ajax request is in a setInterval which is being called every second.
setInterval(function () {
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
}
});
}, 1000);
This is fetching the data every second which is a huge strain on the server as it's making a request and then I am calling it again even when the data hasn't come through first time.
Is there a way that I can call the same AJAX request over and over but only after it's finished fetching the data first time and not keep going up?
There are better architectures to accomplish this type of scenario (websockets as mentioned in the comments would be one example), but to do strictly what you're asking, sure! Wrap it in a function that calls itself:
function getData(){
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
getData();
}
});
}
Replace the setInterval with a setTimeout only once you're done:
function fetchAjax() {
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
setTimeout(fetchAjax, 1000);
}
});
};
Add a variable to distunguish if ajax call is already underway. If it is, don't do anything. If not, go ahead.
var isAjaxInProgress = false;
setInterval(function () {
if (!isAjaxInProgress){
isAjaxInProgress = true;
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
isAjaxInProgress = false;
}
});
}
}, 1000);

How to retrieve variable values outside ajax call?

I have an ajax function call that has a variable sum with value as 5. But when I try to access this variable outside the ajax function call, am getting null value.
Is there any way to access the value outside the ajax function?
$.ajax({
type: "POST",
url: "Service.asmx/chart",
data: appid,
success: function(data) {
var mydata = 5;
}
});
alert(mydata);
Try this:
$.ajax({
type: "POST",
url: "Service.asmx/chart",
data: appid,
success: function(data) {
doGetMyData(data);
}
});
function doGetMyData(data){
alert(data);
}
The first "A" in AJAX means Asynchronous, so your code runs the alert before the request completes. To achieve the goals you want, you may try to make your request synchronous adding the async:false option to your query:
$.ajax({
type: "POST",
url: "Service.asmx/chart",
data: appid,
async:false,
success: function(data) {
doGetMyData(data);
}
});
function doGetMyData(data){
alert(data);
}
The bad news is synchronous request locks your browser until it's finish, it's a good pratice to avoid this.

recursive ajax or setInterval(), WHICH ONE IS BETTER?

I am trying to fetch the message table and append the response on the previous fetched results...
here are 2 approaches I have tried, but all failed
1st: recursive fetch
function fetch(){
$.ajax({
url: url,
type: "post",
data:data,
timeout: 3000,
success: function(data){
$(selector).append(data);
setTimeout(function(){fetch()},3000);
}
})
}
2nd: setInterval()
setInterval(function(){fetch()},3000);
function fetch(){
$.ajax({
url: url,
type: "post",
data:data,
timeout: 3000,
success: function(data){
$(selector).append(data);
}
})
}
after few successful ajax call, the browser went frozen and console shows "net::ERR_EMPTY_RESPONSE " OR "ERR_CONNECTION_TIMED_OUT"
please advise
thank you
You may this this if you want to make a recursive call after success or failure
function fetch(url, selector){
$.ajax({
url:url,
type:"post",
data:data,
timeout:3000,
success:function(data){
$(selector).append(data);
fetch();
},
error:function(data){
fetch();
}
});
}

Resources