views:

56

answers:

2

Hi guys,

I have a bunch of fields that have the same class, now what I am trying to do is get the id and value of each one, create an array, and then using $.ajax send it to a PHP script, which will run through each one and enter it into the database.

I tried using JSON, but my server does not have support for json_decode, which is essential for me to decode the data and enter it into the database, I have also tried using Zend Json but for some reason that wont work either, probably due to character encoding issues, so I am stuck trying to send an array of data and traverse the array in the php file, I really really need some help getting this going, so any help would be appreciated, the JSON I was sending to the PHP file looked like this,

[{"id":"1","value":"one"},{"id":"2","value":"two"},{"id":"3","value":"three"}]

Is there a way for me to substitute that with an array and traverse through it using PHP?

Thanx in advance!

+1  A: 

You could try sending your ajax request in a more PHP friendly manner. For instance this:

$.ajax({  url : 'http://yourdomain.com', 
          data : { 
                    'item[1]' : 'one', 
                    'item[2]' : 'two', 
                    'item[3]' : 'three' 
                  }
         });

will send a request like this:

http://yourdomain.com/?item[1]=one&item[2]=two&item[3]=three

and the data will be available in the PHP var $_GET['item'] which you can loop through like this:

foreach($_GET['item'] as $id => $value) {
     // insert, etc..
}
owise1
Michael Merchant is totally right that you should probably use { 'type' : 'post' } in your ajax call to send a POST instead of a GET request, since you mention that you'll be modifying a database. However, the result in PHP will be in the variable $_POST['item'] not $_POST['item[1]']
owise1
A: 

If you're trying to make a POST request and for whatever reason, it matters for you to not send a GET request (for example, you're modifying information stored on the server), you may want to use:

$.ajax({  url : 'http://yourdomain.com', 
          data : { 
                    'item[1]' : 'one', 
                    'item[2]' : 'two', 
                    'item[3]' : 'three' 
                  },
          type: "POST",
         });

You can then access the data on your server from the $_POST dictionary by calling:

$_POST['item[1]']
Michael Merchant