0

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

8
  • Post the code you're using to do this ! Commented Apr 25, 2015 at 13:48
  • @adeneo heres is the code. please check it Commented Apr 25, 2015 at 13:59
  • have you checked your browser console to see what is being passed from JSON.stringify(imgArr)? Commented Apr 25, 2015 at 14:31
  • when you receive it back, in what format is it? Commented Apr 25, 2015 at 14:32
  • i am receiving it in a string format Commented Apr 25, 2015 at 14:40

1 Answer 1

1

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);
    }
4
  • There is one problem.. $imageArray is not an array and its not working in foreach loop Commented Apr 25, 2015 at 15:50
  • yes i am doing the same but it is giving the following warning: Illegal string offset 'name' in .... Commented Apr 25, 2015 at 15:59
  • yes i am checking in the same manner but its not giving the correct output. when i am printing $imageArray its showing the proper array and when i am echoing $imageArray its showing it in string format. When i am using foreach loop it is giving a warning and showing only A. Commented Apr 25, 2015 at 16:12
  • $getImages = array(); $getImages = $users->getTypeImage($getProfileId); //echo json_encode($getImages); foreach($getImages as $value){ echo json_encode($value); } this is how i encoded the string.. you can see my question all the code is there Commented Apr 25, 2015 at 16:24

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.