I am sending a serialized form with $.post to a Controller PHP:
$.post('/Controller.php',
{
action: 'register',
data: $('#regForm').serialize()
},
function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
},
"json"
);
I would now expect to be able to access the Form fields by $_POST['fieldname'] but INSTEAD I have a Get like parameter string in $_POST['data'] -.- What do I do wrong ?
It's sending the data just as you told it to. .serialize()
creates a "query string", which you added into $_POST['data']
.
Instead of what you have, try this:
var formData = $('#regForm').serialize();
var extraFields = {action: 'register'};
$.post('/Controller.php', $.param(extraFields)+'&'+formData, function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
}, 'json');
Now you should be able to get $_POST['action']
and $_POST['fieldname']
.
the $.post format is like this:
jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
so your first parameter is url correct, the second is data. that is why you are getting $_POST['data'] and $_POST['action'] as post parameters, since indeed you send two url parameters 'action' and 'data'. you could do like this and send the form directly as data:
$.post('/Controller.php',
$('#regForm').serialize(),
function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
},
"json"
);
then you'll get what you ask for, $_POST['fieldname']
Make sure that your input fields in your form have the name
attribute assigned otherwise jQuery will not send the data correctly.
The other option is to use serializeArray
. The difference between the two has been discussed here.
$.post('/Controller.php',
{
action: 'register',
data: $('#regForm').serializeArray()
},
function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
}
)