I have many functions on a page, where the following code is exactly the same, except for the data being sent, and the success div to display the result to. For example:
One ajax post:
$.ajax({
type: 'POST',
url: 'unique_file.php',
data: {qty: 2, item_id: 13},
cache: false,
success: function(data) {
$('#return_div').html(data);
}
});
Another ajax post:
$.ajax({
type: 'POST',
url: 'another_unique_file.php',
data: {no_shipping: 4},
cache: false,
success: function(data) {
$('#a_different_div').html(data);
}
});
So I was thinking it would be ideal to make this into a function like so
function do_ajax(post_file,results_div,post_data) {
$.ajax({
type: 'POST',
url: post_file,
data: {post_data}, // this doesn't appear to work
cache: false,
success: function(data) {
$(results_div).html(data);
}
});
}
Then I can achieve #1 ajax like so:
do_ajax('unique_file.php','#return_div','qty: 2, item_id: 13');
This seems logical to me, but the limits of my logic are how to get the data into my function. Perhaps the post_data is not just a string like that but more something like:
do_ajax('purchase_create.php','#create_purchase_window','item_id:'+$item_id+', qty: '+$qty+'');
Which looks pretty messy… but mostly, it just doesn’t work. Is there a cleaner way of perhaps putting all the data into an array and giving that to the function?
You’re on the right track:
You’re passing an object to
POST, so just pass that object into yourdo_ajaxfunction and pass it along.