submitting form and variables together through jquery

喜夏-厌秋 提交于 2019-12-19 11:51:25

问题


I'm using 2 types of submit.

There is $.post

$.post('servers_side.php', { var1: var1, var2:var2},
function(result) 
{
some code...
});

which sends separate variables to server side script.

And there is AjaxSubmit plugin which submits the whole form

$('#form').ajaxSubmit({success: function(result)
{
some code...
}
});

But now I have the following task let's say I have a form and a few variables which I must submit at the same time.

So Is that possible to submit form + some variables together ?


回答1:


Update

And here is how you can submit:

var Vars = {var1: var1, var2:var2};
var varsData = $.param(Vars);

// form data
var formData = $('#formID').serialize();

var data = varsData + '&' + formData;

$.ajax({
  type: 'POST',
  url: 'servers_side.php',
  data: data,
  success: function(res){ alert (res) }
})

You can use jQuery.param() to convert an array or an object into url-friendly name-value paris. You may also need to use jQuery.serialize() to convert form data into name-value paris. Here is how you can go about:

var Vars = {var1: var1, var2:var2};
var varsData = $.param(Vars);

// form data
var formData = $('#formID').serialize();

var data = varsData + '&' + formData;

Now data contains all data of your custom vars and form elements you can send in ajax request.




回答2:


Well, it's possible but code might look messy. As best practice you should add some hidden fields

<form>
   .
   .
   .
   <input type="hidden" name="var1" id="var1" />
   <input type="hidden" name="var2" id="var2" />
   <input type="hidden" name="var3" id="var3" />
   .
   .
   .
</form>

And use this JavaScript to set values to these hidden fields

$("#var1").val("some data 1");
$("#var2").val("some data 2");
$("#var3").val("some data 3");

And you can carry on with your existing $.post() code



来源:https://stackoverflow.com/questions/8103374/submitting-form-and-variables-together-through-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!