submitting form and variables together through jqu

2019-02-20 18:51发布

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 ?

2条回答
成全新的幸福
2楼-- · 2019-02-20 18:57

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-20 19:12

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

查看更多
登录 后发表回答