Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a javascript object array to php using POST

Lets say I have an array of javascript objects, and I am trying to pass those objects to a php page to save them into a database. I have no problems passing a variable to the php and using $_POST["entries"] on that variable but I can't figure out how to pass an entire array of objects, so I can access my objects.entryId and .mediaType values on the php page.

Oh and before anyone asks, yes the reason I need to do it this way is because I have a flash uploader, that you guessed it.. uploads into a CDN server (remote) and the remote server only replies back with such js objects.

Thanks for any help anyone can provide.

Here is my JS functions:

function test() {
        entriesObj1 = new Object();
        entriesObj1.entryId = "abc";
        entriesObj1.mediaType = 2;
        entriesObj2 = new Object();
        entriesObj2.entryId = "def";
        entriesObj2.mediaType = 1;

        var entries = new Array();

        entries[0] = entriesObj1;
        entries[1] = entriesObj2;
        var parameterString;

        for(var i = 0; i < entries.length; i++) {
            parameterString += (i > 0 ? "&" : "")
              + "test" + "="
              + encodeURI(entries[i].entryId);
        }

        xmlhttp.open("POST","ajax_entries.php",true);

        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", parameterString.length);
        xmlhttp.setRequestHeader("Connection", "close");

        xmlhttp.onreadystatechange  = handleServerResponseTest;
        xmlhttp.send(parameterString);
    }
    function handleServerResponseTest() {
       if (xmlhttp.readyState == 4) {
         if(xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
         }
         else {
            alert("Error during AJAX call. Please try again");
         }
       }
    }
like image 445
jesusOmar Avatar asked May 21 '09 03:05

jesusOmar


1 Answers

maybe you need to take a look at json and jQuery ajax methods:

.- http://blog.reindel.com/2007/10/02/parse-json-with-jquery-and-javascript/

.- http://us.php.net/json_decode

The turorial is maybe a little outdated because jQuery last version is 1.3.x but you will get an idea on that and about the PHP json functions... if your server does not have the json extension enabled you can use some php classes:

.- http://google.com.co/search?rlz=1C1GPEA_enVE314VE314&sourceid=chrome&ie=UTF-8&q=php+json+class

good luck!

like image 90
coma Avatar answered Oct 18 '22 04:10

coma