Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Bill Dowd
Bill Dowd
7,681 Points

Extracting the results of JQuery's serialize function

It has been over a year since I last wrote a Web app with PHP. I have a fairly simple project that I want to complete, but I very much want to employ JQuery and AJAX. However, I'm struggling with being rusty on my PHP and now I'm trying to learn this new and very cool stuff.

Mostly the app is about interacting with a MySQL database, entering form data and updating that data. I understand that serialize will prepare all the form fields that have data into a "$_GET" type of query string, but I'm struggling with the server side of this.

How do I extract the query string without having to write a bunch of PHP code or function to parse it properly for database updating or inserting? I'm using the JQuery Post, but I'm used to the format $_POST['formfieldname'].

Thanks, Bill

2 Answers

Aaron Graham
Aaron Graham
18,033 Points

Assuming you have a form like this:

<form id="my-form">
  <input name="data">
  <input name="moreData">
</form>

and you sent this to your server like this:

$.post( "yoursite.com/endpoint", $( "#my-form" ).serialize() );

you should be able to get the data like this:

$data = $_POST['data'];
$moreData = $_POST['moreData'];

I'm not exactly sure where your problem is, but it sounds like it might be a naming issue. (?) The critical things is that you use name="" in your html form elements so that your $_POST superglobal has the correct keys in it.

Bill Dowd
Bill Dowd
7,681 Points

Thanks Aaron. The problem was that when I looked at the sample of how the encoded string looks, I took it literally that the entire string was placed inside the $_POST as one value and I was unsure of the key to use to extract it and how I was supposed to parse it from that string. I now realize that the results are just as I've always expected when using forms the regular way.

Bill Dowd
Bill Dowd
7,681 Points

It still uses the $_POST['form_field_name'] just as before.