submitting form and variables together through jquery

前端 未结 2 1442
醉酒成梦
醉酒成梦 2021-01-17 01:30

I\'m using 2 types of submit.

There is $.post

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

相关标签:
2条回答
  • 2021-01-17 01:53

    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

    0 讨论(0)
  • 2021-01-17 02:08

    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.

    0 讨论(0)
提交回复
热议问题