Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    New Coder
    Join Date
    Sep 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    How do I send Javascript/jQuery array to PHP?

    Hi

    How do I send an array created in jQuery or Javascript to PHP? (page will be redirected to PHP)

    I'm thinking of URL parameters right now, but wont that result to a long URL? Is there another optimized way of sending the array?


    Here's my script. Which doesn't work.

    Here's my script, this works fine...

    send_array_to_other_page.html
    Code:
    $(function(){
        //DECLARE ARRAY
        var arr = new Array();
        var i = 0;
        $('#form').submit(function(e){
            e.preventDefault();
            var value = $('#box').val();
            var index = arr.length;
            var list = ''; 
            //ADD VALUE TO ARRAY
            arr[index] = value; 
            //OUTPUT VALUES IN ARRAY
            for (var index in arr){
                list+=index+': '+arr[index]+'<br/>';
                $('#arrLength').html(arr.length);
            }
            //DISPLAY ARRAY
            $('#display').html(list);
            $('#form').get(0).reset(); //RESET FORM
        });
        $('#send').click(function(){
            window.location = 'send_array_to_other_page_2.php?list='+arr;
        });
    });
    This doesn't. It outputs Array content lost. Id also like to point out the the url of this page is send_array_to_other_page_2.php. Its missing the ?list=
    PHP Code:
    <?php
        $arr 
    $_GET['list'];
        echo 
    'The contents of the array are still... <br/>';
        if(isset(
    $arr)){
            
    print_r($arr);
        } else {
            echo 
    'Array content lost';
        }
    ?>

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,561
    Thanks
    80
    Thanked 4,494 Times in 4,458 Posts
    Only two ways: Query string or post data. And neither way allows you to actually send an array. The best you can do is convert the array to a delimited string and send the string.

    So the easy way to do this is to have a <form> with a (possibly hidden) field that you put the array (converted to a delimited string, of course) into that field and then submit the form.

    I don't use jQuery, so I don't understand WHAT is building the array in that code.

    It looks like each time the user hits the submit button you tack on another value to the array and then when he/she hits the send button you send the entire array?

    Is this that same page where you have many <form>s??? How do you prevent them from submitting the same <form> more than once?

    By the way:
    Here's my script. Which doesn't work.

    Here's my script, this works fine...
    Ummm...okay... so which is it?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Senior Coder DanInMa's Avatar
    Join Date
    Nov 2010
    Location
    Salem,Ma
    Posts
    1,577
    Thanks
    13
    Thanked 248 Times in 248 Posts
    i had to read it about 5 times but i think i get it. I have a question, do you have more than one element with an id of #box by chance?

    I also suspect you are trying to send general form data, why not use .serialize()?

  • #4
    New Coder
    Join Date
    Sep 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by DanInMa View Post
    i had to read it about 5 times but i think i get it. I have a question, do you have more than one element with an id of #box by chance?

    I also suspect you are trying to send general form data, why not use .serialize()?
    I can have different elements with different indexes.

    How do I use serialize()?


    Quote Originally Posted by Old Pedant View Post
    It looks like each time the user hits the submit button you tack on another value to the array and then when he/she hits the send button you send the entire array?
    Thats what the script does.

    Quote Originally Posted by Old Pedant View Post
    By the way:
    Ummm...okay... so which is it?
    Sorry about that. What I meant is the HTML works fine but the PHP doesn't

  • #5
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    Quote Originally Posted by Old Pedant View Post
    Only two ways: Query string or post data. And neither way allows you to actually send an array.
    Not exactly.

    Data can be sent as a JSON object, via AJAX
    http://ditio.net/2008/07/17/php-json...ascript-usage/
    http://www.factsandpeople.com/facts-...x-json-and-php

    There is also a possibility to send data which will be interpreted as an array by PHP: using a common squared names like

    ?name[]=value1&name[]=value2&name[]=value3 ... and so on
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #6
    New Coder
    Join Date
    Mar 2010
    Posts
    30
    Thanks
    0
    Thanked 1 Time in 1 Post
    This is quite simply done using jQuery. You will convert the array to a JSON string, POST the string to your PHP page using ajax, then PHP will convert it back to an array. You can also return a JSON response back to the client if you wish. Example follows:

    JavaScript/jQuery:
    Code:
    //convert array to json
    var jsonArray = JSON.stringify(theArray);
    //prepare POST data
    var dataToPost = { 'jsonArray':jsonArray };
    
    //send POST data to PHP and handle response
    $.ajax({
      type: 'POST',
      url: 'http://www.example.com/example.php',
      data: dataToPost,
      success: function (data) {
        //function to handle the response
        var response = eval( '(' + data + ')' );
        //response is now an object!
      }
    });
    example.php:
    PHP Code:
    //create object/array from json data
    $theArray json_decode($_POST['jsonArray']);

    //$theArray is now the array you had on the client side!

    $some_object doSomething($theArray);

    //prepare the response object/array to the client
    $response json_encode($some_object);

    echo 
    $response
    Last edited by coiner; 09-30-2011 at 02:32 PM.

  • Users who have thanked coiner for this post:

    JustBob (10-01-2011)

  • #7
    New Coder
    Join Date
    Sep 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by coiner View Post
    This is quite simply done using jQuery. You will convert the array to a JSON string, POST the string to your PHP page using ajax, then PHP will convert it back to an array. You can also return a JSON response back to the client if you wish. Example follows:

    JavaScript/jQuery:
    Code:
    //convert array to json
    var jsonArray = JSON.stringify(theArray);
    //prepare POST data
    var dataToPost = { 'jsonArray':jsonArray };
    
    //send POST data to PHP and handle response
    $.ajax({
      type: 'POST',
      url: 'http://www.example.com/example.php',
      data: dataToPost,
      success: function (data) {
        //function to handle the response
        var response = eval( '(' + data + ')' );
        //response is now an object!
      }
    });
    example.php:
    PHP Code:
    //create object/array from json data
    $theArray json_decode($_POST['jsonArray']);

    //$theArray is now the array you had on the client side!

    $some_object doSomething($theArray);

    //prepare the response object/array to the client
    $response json_encode($some_object);

    echo 
    $response
    I actually saw some example of JSON.stringify but was unable to test because most of the examples I saw require additional scripts that need to be included but their links were broken. Do you have the link to the required additional script?

  • #8
    New Coder
    Join Date
    Mar 2010
    Posts
    30
    Thanks
    0
    Thanked 1 Time in 1 Post
    the JSON functions are included in all modern browsers, no external script is required. If you require support for IE6 and the like, the script is available on json.org.
    Last edited by coiner; 09-30-2011 at 03:45 PM.

  • #9
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    Quote Originally Posted by coiner View Post
    the JSON functions are included in all modern browsers, no external script is required.
    Unfortunately, not all the users have modern browsers. We must wait till at least IE6 and IE7 will be extinct
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #10
    New Coder
    Join Date
    Sep 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by coiner View Post
    the JSON functions are included in all modern browsers, no external script is required. If you require support for IE6 and the like, the script is available on json.org.
    I see...I guess the thread I saw was quite old. I'll try this and post back.

  • #11
    Regular Coder
    Join Date
    Mar 2008
    Location
    London
    Posts
    152
    Thanks
    4
    Thanked 42 Times in 42 Posts
    $('#send').click(function(){
    alert(('send_array_to_other_page_2.php?list='+arr).length); // added by me
    window.location = 'send_array_to_other_page_2.php?list='+arr;
    });
    can you please check the length of the string you are passing to window.location ??

    This check is required because this will create "GET" request rather then "POST", and the maximum possible size of the "GET" query request is 2048 characters.

    So, if your url length exceeds this, then definitely you will get the "Array contents lost" error.

    Its better to use form.submit() (and method=POST) to send large data to server side.

    Hope this may resolve your problem

    Thanks & Regards,
    Niral Soni

  • #12
    New Coder
    Join Date
    Sep 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts
    @coiner

    JSON.stringify works perfectly! Thanks


    @niralsoni

    It is possible that the length of the variable would be long. It will depend on how many items are added to the cart.


    How do I incorporate form.submit() to my script? As I understand, using submit in jQuery/Javascript would work if I intend to refresh a div in the same page, but it wont work if I redirect to another page.

  • #13
    Regular Coder
    Join Date
    Mar 2008
    Location
    London
    Posts
    152
    Thanks
    4
    Thanked 42 Times in 42 Posts
    How do I incorporate form.submit() to my script? As I understand, using submit in jQuery/Javascript would work if I intend to refresh a div in the same page, but it wont work if I redirect to another page.
    form.submit() is used for both of the above quoted sentences, i.e., refreshing same page or redirecting to another page.

    The change between both these requirement lies in the action attribute of the form.

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,561
    Thanks
    80
    Thanked 4,494 Times in 4,458 Posts
    Totally silly post deleted.

    Though I still don't know how you could meaningfully use XMLHTTP to do fully binary transfers. For that matter, I don't know how you get the *binary* representation of JavaScript data in the first place.
    Last edited by Old Pedant; 10-02-2011 at 05:13 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #15
    New Coder
    Join Date
    Mar 2010
    Posts
    30
    Thanks
    0
    Thanked 1 Time in 1 Post
    @Old Pedant - Actually http does support binary data transfer, how else would you transfer pics and other files between the client/server? In addition, the JavaScript Object Notation implies plain text anyway. Ranting doesn't answer the question either...

    @JustBot - As for updating a <div> on your page, I already showed you how to do that in my example. Use jQuery's built in AJAX functions.


  •  
    Page 1 of 2 12 LastLast

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •