Aisha
Aisha

Reputation: 247

php - pass an array from php to jquery ajax and then again pass the same array from jquery to php

I am in a situation where i am passing an array from php to jquery ajax using json_encode and saving it in an empty array i declared in jquery script var myarr = [], and later on in the same script i am sending the same array i-e, myarr to php script through $.ajax using JSON.stringify function and receiving the array in php script like this json_decode($_POST['myarr'], true), but the problem is it is not converting back into an array. I want to receive an array so that i can use foreach loop to read that array.

Here is the code below. First I am declaring an array in jquery script

var imgArr = [];

Then fetching all the images from php script and saving it in above declared array

PHP Script:

$getProfileId = $users->getPrfId($photoId);
$getImages = array();
$getImages = $users->getTypeImage($getProfileId);
//echo json_encode($getImages);
foreach($getImages as $value){
   echo json_encode($value);
 }

JQuery
  $.ajax({
        type: 'POST',
        url: 'fetchAllImages.php',
        data: {'photoId': photoId},
        success: function(data){
             imgArr = data;
          }
        });

Now in the same script on other button click i am sending this array imgArr to php Script using $.ajax. Here is the code:

JQuery:

$('#right_arrow').live('click', function(e){

var photoId =   $(this).siblings('#o_popup_post').children('#o_post_box').children("#o_complete_post_image").children("img").attr("id");
       $.ajax({
       type: 'POST',
       url: 'nextImage.php',
       data: {'photoId': photoId, 'imgArr' : JSON.stringify(imgArr)},
               beforeSend: function(){
                $('#o_popup_post').fadeOut("normal").remove();
                    $('.o_background_popup').append("<div id='o_popup_post'></div>");
       },
       success: function(response){
            $('#o_popup_post').append(response);
        // alert(imgArr);

       }
    });
   });  


  PHP Script:

  $photoId = $_POST['photoId'];

  $imageArray = array();
  $imageArray = json_decode($_POST['imgArr'], true);

  foreach($imageArray as $key=>$value){....}

Please help. Thanks

Upvotes: 0

Views: 1428

Answers (1)

michalh
michalh

Reputation: 2997

I tried your example on my web server... works as expected... and correctly... the only thing I removed is the beforeSend and success javascript functions implementations

I tested this and it works correctly

HTML: test.html

    <html>
    <head>
    <script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js">
    </script>
    </head>
    <body>
    <button id="btn">btn</button>
    <script type="text/javascript">
    $(function() {
    $('#btn').on('click', function(evt) {
       var photoId = 1;
       var imgArr = [{ "name": "photo.jpg", "id": 1 }];
       $.ajax({
              type: 'POST',
                 url: 'test.php',
                 data: {'photoId': photoId, 'imgArr' : JSON.stringify(imgArr)},
                 beforeSend: function(){
                 },
                 success: function(response){
                     alert(imgArr);
                }
            });
    });
    });
    </script>
    </body>
    </html>

PHP: test.php

    <?php
    //print_r($_POST);

    $photoId = $_POST['photoId'];

    $imageArray = array();
    $imageArray = json_decode($_POST['imgArr'], true);

    print_r($imageArray);

    foreach($imageArray as $key=>$value){

    }
    ?>

the $imageArray variable is an array of arrays as shown by the print_r($imageArray) output:

    Array
    (
        [0] => Array
            (
                [name] => photo.jpg
                [id] => 1
            )

    )

thus you have to walk it like this:

    foreach($imageArray as $key=>$value){
        echo $value["name"];
    }

or you might try this function, which handles slashes problem in the JSON according to the magic quotes setting in PHP:

    function _json_decode($string) {
        if (get_magic_quotes_gpc()) {
            $string = stripslashes($string);
        }

        return json_decode($string);
    }

Upvotes: 1

Related Questions