1

I have this form

<form action="" method="post">
  <input type="hidden" name="one" value="somevalue">
  <input type="hidden" name="two" value="anothervalue">
  <input type="hidden" name="three" value="someothervalue">
</form>

I also can use jQuery.

How can i serialize the form data to get the $.post() or $.ajax() methods to send the data in the HTTP request this way:

mydata[one]: somevalue
mydata[two]: anothervalue
mydata[three]: someothervalue

Instead of:

one: somevalue
two: anothervalue
three: someothervalue
Eduardo Escobar
  • 3,301
  • 2
  • 18
  • 15

2 Answers2

1

Two suggestions:

1) set the name directly:

<input type="hidden" name="mydata[one]" value="somevalue">

2) change the form's names after load (if you want some dynamic behavior). Something like that (not tested):

$(document).ready(function() {
    var prefix = 'data'; //or get from some data- attribute
    $('form input').each(function() {
        $(this).attr('name', prefix + '[' + $(this).attr('name') + ']' );
    });
});

Then, if you want to send your data via AJAX+jQuery, one approach is to serialize your form data with serialize().

mrlew
  • 7,078
  • 3
  • 25
  • 28
0

You cannot send an array through $.ajax(), but you can send a JSON string. So, something like this would work:

var frm = $(document.myform);
var data = JSON.stringify(frm.serializeArray());

Example:

$.ajax({
    type: "POST",
     url: targetURL,
    data: JSON.stringify($('#form').serializeArray())
})
.done(function(data){
      console.log(data);
      return true;
})
.complete(function() {})
.error(function(xhr, textStatus, errorThrown) {
     console.log('ajax loading error...');
     return false;
    }
});

On PHP side, use json_decode to turn the JSON back into an array:

// decode JSON string to PHP object, 2nd param sets to associative array
$decoded = json_decode($_REQUEST['data'],true);

output values:
foreach ($decoded as $value) {
   echo $value["name"] . "=" . $value["value"];
}

References:

https://www.sitepoint.com/jquery-php-ajax-json/

https://stackoverflow.com/a/11338832/1447509

https://jsfiddle.net/gabrieleromanato/bynaK/

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111