views:

1028

answers:

4

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?

+4  A: 

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.

kgiannakakis
this is the best idea. It also allows you to upload files via ajax.
Ionut Staicu
+8  A: 

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.

Danita
A: 

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.

kkyy
A: 

Thanks, i just decided to use a conventional submit instead. Not enough time to waste on configuring this.

Click Upvote
You could at least give the points to someone who actually answered the question for others who might want to do it.
Rex M