Functions with Variable Arguments in javascript/jQuery - javascript

I need and advice.
This is my issue, I have "N" functions.
var FirstOne = function(){
return $.ajax({
type: "POST",
url: hrefUrl,
data: JSON2.stringify(option),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(status){
},
success: function(data){
}
});
};
var SecondOne = function(){
return $.ajax({
type: "POST",
url: hrefUrl,
data: JSON2.stringify(option2),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(status){
},
success: function(data){
}
});
};
.............
var NOne = function(){
return $.ajax({
type: "POST",
url: hrefUrl,
data: JSON2.stringify(optionn),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(status){
},
success: function(data){
}
});
};
all these function arr pushed in an object which is this .
var funcObject= [FirstOne(), SecondOne(), ....... NOne() ];
after I am waiting when all Ajax functions are done with and and after I am fine.
$.when.apply($, funcObject).done(function (a1, a2, ...an) {
// ..... here already doesn't matter
});
my issue is here:
function (a1, a2, ...an)
I want to have instead function arguments an object because I do not know how many function is going to be.
So i can edit function object, which is cool $.when.apply($, fucArr), problem is to use variable numbers of arguments .
PS: Maybe I can use "apply" or "call" for these arguments as well?
Can someone give me an idea here. Thanks A lot guys!!!

You can access all arguments passed to a method using the arguments keyword eg:
function () {
Console.log(arguments); //arguments is an array
}
The apply method can be used to use these arguments in another function call:
function () {
someFunction.apply(this, arguments);
}

Related

Can I use a variable in an ajax error call instead of the Function name?

I have an Ajax call that works fine, but I am now trying to polish the code a bit
$.ajax({
url: wbURL,
dataType: "xml",
contentType: "text/xml; charset=\"utf-8\"",
type: "POST",
headers: '#"HEADER DATA',
data: dataPacket,
success: dealWithResonse,
error: dealWithError
});
what I am now trying to do is replace the success and error function names with variables so I can use it for other jobs.
var SuccessFunctionCall = dealWithResonse;
var ErrorFunctionCall = dealWithError;
$.ajax({
url: wbURL,
dataType: "xml",
contentType: "text/xml; charset=\"utf-8\"",
type: "POST",
headers: '#"HEADER DATA',
data: dataPacket,
success: SuccessFunctionCall,
error: ErrorFunctionCall
});
But my program stops at this point, assumingly as it can't find a function called
ErrorFunctionCall.
can I use a variables vaule instead of an actual function name?
Thank you in advance
You may define those functions as global and assign them to what you want:
var SuccessFunctionCall = function(){dealWithResonse()};
var ErrorFunctionCall = function(){dealWithError()};
and call them as members of window:
success: window[SuccessFunctionCall](),
error: window[ErrorFunctionCall]()
Finally I have to say that I am not sure why you want to assign functions to variable names. You may define those functions directly and call them as you need.
You should define those functions in your variables as shown below:
$(document).ready(function(){
var SuccessFunctionCall = function dealWithResonse(){
console.log("success");
};
var ErrorFunctionCall = function dealWithError(){
console.log("error");
};
$.ajax({
url: 'http:test',
dataType: "xml",
contentType: "text/xml; charset=\"utf-8\"",
type: "POST",
headers: '#"HEADER DATA',
data: '',
success: SuccessFunctionCall,
error: ErrorFunctionCall
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
Try this

how to create a javascript rusable class to pass parameters to ajax

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

Returning String Result from Ajax Method

I have a DoughnutChart chart and I would like to change the color of its parts regarding color hexa-codes saved in the database I used this Ajax method to get the color string by invoking an action method that returns JSON Result ,
getcolors: function getcolors(name) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
// return data;
},
error: function (data) {
// return "Failed";
},
async: true
});
but instead of receiving the string I received Object {readyState: 1} in the console window
However, I can find the color value stored in ResponseText element.I need your help in how can I get the color value as string.
EDIT :
To make things more clear that's where I would like to invoke the ajax method to receive the color string then I will be able to push in the chart color array .
getColorArray: function getColorArray(categories) {
var colors = [];
for (var i = 0; i < categories.length; i++) {
console.log(this.getcolors("Risk"));
//colors.push(this.getcolors(categories[i]));
}
return colors;
}
Why your code is like this?
success: function (data, textStatus, jqXHR) {
// return data;
},
Did you use it?
success: function (data, textStatus, jqXHR) {
console.log(data);
}
Ok, i got it. When you use an ajax request your will work with asynchronous data, to do this you need return a promise in your method. Please, try to use the code below.
getcolors: function getcolors(name) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
And for use your function use this code:
getcolors("name").done(function(result){
console.log(result);
});
Or you can use a callback
getcolors: function getcolors(name, success, error) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
success(data);
},
error: function(data){
error(data);
}
});
}
... And for use with callbacks:
getcolors("name", function(data){
//success function
console.log(data);
}, function(){
//Error function
console.log(data);
})
Try one of this options and tell the result.
The Solution
First of all I would like to thank Mateus Koppe for his efforts, through his solution I got the way to solve my problem ..
What I did simply is just I received the ResponseText from the incoming successful result in my Ajax method and then I passed it to a callback function that handles the result like the following :
getcolors: function getcolors(name, handleData) {
$.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
handleData(data.responseText);
//return data.responseText;
},
error: function (data) {
handleData(data.responseText);
//return data.responseText;
},
async: false
});
then I worked with getColorArrayModified to loop through my categories list and populate its own color.
getColorArrayModified: function getColorArrayModified(categories) {
var colors = [];
for (var i = 0; i < categories.length; i++) {
this.getcolors(categories[i], function (output) {
colors.push(output);
});
}
return colors;
}
Thanks for all :).

jquery ajax - second array push not working [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
i have this code that needs to populate an array that will be used on some diagramming tools. so there's a button that will show the results and a checkbox that enables the user to add another set of rows to the array. i use .push() for the array and it works. now, the problem is that the second push on my second ajax calls did not add the data to the array. here's my code:
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategorySalesPerTerritory",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.each(response.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one works
});
if ($('#chkPromotion').is(":checked")) {
$.ajax({
type: "POST",
url: "Default.aspx/AddPromotion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one fails
alert("pushed");
});
},
failure: function (data) {
alert(data.d);
}
});
drawChart(rows);
} else {
drawChart(rows);
}
},
failure: function (response) {
alert(response.d);
}
});
i really don't know why it fails. what happens is that even if the condition is satisfied and the second ajax call succeeds, the contents of the array rows is still the first array push. what's the problem with the code?
the result you are getting is actually expected because of async nature of ajax
you should call the method within the success callback of the second ajax call like this
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategorySalesPerTerritory",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.each(response.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one works
});
if ($('#chkPromotion').is(":checked")) {
$.ajax({
type: "POST",
url: "Default.aspx/AddPromotion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values);
});
drawChart(rows); // here
},
failure: function (data) {
alert(data.d);
}
});
} else {
drawChart(rows);
}
},
failure: function (response) {
alert(response.d);
}
});

Jquery ajax: pass the scope to set it

I have this class with this ajax call:
Person = function () {
this.__type = "PersonDto:#Empower.Service.Common.Dto";
this.Name = undefined;
this.Surname = undefined;
this.GetById = function (id) {
return $.ajax({
type: "POST",
url: "/Services/PersonService.svc/GetPersonById",
data: JSON.stringify(id),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
...
this = data;
...
}
});
}
};
In success of ajax call i want to set the current instance of person, but "this" is not scope correct for setting.
There is a more elegant way than using a global variable?
Thank you in advance for your help, and I apologize for my bad English
The jQuery.ajax()[docs] method gives you a context property where you can set the value of this in the callbacks.
Just do:
context: this,
...in your call, as in:
this.GetById = function (id) {
return $.ajax({
type: "POST",
context: this, // <---- context property to set "this" in the callbacks
url: "/Services/PersonService.svc/GetPersonById",
data: JSON.stringify(id),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// in here, "this" will be the same as in your "getById" method
}
});
}
You don't need a global.
Just put:
var self = this;
immediately before the return $.ajax(...) line, and then use self to reference the current instance inside the AJAX callback function.
This variable will only be in scope within the GetById() funciton.
Sure, you can put this to a variable and then use that variable in your callback
var self = this;
this.GetById = function (id) {
return $.ajax({
type: "POST",
url: "/Services/PersonService.svc/GetPersonById",
data: JSON.stringify(id),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
...
self = data;
...
}
});
}

Categories