Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass additional arguments with the model in ajax?

Using the script bellow to pass a strong typed model and it is working fine. Is there a way to also include, with the model, the value of the vars, as additional arguments? I know how to pass either the model or the vars, but not both.

var sample1 = "aaa";
var sample2 = "bbb";

    $.ajax({

   url: "Action/Controller",
   data: $("#form123").serialize(),       
   cache: true,
   type: "POST",
   dataType: 'html',                                
   success: function (data) {                       
   $('#form123').html(data)};              

});
like image 337
Ben Junior Avatar asked Dec 03 '25 05:12

Ben Junior


2 Answers

Use $.extend to merge multiple objects together:

data: $.extend(
   $("#form123").serialize(), 
   { something: 'else'}, 
   { and: 'even', more: 'things'}
)

Alternatively, just add the other fields to your form as <input type='hidden' ...> elements

like image 171
Robert Levy Avatar answered Dec 05 '25 17:12

Robert Levy


You can set the data object to include three properties, one for the serialized form and the others for the samples.

data: {
  formData: $("#form123").serialize(),
  sample1: sample1,
  sampleTwo: sample2
}

Update: In light of this solution's not working in your case, here is an alternative.

Since the result of .serialize() is to turn its input into standard URL-encoded form such as prop1=val1&prop2=val2, you could append your additional variables to the output string. For example,

var formData = $("#form123").serialize() + '&' + sample1 + '&' + sample2;
$.ajax({
  ...
  data: formData,
  ...
});

However, this is somewhat kludgy, not readily extensible to larger numbers of additional parameters, and should not be done without sanitizing the values of sample1 and sample2.

Depending on your situation this may be a workable solution, but I think that Robert Levy's suggestion of adding the data to hidden inputs in your form is probably a better one.

like image 24
Michael Avatar answered Dec 05 '25 19:12

Michael