This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a PHP script that takes a query string returns and JSON object. I am trying to make an AJAX call that will return this JSON object so I can use it in jQuery autocomplete. Here is my AJAX call so far
$(document).ready(function(){
$("#searchBox").keyup(function(){
var search_result = $.ajax({
url:"/mm5/service/product_lookup_json.php",
type: "GET",
dataType: "json",
jsonp: false,
data: "query=" + $("#searchBox").val(),
success: function(data){
return data;
}
});
console.log(search_result);
});
});
This sends the result of the AJAX call to the console ( a javascript object). I can see a JSON in that object. I would think all I have to do to access the data I want is this
console.log(search_result.responseJSON);
But this just gives me undefined. What am I doing wrong here?
That is not the way to do it because it is an async call so the data will not be returned by the ajax call. Try this
$(document).ready(function(){
var search_result;
$("#searchBox").keyup(function(){
$.ajax({
url:"/mm5/service/product_lookup_json.php",
type: "GET",
dataType: "json",
jsonp: false,
data: "query=" + $("#searchBox").val(),
success: function(data){
search_result = data;
console.log(search_result);
}
});
});
});
You need to wait for the AJAX call to complete in order to access the data it returns.
$(document).ready(function(){
$("#searchBox").keyup(function(){
$.ajax({
url:"/mm5/service/product_lookup_json.php",
type: "GET",
dataType: "json",
jsonp: false,
data: "query=" + $("#searchBox").val(),
success: function(data){
//data is available at this points
console.log(data);
}
});
});
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I can't get the returned data of an GET AJAX call.
The call gets the data properly but I can't get the data I need in a variable and return it.
I know that the AJAX calls are asynchronous and I've tried different approaches but failed.
function getQuantity(Id) {
var productQuantity = null;
$.ajax({
type: "GET",
dataType: "json",
url: "/Product/ProductData/" + Id,
success: function (response) {
productQuantity = response.QuantityInStock;
console.log("in call: ", productQuantity);
}
});
console.log("in return: ", productQuantity);
return productQuantity;
}
This is what I get in the console:
in return: null
in call: 2724 -> this is the right value
Hope you can help.
You need to return the AJAX call and add asycn: false option
function getQuantity(Id) {
var productQuantity = null;
return $.ajax({
type: "GET",
dataType: "json",
async: false,
url: "/Product/ProductData/" + Id,
success: function (response) {
console.log("response: ", response);
}
}).responseText;
}
This question already has answers here:
How to dynamically pass data parameter in a jquery ajax call (multiple arrays of data)
(4 answers)
Closed 5 years ago.
usually when I need to use the same function with some edits I must copy/paste the function and then add some variables (sometimes the code is very long)
for example:
1st f unction
$.ajax({
type: 'GET',
url: url,
data: {s: size},
dataType: 'json',
success: function (data) {
//data
In the second function i have to add a variable in data (success data will be the same as the first function):
$.ajax({
type: 'GET',
url: url,
data: {s: size, f:from},
dataType: 'json',
success: function (data) {
//data
How I can call the first function without rewrite all?
You can have an function and pass the data into it and call your $ajax inside the function with the given data. Also you can pass your callbacks into it to make more flexible.
function makeAjax(data, success, error){
$.ajax({
type: 'GET',
url: url,
data: data,
dataType: 'json',
success: success,
error: error
});
}
Enclose your AJAX request in a single function and pass your data as a parameter.
function ajax_request(request_data) {
$.ajax({
type: 'GET',
url: url,
data: request_data,
dataType: 'json',
success: function (data) {
//do something here
}
});
}
I am trying to retrieve certain values in a JSON object retrieved from AJAX.
Using console.log(), I was able to view these:
0: Object
title: "First post"
body: "This is a post"
id: 1
userId: 27
.
.
.
100: //same format of data as object 0
Now I want to try storing the whole JSON object above so that I can use the userId and match it with another list of data to find the user who made the post. Problem is, I can't store it to a global variable. Here is my jscript snippet:
var postJson; //global variable
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
console.log(response);
}
});
I also tried doing postJson = $.ajax but nothing happened and postJson continues to be undefined.
$.ajax is async function, you need to use callback or do all the code in success function
var postJson; //global variable
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
//do something with postJson or call function doSomething(response)
}
});
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
doSomething(response);
//do something with postJson or call function doSomething(response)
}
});
You can do directly via calling function from response no need to declare variable. Hope it will also helps you
I have 3 ajax call. Data from each ajax call is passed to john_doe();
Call 1
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data1){
john_doe(data1);
});
Call 2
$.ajax({
url: url2,
dataType: "JSON",
type: "GET",
}).success(function(data2){
john_doe(data2);
});
Call 3
$.ajax({
url: url3,
dataType: "JSON",
type: "GET",
}).success(function(data3){
john_doe(data3);
});
Main function
function john_doe(param){
console.log(param); //Print data from all three ajax call.
}
How to separate data1, data2 and data3 in john_doe function? because I need to carry out arithmetic operation.
Currently,
Input
data1 = one,two,three
data2 = four
data3 = five
Output
console.log(param) would give output as
one
four
five
I want output as
console.log(param[0])
console.log(param[1])
console.log(param[2])
param[0] containing one,two,three
param[1] containing four
param[2] containing five
I dont have control over the data. How to access data1, data2 and data3 separately?
Using promises you can access all the data in Promise.all() callback and do whatever you need with it all at once. Assumes using jQuery 3+. Can use $.when in older versions
var urls =['data-1.json','data-2.json','data-3.json'];
// array of ajax promises
var reqPromises = urls.map(function(url){
return $.ajax({
url: url,
dataType: "JSON",
type: "GET"
});
});
Promise.all(reqPromises).then(function(res){
// res is array of all the objects sent to each `$.ajax` from server
// in same order that urls are in
var param = res.map(function(item){
return item.val
});
console.log(param)
})
DEMO
Quick and dirty solution is simply pass in an identifier, why is this dirty because it isn't really extensible with respect to adding say 4th or 5th call each time you do this you need to add more identifiers and your if statement in the main method will end up pretty ugly at one point. But that said sometimes "Keeping It Simple" is ok.
Main function:
function john_doe(identifier, param) {
// best to use something more readable then numbers
if(identifier == 1) {
console.log(param); //Print data from all ajax call 1.
} else if(identifier == 2) {
console.log(param); //Print data from all ajax call 2.
} else if(identifier == 23) {
console.log(param); //Print data from all ajax call 3.
} else {
// handle bad id
}
}
In your ajax calls, pass in the right identifier, for example Call 2:
$.ajax({
url: url2,
dataType: "JSON",
type: "GET",
}).success(function(data2){
// numeric 2 in in the first param is your identifier
john_doe(2,data2); });
Adding a param to let you know where it is being called from
Call 1
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
john_doe('call1',data);
});
Call 2
$.ajax({
url: url2,
dataType: "JSON",
type: "GET",
}).success(function(data){
john_doe('call2',data);
});
Call 3
$.ajax({
url: url3,
dataType: "JSON",
type: "GET",
}).success(function(data){
john_doe('call3',data);
});
Main function
function john_doe(call,data){
console.log('Called from : ' + call);
console.log(data); //Print data from all three ajax call.
}
How about this?
Declare an object container to hold your response data values and your arithmetic operation function.
var myParams = {
all_params: [],
getParams: function(){
return this.all_params;
},
setParam: function(index, data){
this.all_params[index] = data;
},
yourArithmeticOperation: function(){
console.log(this.all_params); // your actual logic using all 3 ajax response data
}
}
Then, in your ajax calls:
// call 1
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
myParams.setParam(0, data); // add ajax 1 response data
});
// call 2
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
myParams.setParam(1, data); // add ajax 2 response data
});
// call 3
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
myParams.setParam(2, data); // add ajax 3 response data
});
In case you need all your response data,
// after all three ajax calls
params = myParams.getParams();
console.log(params);
And finally, your arithmetic operation,
myParams.yourArithmeticOperation();
try adding async: false to your ajax calls
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
async: false,
}).success(function(data){
john_doe('call1',data);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have this code:
function aaa (){
var db_data;
$.ajax({
url: "http://localhost:8888/aaa/{{$article->id}}",
type: "GET",
async: true,
dataType: "json",
success: function(data) {
db_data = data;
console.log(db_data);
},
error: function (data) {
console.log(data);
console.log('GRESKA NEKA');
}
});
console.log(db_data);
};
but then I get at least line console.log(aaa) - > undefined...
Why? First console.log work ok but outside ajax I cant get db_data... WHy?
You are ordering a pizza, then trying to eat it before it is delivered! Ajax is an async call and the success gets called-back long after the last console.log executes.
You need to only use Async data in side the callbacks.
An alternative is to use the promise returned by Ajax so you code becomes a function that "promises to return the data":
// Return the Ajax promise
function aaa() {
return $.ajax({
url: "http://localhost:8888/aaa/{{$article->id}}",
type: "GET",
async: true,
dataType: "json",
});
}
// and use like this
aaa().then(function(data){
// Do something with the data
}).fail(function(data){
// Do something with the data when it fails
});
Promises make the functions reusable.