mvc_help mvc_help - 2 months ago 18
Javascript Question

Housing $.AJAX inside a function and using a paramter as part of the "data" argument

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

http://imgur.com/a/GSaPd

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

Answer

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.