5

Quick question

If I have serialized a form using jquery's .serializeArray(); function do I need to do anything to it before I can send it off using jquery's ajax data:?

e.g. can I send off

[{name: inp1, value: 'val1'}, {name: inp2, value: 'val2'}] as is, or do I need to preprocess it somehow?

and, in php how would I read this?

Hailwood
  • 89,623
  • 107
  • 270
  • 423

1 Answers1

32

It would be better here to use serialize. This converts your form's values into a simple string that can be used as the AJAX call's data attribute:

var myData = $('#yourForm').serialize();
// "inp1=val1&inp2=val2"
$.ajax({
    url: "http://example.com",
    data: myData
});

Presuming you send this to PHP using the GET method, you can access these values using $_GET['inp1'] and $_GET['inp2']


Edit: You can convert an array made by serializeArray into a parameter string using $.param

var myData = $('#yourForm').serializeArray();
// remove items from myData
$.ajax({
    url: "http://example.com",
    data: $.param(myData) // "inp1=val1&inp2=val2"
});
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • Post :/ also, I am doing some preprocessing on the returned array (removing the objects that have not been changed from when the form was created), hence why I need the array – Hailwood Feb 01 '11 at 12:12
  • 1
    @Hailwood See updated answer. POST variables will be accessible using `$_POST['inp1']` instead, as per normal in PHP. – lonesomeday Feb 01 '11 at 12:16