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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Is it possible to pass additional arguments with the model in ajax? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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)};              

});

Answer

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.

We are here to answer your question about Is it possible to pass additional arguments with the model in ajax? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji