3

I'm trying to submit a form using Jquery's ajax. It has got a few textboxes, some checkboxes, and a multiple options' dropdown (i.e multiple options can be selected).

Someone here told me that I can get values of all selected checkboxes using

$("input:checkbox[name=type]:checked")

Then I can loop through all the values returned by the above code, assign them to an array like this:

var types=new Array();

    $.each(cboxes, function()
      {
         types[types.length]=$(this).val();
      }
    );

And try to submit the form using this:

var someField=$("#someField").val();
var someField2=$("#someField2").val();
var data={field1 : someField, field2=someField2, s_types:types};
$.post("signup.php?type=p",types);

But that doesn't work, specifically the checkboxes don't get submitted correctly. How can I make it work?

3 Answers 3

13

It's not necessary to iterate over each field to get the form values. jQuery has a method to serialize form inputs into a querystring. You can do this:

$.ajax({
  url: "mybackend.php",
  data: $("#myForm").serialize(),
  success: function(e) { // do something on success },
  error: function(e) { // do something on error }
});

Remember that javascript posts always send data in UTF-8 format, so be sure you're expecting that on the backend if you plan to send text with international characters.

Sign up to request clarification or add additional context in comments.

Comments

5

I recommend using a plug-in to do that. Have a look at this form plug-in. It also can integrate nicely with validation plug-in.

1 Comment

this is the best idea. It also allows you to upload files via ajax.
2

The default jQuery $.param doesn't handle arrays (by design), so you can't use $.serialize as it is. Use either a plugin, like suggested in kgiannakis' answer, or overwrite the $.param function so it'll handle arrays properly:

function($) {
  $.param = function(a) {
    var s = [];
    if (a.constructor == Array || a.jquery) 
      jQuery.each(a, function() { s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) ); });
    else
      for (var j in a)
        if (a[j] && a[j].constructor == Array) jQuery.each( a[j], function(){ s.push( encodeURIComponent(j) + "[]=" + encodeURIComponent( this ) ); });
        else s.push(encodeURIComponent(j) + "=" + encodeURIComponent(a[j]));
    return s.join("&").replace(/%20/g, "+");
  };
})(jQuery);

...and then use $.serialize, like suggested by Danita.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.