Skip to content Skip to sidebar Skip to footer

Function As Parameter In Jquery Ajax

Is it possible to put a function into a parameter for Jquery Ajax like below. dataType and data are given as functions. dataType returns a value of JSON if the returntype is JSON a

Solution 1:

From the manual:

data Type: PlainObject or String

So no.

Call the function. Use the return value.

data: function () { ... }();
//                       ^^ call the function

Solution 2:

Not that way. But it will work with a little change:

(function () {
    if (isJson == true) {
        return"JSON";
    } else {
        return"text";
    }
})()

That should work. You just call the function immidiately after you created it. This way, dataType is a String and the script will work. Same with data. Also use the (function(){})()-notation here

Solution 3:

jquery just adds a : to the end of the request like so:

{dataVar[0]:dataVal[0]}:

No, your devtools display does. However, as you're data string does not contain a = sign, and you send the content as application/x-www-form-urlencoded, the whole body is interpreted as if it was a parameter name.

For sending JSON, you should:

  • use contentType: "application/json"
  • use data: JSON.stringify(_.object(dataVar, dataVal))

to ensure valid JSON is sent with the correct header (and correctly recognised as such at the server).

1: _.object is the object function from Underscore.js which does exactly what you want, but you can use an IEFE as well: JSON.stringify(function(p,v){var d={};for(var i=0;i<p.length;i++)d[p[i]]=v[i];return d;}(dataVar, dataVal))

Solution 4:

You need to call the function with parenthesis like below:

function func1(){
//func1 code in here
}
function func2(func1){
//func2 code in here//call func1 like this:func1();
}

So, you can use like this:

data: function () {
//your stuff her
}(); // which mean you are having data()

Post a Comment for "Function As Parameter In Jquery Ajax"