-1

I'm trying to create a reusable function that will allow me to call an AJAX request and use one of the passed in parameters as an argument in the data section of the AJAX call.

// Returns AJAX data for updating other fields based on a dropdown changing
App.prototype.OnDropdownChange = function (s, e, newId, ajaxParameter, ajaxRequestURL) {
    // Create an AJAX request based on the parameters
    $.ajax({
        url: ajaxRequestURL,
        data: JSON.stringify({ ajaxParameter: newId }),
        type: 'POST',
        success: function (data) {
            // Return the data
            return data;
        },
        error: function (data) {
            // Error
            return data;
        }
    });
}

The "ajaxParameter" would, ideally, hold the name of the parameter being passed up. So for example, "ajaxParamter" contains "theNewID" which is what my MVC controller is expecting as a parameter however when it's passed up it is shown as "ajaxParameter" and not the value inside.

How can I get this working?

EDIT

https://i.stack.imgur.com/ocJBi.jpg

See here how it shows as ajaxParameter? What I want is that to be whatever I pass it in as.

mvc_help
  • 187
  • 9
  • Yeah, that's entirely possible, assuming you control what calls said function. – Kevin B Sep 08 '16 at 15:18
  • I do control what calls it, but what gets logged is "undefined". var data = x.OnDropdownChange(s, e, contactID, "CustomerContactId", "/Project/Project/GetCustomerContactDetails/"); console.log(data); – mvc_help Sep 08 '16 at 15:19
  • uhm... lol you can't return from an async callback. – Kevin B Sep 08 '16 at 15:19
  • It's not the return that's the issue, it's the fact that if I pass in "theNewID" as the ajaxParamater (because my server side controller is expecting "thenewID" as the parameter) but it passes "ajaxParameter" to the controller instead of what's containing inside the ajaxParameter. – mvc_help Sep 08 '16 at 15:23
  • uhm... you named the parameter "ajaxParameter", of course it's goign to pass that key with a value, in json format. – Kevin B Sep 08 '16 at 15:23
  • you'd be better just to pass the data in as a ready-formed JSON object. Then you have complete control over it. – ADyson Sep 08 '16 at 15:24
  • You need to open the console and look at what is actually being sent. This is more likely an issue server-side. – Kevin B Sep 08 '16 at 15:24
  • @ADyson thats... what he is doing.. – Kevin B Sep 08 '16 at 15:25
  • Yeah dude I understand that, what I wanna know is if there is a way to use what ajaxParameter contains as the key? Because I have a lot of $.ajax calls and wanted to be able to have a reusable method and just change what ajaxParameter gets passed in. – mvc_help Sep 08 '16 at 15:25
  • @KevinB no he isn't, he's passing "ajaxParameter" and "newID" which are both strings. But he thinks that putting "ajaxParameter" in the json object in the "data" is going to write the contents of the passed-in "ajaxParameter" variable as the name of the parameter in the JSON object. What I'm saying is that his function should just accept a single ready-formed JSON object to be used as data, instead of the two separate parameters. Then he'd have total control over what the key is named for each call. – ADyson Sep 08 '16 at 15:26

2 Answers2

4

You can do what you require, you just need to build the object using bracket notation to define the key.

However a much larger problem is your use of return within the success and error handlers. As the AJAX request is asynchronous you cannot return anything from it. Instead you need to provide callback functions to be executed under those events. Try this:

App.prototype.OnDropdownChange = function (s, e, newId, ajaxParameter, ajaxRequestURL, sCallback, eCallback) {
    var data = {};
    data[ajaxParameter] = newId;

    $.ajax({
        url: ajaxRequestURL,
        data: data, // note no need to stringify the object
        type: 'POST',
        success: function (data) {
            sCallback && sCallback(data);
        },
        error: function (x, s, e) {
            eCallback && eCallback(x, s, e);
        }
    });
}

You can then call that like this:

x.OnDropdownChange(s, e, contactID, "CustomerContactId", "/Project/Project/GetCustomerContactDetails/", function(data) {
    // success:
    console.log(data);
}, function(x, s, e) {
    // error:
    console.log(x, s, e);
}); 

As you can see from this code, it's still quite verbose and is essentially now just a wrapper for $.ajax with very little benefit.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thanks for taking the time to read my problem and respond man. Works like a charm, appreciate the help. – mvc_help Sep 08 '16 at 15:31
0

First of all when you are passing an obj in the data paramater of $.ajax request you don't need to stringify it unless i presume that you are storing like a JSON string in a database.

Second you can't return the data provided by the success, error, beforeSend and complete callback functions of the ajax request as they are a function itself and you are just returning the data to the callback function itself.

To get the data from the callback function to your original function you need to use a temporary variable to store the data you need to return

var myAjaxDatavalue = (function(myMethod,myData,myUrl){
   var temp = null;
   $.ajax({
      method: myMethod,
      url: myUrl,
      data: myData,
      async: false,
      success: function(result){
         temp = result
      }.
      error: function (xhr, ajaxOptions, thrownError){
         console.log(xhr);
      }
   });
   return temp;
})();

but beware as you can see one of the purpose of ajax, which being an asynchronous will be disable. This may lead to problems if your getting an enormous amount of data.

Daren Delima
  • 131
  • 8