Welcome to the Treehouse Community
Looking to learn something new?
Bill Dowd7,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'].
Aaron Graham18,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.