2

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

1
  • 1
    Your 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. Commented Aug 5, 2011 at 15:08

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

yep i switched to serialize and it is working now. thanks for the switching to the name value tip. it is working now. Thanks!! :-)
1

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();
     }            
});

2 Comments

when i do a print_r($_POST) all i got was array()
That means your post variable aren't being set. I'd use serialize as is suggested above or use a string method "param1=value&param2=value2" etc
0

Try this

var param = $('form').serialize();

$.post("example.php", param);

1 Comment

Note that it won't work unless you've set the names of the inputs appropriately. Use names not IDs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.