Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit a form and pass some extra parameters to a $.getJSON callback method?

I know how to pass some parameters to a JQuery $.getJSON callback method, thanks to this question:

$.getJSON('/website/json',
{
  action: "read",
  record: "1"
}, 
function(data) {
   // do something
});

And I can also submit a form to a $.getJSON callback method:

$.getJSON('/website/json', $(formName)
function(data) {
   // do something
});

But I want to pass some parameters AND submit some form elements. How can I combine the two things togheter?

I could serialize the form elements and manually add some parameters to the url, and it looks like it works:

$.getJSON('/website/json',
  'action=read&record=1&'
  + $(formName).serialize(),
function(data) {
   // do something
});

But it doesn't look very elegant. Is this the proper way, or there's a better way to do it?

like image 785
fthiella Avatar asked Oct 30 '22 18:10

fthiella


1 Answers

We could implement the functionality demonstrated in this answer as a custom jQuery instance method which produces an object of key/value pairs from a form and combines it with the properties that aren't derived from the form:

$.fn.formObject = function (obj) {
    obj = obj || {};
    $.each(this.serializeArray(), function (_, kv) {
        obj[kv.name] = kv.value;
    });
    return obj;
};

$.getJSON('/website/json', $(formName).formObject({
    action: "read",
    record: "1"
}), function(data) {
   // do something
});
like image 51
sdgluck Avatar answered Nov 11 '22 05:11

sdgluck