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

2 Answers 2

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().

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

1 Comment

Yeah, 2nd choice is what i finally used. I can't modify the source HTML form, that's why i needed a client side solution.
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/

1 Comment

Cool, i forgot to tell i needed a client side solution. mrlew pointed to the right direction. Thanks anyway man.

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.