2

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 and text if isJson is false.

dataVal and dataVar are arrays containing the parameter names and values used to construct the data paramater. The result of the data: function would be a string as:

{dataVar[0]:dataVal[0],dataVar[1]:dataVal[1],.....,}

I'm getting an error when I try this, so, just wanted to know if this method was possible.

function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
    $.ajax(page, {
        type: 'POST',
        dataType: function () {
            if (isJson == true) {
                return "JSON";
            } else {
                return "text";
            }
        },
        data: function () {
            var dataString = '{';
            for (var i = 0; i < dataVar.length; i++) {
                dataString = dataString + dataVar[i] + ':' + dataVal[i] + ',';
            }
            console.log(dataString);
            return dataString + '}';
        },
        success: function (res) {
            dfd.resolve(res);
        }
    });
}

Edit

As per answers and comments, made the changes. The updated function is as below. This works:

function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
    $.ajax(page, {
        type: 'POST',
        dataType: isJson ? "JSON" : "text",
        data: function () {
            var dataString ="";
            for (var i = 0; i < dataVar.length; i++) {
                if (i == dataVar.length - 1) {
                    dataString = dataString + dataVar[i] + '=' + dataVal[i];
                } else {
                    dataString = dataString + dataVar[i] + '=' + dataVal[i] + ',';
                }
            }
            return dataString;
        }(),
        success: function (res) {
            dfd.resolve(res);
        }
    });
}

And my original question is answered. But apparently, data is not getting accepted.

The return value of the data function is just treated as the parameter name and jquery just adds a : to the end of the request like so:

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

So, my server is unable to pick up on the proper paramater name.

7
  • I don't think so, you'd have to set data and dataType as the result of the execution of these functions Commented Apr 15, 2014 at 6:45
  • 1
    WTH don't you use JSON.stringify? Commented Apr 15, 2014 at 7:13
  • 1
    Just put dataType: isJson ? "JSON" : "text", Commented Apr 15, 2014 at 7:16
  • @Bergi: The code works now, as per answers but the 'data' result is not accepted. Apparently the return value is just treated as the parameter name. The sent data is like so: {TableName:tblLGRQueryTracking}: Commented Apr 15, 2014 at 7:19
  • Not accepted by what? Is the data invalid or the format? {TableName:tblLGRQueryTracking} is no valid JSON at least Commented Apr 15, 2014 at 7:24

4 Answers 4

2

From the manual:

data
Type: PlainObject or String

So no.

Call the function. Use the return value.

data: function () { ... }();
//                       ^^ call the function
Sign up to request clarification or add additional context in comments.

1 Comment

Original question answered. Thank You..:-)
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

1 Comment

There's no need to wrap the whole thing in parenthesis, it's inside an object literal so it is already in a context that will make it a function expression instead of a function declaration.
1

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))1

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

3 Comments

What if I just wanted to send data as data: { dataVar[0]: dataVal[0] } as I've been successfully doing for a long time and not as JSON content.
Do as you want if it works, but a) don't call it "JSON" b) don't expect your server to parse it correctly c) don't expect devtools to display the request properly
Thanks, the JSON.stringify method works wonders. And I took your hint and tried adding an equals instead of a semicolon and the server side program seems to accept it. Fragile, yet working. Thanks for all your help...:-)
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.