I have an array in Javascript that i am trying to pass to php. my array looks like this.
Array[0]
"empNo" : "1347"
"empName" : "John Doe"
I am building this array from this javascript:
$('input[type=text]').each(function()
{
if ($(this).attr("value").length>0)
{
param[$(this).attr("id")]=$(this).attr("value");
}
});
Then I pass the array to php using
$.post("example.php",param)
Then in php when I try to interact with the post like this:
$emp=$_POST['empNo'];
$name=$_POST['empName'];
echo ($_GET[0]);//this is for testing
It throws an error saying that The Indexes of empNo and empName are not Defined.
It also says that 0 is an undefined offset.
Thanks for the help
-
1Your problem is either in Javascript or PHP and your first step should be to figure out which one. Use Firebug net tab to determine if the POST is being made correctly, then work back or forward.Michael Lorton– Michael Lorton2011年08月05日 15:08:14 +00:00Commented Aug 5, 2011 at 15:08
3 Answers 3
Instead of looping through and manually building your data to pass just do this for the whole form.
var data = $('form').serialize();
$.post("example.php", data);
Then you should have access as you expect in your php script.
BUT make sure you're using the <input name="exampleName" /> attribute and then try to access them like this...
$value = $_POST['exampleName'];
while right now, it looks like you're trying to use the id instead of name
1 Comment
My first guess would be that $_POST has an array whose members are the values you are sending.
So, I think the values are in $_POST[1], $_POST[2], etc...
Try to print_r($_POST) and see where your variables went to.
Response to your comment:
I would tidy up things a bit, just a suggestion - especially the attr('value') part.
$('input[type=text]').each(function() {
if ( $(this).val() ) {
param[$(this).attr('id')] = $(this).val();
}
});
Try this
var param = $('form').serialize();
$.post("example.php", param);
1 Comment
names of the inputs appropriately. Use names not IDs.