Using jQuery.serialize () in ajax array to pass PHP $ _POST as variables?

This is the jQuery code that I use to submit form details to a php function:

jQuery(document).ready(function($) { jQuery('.submit').click(function(){ var str = $("#ajaxForms").serialize(); var data = { action: 'myajax-submit', serialize: str, beforeSend: function(){ alert('Sending...'); } }; jQuery.post(MyAjax.ajaxurl, data, function(response) { alert('Got this from the server: ' + response); }); return false; }); }); 

and this is the php function:

 function myajax_submit() { $whatever = $_POST['serialize']; echo $whatever; die(); } 

Everything works, but when a warning window appears, the text displays a string of values ​​from my html form #ajaxForms . I believe this is because the php function echos $_POST['serialize'] .

In my form, I have an input field, for example:

<input id="postID" name="postID" value="First Name" type="text" />

but when I try to execute the echo variable $_POST['postID'] in php, it does not display anything in the warning field.

I thought, by sending form data serialized to a php function, could I use the $ _POST variable associated with the form inputs?

Help evaluate. :)

+8
jquery php serialization
source share
2 answers

By serializing the form input with jQuery serialization, you create a line like:

 a=1&b=2&c=3&d=4&e=5&postID=10 

To get postId, you need to de-serialize $ _POST ['serialize']. For this you need to do something like:

 parse_str($_POST['serialize'], $whatever); 

Now $whatever['postID'] is what you are looking for.

Edit: Fix parse_str () :)

+10
source share

You are not implementing $.post correctly. .serialize() returns a string. So, when you pass serialize: str to $.post() , the form itself is no longer added, but a simple string containing the serialized form.

The code below is correct using $.ajax (see commented lines).

 jQuery('.submit').click(function(){ var str = $("#ajaxForms").serialize(); // If you realllly. want a parameter serialize, uncomment the following line // str += '&serialize=' + encodeURIComponent(str); str += '&action=myajax-submit'; jQuery.ajax(MyAjax.ajaxurl, { method: 'POST', data: str, success: function(response) { alert('Got this from the server: ' + response); }, beforeSend: function(){ alert('Sending...'); } }); return false; }); 
+7
source share

All Articles