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);
});
Related
im new in JS,im looking for a way to create a class or function,reusable everywhere in my code,just pass it parameters and get the result,because currently I am doing like this:
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "regionalManager": tmpString }),
success: function (result) {
})}
I write this every time I need, and im sick of it,
function sendAjaxCustom(DataType,Type,Url,Ctype,Data){
$.ajax({
dataType: DataType,
type: Type,
url: Url,
contentType: Ctype,
data: Data,
success: function (result) {
return result;
})}
}
You can call this function in JS like
var result = sendAjaxCustom("json","POST",'#Url.Action("power","Ranking")',"application/json; charset=utf-8",JSON.stringify({ "regionalManager": tmpString }));
you will have the result in result variable.
You can create a function like this
function ajax(url, data) {
$.ajax({
dataType: "json",
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
})}
}
Pass the url if it's dynamic and the object data on the second parameter.
Just create a simple function with your variables that need to change between calls and return the $.ajax result from there.
function ajaxWrapper(url, data, callback) {
return $.ajax({
dataType: 'json',
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: callback
});
}
When you want to call it:
ajaxWrapper('http://www.google.com/', { hello: 'world' }, function(result) {
console.log(result);
});
With the callback it's much more reusable, since you can use this anywhere and change what you do on completion of the function wherever you use it.
A simple solution is to return an object and pass it to the ajax and if some change is required then you can update the properties of the object before calling the ajax service
function commonAjaxParams() {
return {
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
//and so on that are common properties
}
}
//now in your application first call the function to get the common props
var commonParams = commonAjaxParams();
//change or add an parameter to your liking
commonParams.type = 'GET';
commonParams.success = function(){...} //if this action is need
commonPramss.error = function(){...}
//now call you ajax action
$.ajax(commonParams)
There is another way in which you may call the ajax function and you may get success, fail response return.
The benefit is you manage success or fail response independently for each ajax request.
$(document).ready(function() {
function ajaxRequest(dataType, requestMethod, dataURL, jsonData) {
return $.ajax({
dataType: dataType,
type: requestMethod,
url: dataURL,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData)
});
}
var jsonData = {
"regionalManager": "jason bourne"
};
ajaxRequest(
"json",
"POST"
"#Url.Action('power','Ranking')",
jsonData)
.success((data) {
console.log("success");
}).error((err) {
console.log("error");
}).done(() {
console.log("done");
});
});
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 want to call a json data inside my AJAX success. I'm still new on manipulating json and AJAX. Can somebody help me on how to access my json data which is from another URL? And I want to compare the id to the JSON data. Here's my code so far:
function getCard(id){
$.ajax({
type: "GET",
data: "id=" + id,
success: function(data){
#call JSON data here from another URL
# Is it possible to call another AJAX here?
}
});
}
This code will work for you
$.ajax({
url: "url",
method: "post",
data: "id=" + id,
success:function(data) {
// success goes here
$.ajax({
url: "url",
async:false,
method: "post",
data: "id=" + id,
success:function(json) {
JSON.parse(json);
// compare data and json here
},
error: function(){
// error code goes here
}
});
},
error: function(){
// error code goes here
}
});
yes Zuma you can call another Ajax inside Success function of Ajax call. Below is the example:
$.ajax({
type: "post",
url: url1,
data: data1,
success: function(data){
$.ajax({
type: "post",
url: url2,
data: data2,
success: function(data){
});
});
});
function getCard(id){
$.ajax({
type: "Get",
url: "发送请求的地址",
data: "id=" + id,
success: function(data){
#call JSON data here from another URL
# if success,you can call another AJAX.
# Is it possible to call another AJAX here?
# yes!
}
});
}
We have some code(simplified) that looks like bellow. We run function x which does an ajax call. When the call is done we call a different function recalculateOrderObjects which also does an ajax call. When this one is completed, it should output the data that which is obtained via the second call. However, what actually happens is that only the first ajax call is made and the second is not executed (or at least immediately goes to done) but does show the data obtained from the first call as the data obtained from the second one.
When running only the recalculateOrderObjects function the function does work as expected.
Edit 1
The subscription variable is a global
There are no errors on the console
Also, when I first call recalculateOrderObjects independent the function work when first x is called and after that I call recalculateOrderObjects independently the function will not work and shows the same behaviour as when called from `x.'
Edit 2
I tried the suggestion to use successinstead of doneas well. With the same result. recalucateOrderObjects is called succesfully, thought after one executing x the whole ajax call in recalucateOrderObjects is never requested again but instead thinks that it is succesfully executed.
function recalculateOrderObjects() {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription}
})
.done(function (data) {
console.log('Data ' + data);
});
}
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
async: false
}).done(function (response) {
recalculateOrderObjects();
}
});}
x();
You can't get success responce by ".done" function.
"success" function gives you responce after ajax load.
Please try below code
function recalculateOrderObjects() {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription},
success: function(data) {
console.log('Data ' + data);
}
});
}
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
success: function(data) {
recalculateOrderObjects();
}
});
}
x();
OR
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
success: function(data) {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription},
success: function(data) {
console.log('Data ' + data);
}
});
}
});
}
x();
Hi I am trying to get a return value from a get function from a jquery Get request on success.
I have tried many ways already but with no success. Two forms which i have tries are:
1)
GetResultOutput = function () {
var outPut = "No Data Found";
var test = test();
return test["outPut"];
}
test = function()
{
outPut = "No Data Found";
**return** $.ajax({
type: "GET",
url: serviceUrl,
dataType: "xml",
success: function (xml) {
outPut = "done";
}
});
}
2)
GetResultOutput = function () {
outPut = "No Data Found";
$.ajax({
type: "GET",
url: serviceUrl,
dataType: "xml",
success: function (xml) {
outPut = "done";
}
});
return outPut;
}
But both of them is not giving me any result..
2nd one outputs me as no data found. and 1st one which is preferred one when googled...results as undefined
Instead of trying to get the output and then process it like:
var output = GetResultOutput();
process(output);
You could pass process as a callback like:
var GetResultOutput = function (callback) {
$.ajax({
type: "GET",
url: serviceUrl,
dataType: "xml",
success: function (xml) {
callback(xml);
}
});
};
// usage:
GetResultOutput(process);
You can also make your ajax call synchronous by using:
$.ajax({
type: "GET",
url: serviceUrl,
async: false,
dataType: "xml",
success: function (xml) {
outPut = "done";
}
});
Ajax request are asynchronous, which means you cannot immediately "return" data from the call. That is why all forms of $.ajax take one or more callbacks to be called when data is received, or an error occurs etc.
Which means your method must look like:
GetResultOutput = function (callback) {
$.ajax({
type: "GET",
url: serviceUrl,
dataType: "xml",
success: callback
});
}
with callback looking like:
function callback(xml)
{
console.log('done: ' + xml);
}