0

When inside a function can I get it's parameters name/value?

I'm looking to turn those into an object that I can JSON.stringify() so I can pass it as data to an ajax call.

[EDIT] Thanks to others pointing me in the right direction I have a solution that dynamically creates parameters that match the webmethod with a client stub that matches the webmethod as well. This, I think, helps make things more readable.

[EDIT2] Took it a step further. Now the function name in javascript must match the name of the webmethod, and now you pass to it as the first param the page the webmethod exists on. It dynamically takes the client javascript function name, and that's what it's looking for now for the webmethod.

Here are the common methods that you create somewhere in your code:

    function WebMethodCall(args) {
        // in your stubs call this to get argname/value pairings in JSON form
        var params = JSONArgs(args);
        var fun = GetFunctionName(args);

        // make a call to the webmethod via ajax using json
        AjaxPostJSON(args[0] + "/" + fun, params, args);
    }

function JSONArgs(args) {
        var tmp = args.callee.toString().match(/\(.*?\)/)[0];
        var argumentNames = tmp.replace(/[()\s]/g, '').split(',');

        var param = new Object();
        for (var i = 0; i < argumentNames.length; i++) {
            param[argumentNames[i]] = args[i];
        }

        return JSON.stringify(param);
    }

    function GetFunctionName(args) {
        var fName = args.callee.toString().match(/function ([^\(]+)/)[1]

        return fName;
    }


    function AjaxPostJSON(url, data, args) {
        var objGetData = new Object();
        var fun = GetFunctionName(args);
        var s = "On" + fun + "Success";
        var f = "On" + fun + "Failure";

        objGetData.url = url;
        objGetData.type = "POST";
        objGetData.data = data;
        objGetData.contentType = "application/json; charset=utf-8";
        objGetData.dataType = "json";
        objGetData.success = window[s];
        objGetData.error = window[f];

        $.ajax(objGetData);
    }

The stub where the parameter names should match the webmethod parameter names. The function name MUST also match the webmethod function name. Note that page is required to be the first parameter, but shouldn't be in your webmethod. It's simply used here to make the call correct: // function stub function GetData(page, id, name) { WebMethodCall(arguments); }

Notice the success and failure name patter of "On" + func_name + "Success"/"Failure". The usage:

    function Button2_onclick() {
        // call client side stub that matches the webmethod
        GetData("Default.aspx", 8, "Bob");
    }

    // automatically registers these as success/error
    function OnGetDataSuccess(data) {
        alert(data.d);
    }

    function OnGetDataFailure(data) {
        alert("failure");
    }

The nice thing about this, I think, is that when I change/add parameters to my webmethod, it's so easy to just get the client javascript method and change the parameter names to match the webmethod and that's it.

user441521
  • 6,942
  • 23
  • 88
  • 160
  • Sorry, that probably sounds odd. When I say name I mean the string name of the param not the variable name because I need to create an object dynamically with the string var name. I'm making a function to do this so it can be used for any function I make. Basically creating stub like functions on client to webmethods on server. – user441521 Nov 22 '12 at 13:36
  • You might look here? http://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically-from-javascript – TryingToImprove Nov 22 '12 at 13:37

4 Answers4

1

You can get the values with the arguments object. The names are a bit trickier, you'd have to parse the function's string representation.

I'd prefer directly passing an object to the function: myFunction({name: value}) and pass that object directly to JSON.stringify.

instanceof me
  • 38,520
  • 3
  • 31
  • 40
  • The reason I'm actually thinking of doing this is because I dislike the shorthand object creation method in javascript. I'm trying to ease calling ajax (the syntax is horrible) by making client side stubs. It would have been nice to be able to get the parameter name/value to automatically create the json object. As long as I made the client side function the same param names as the server side it would be very easy and very reader friendly. – user441521 Nov 22 '12 at 13:44
1

if I understood you, you want to obtain the "name" of the variable as a "value", if that is the case, no, you can't, a variable name is just a symbol that helps you as a programmer to distinguish them, but there is no way you can get that 'meta-data' information, this is why we now prefer to use json to provide a more meaningful object as a data-transfer object.

Jorge Alvarado
  • 2,664
  • 22
  • 33
1

Does this help?:

function test (name, pass){
    var params = (test.toString().substring(test.toString().indexOf('(')+ 1, test.toString().indexOf(')'))).replace(/ /g, '').split(',');
    var obj = new Object();
    var js = "";
for(var i=0;i<arguments.length;i++){
        js += 'obj.'+ params[i]+' = "'+ arguments[i]+'";';
    }
     eval(js);
     JSON.stringify(obj);
}
Reporter
  • 3,897
  • 5
  • 33
  • 47
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
  • Will that work for an ajax call to a webmethod? My understanding, and testing, is showing that the property name of the object needs to match the webmethod parameter name. – user441521 Nov 22 '12 at 13:50
  • The variable namely arguments holds the list of parameters passed to it. – Akhil Sekharan Nov 22 '12 at 13:53
  • Right, but arguments doesn't have the name of the parameter. When making an ajax call to a webmethod it's my understanding the jason object needs the same name as the webmethod param ie {id:5}. When I do your code above I get {"0": 5}. I want to define my javascript function parameter id, the same as the webmethod and extract that so my json object looks like {"id":5} – user441521 Nov 22 '12 at 13:56
  • This does. With the help of others here I also got a solution that I've posted in my original post. Very similar. Thank you! – user441521 Nov 22 '12 at 14:29
  • Is there a way now that I could pass a created from string function to the success and error parameters of the ajax call? Based on the client method name I want to say prefix with "On" + functionName + "Success" and get that function (the user would be responsible to create it) and pass that automatically to success/error variables. Basically it's like getting a function pointer via a string function name. – user441521 Nov 22 '12 at 14:42
0

Yes you can ... Buts its really a simple thing, google would have helped

function myFunction(name,job) {
 alert("Welcome " + name + ", the " + job);
}
toxicate20
  • 5,270
  • 3
  • 26
  • 38
  • Sorry didn't explain myself very well. I actually want, dynamically, the "name", & "job" so that I can make an object that has a property "name" with the value name, and property "job" with the value job. – user441521 Nov 22 '12 at 13:45