Jquery, how I can call the same function without rewrite [duplicate] - javascript

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

Related

multiple ajax call to single function javascript

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

Call JSON inside AJAX success

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

jQuery ajax in ajax request

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

Call another method onSuccess event of an Ajax call

I have an AJAX call on MVC3 it looks like this
save: function () {
$.ajax({
url: "#Url.Action("Save")",
type:"post",
data: ko.toJSON(this),
contentType:"application/json",
success: function(result){alert(result.message)}
});
}
The trouble is the line
success: function(result){alert(result.message)}
I want to pass all the messing things in a HtmlHelper, however, the success line prevents me from doing so, is there a way I can specify a function for that line
success: doSomeStuff(result)
and
function doSomeStuff(result){alert(result.message)}
Thanks in advance
Simply pass the function name to the success: method and it will pass the data onwards, as such:
save: function () {
$.ajax({
url: "#Url.Action("Save")",
type:"post",
data: ko.toJSON(this),
contentType:"application/json",
success: doSomeStuff
});
}

Why do I have to enclose a function in another function?

When I write a function in JSON, why do I have to enclose it inside an anonymous function?
This works:
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: function(data) {
alert(data);
}
});
This doesn't work:
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: alert(data)
});
Thanks
You can do that. You just using the wrong syntax.
The success property needs a function expression not a function() call (which then returns a value into success);
So
success: myfunction
instead of
success: myfunction()
In short, because you're executing alert() and trying to assign the result to the success callback, so this won't work (the result of alert() is undefined). However you can do this:
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: customFunc //*not* customFunc() which would call it
});
In this case customFunc will receive the same parameters as success passes, so it's signature should be: customFunc(data, textStatus, XMLHttpRequest), though it can be a subset, for example customFunc(data).

Categories