I am developing some software that makes ajax calls to a web API and returns some data. After completing the majority of work, I am going back through to see if i can refactor any code. From this I have realised that I make multiple ajax calls which have the same function asides from the parameters passed into them. With this in mind I wanted to refactor the ajax call into a reusable function or component of which I can then pass in different parameter fro each call, significantly reducing the amount of code. This is the ajax call I have created:
function AjaxCall (ajaxUrl, ajaxData){
return $.ajax({
type: "GET",
url: ajaxUrl,
data: {
ajaxData: ajaxData
},
dataType: 'JSON'
});
}
Later in my code I have then invoked this functioned as so…
var brandId = $('#brandDropdownList option:selected').prop('id');
var ProductUrl = "http://localhost:54442/api/products/GetProducts";
var getProducts = AjaxCall(ProductUrl, brandId);
getProducts.done(function(data) {
$('#productDropdownList').html('').append('<option id="-1" disabled selected="selected">Please Select a Product...</option>');
$.each(data, function(key, val) {
$('#productDropdownList').append('<option id="' + val.productId + '">' + val.productName + '</option>');
})
})
In this I get the id of a field from the UI and stored it in a variable called brandId. I then set the URL for the ajax call to use. I then invoke the function AjaxCall passing in productUrl and brandId. getProduct.done is then the success of which I append the data to a dropdown however this is relevant in the context of the question.
Basically my question is that where in the reusable component I have used ajaxData, I need the ajaxCall to use the passed in parameter brandId. So the actual ajax call I am wanting is
function AjaxCall (ajaxUrl, brandId){
return $.ajax({
type: "GET",
url: ajaxUrl,
data: {
brandId: brandId
},
dataType: 'JSON'
});
This results in a request to the following URL “http://localhost:54442/api/products/GetProducts?brandId=1” which is what I want. But every time I want to make an ajax call the variable brandId will change for example to productId. So is there a way to have a reusable ajax call that I can pass in the different variables (brandId, ProductId to name a few) but also changing the variable in the data section of the ajax call to the passed in variable as otherwise the resulting URL is as follows: “http://localhost:54442/api/products/GetProducts?ajaxData=1“.
Hopefully this makes sense. Thanks in advance
2
Answers
In the function, the
data:
property passed to$.ajax()
should beajaxData
:Then when you call it you can pass an object with any parameters you want:
Sure, just make the second parameter take an object as argument. This way you can pass any amount of parameters into the
$.ajax
call.