Ali
Ali

Reputation: 267197

How to submit a complex form using Jquery's AJAX?

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?

Upvotes: 3

Views: 2750

Answers (3)

kkyy
kkyy

Reputation: 12460

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.

Upvotes: 2

Danita
Danita

Reputation: 2514

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.

Upvotes: 13

kgiannakakis
kgiannakakis

Reputation: 104188

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.

Upvotes: 5

Related Questions