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

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

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);
    }
  • There is one problem.. $imageArray is not an array and its not working in foreach loop – Aisha Apr 25 '15 at 15:50
  • edited the post – Michal Hainc Apr 25 '15 at 15:55
  • yes i am doing the same but it is giving the following warning: Illegal string offset 'name' in .... – Aisha Apr 25 '15 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. – Aisha Apr 25 '15 at 16:12
  • so for you it seems that the json_decode simply returned a string instead of parsed array right? – Michal Hainc Apr 25 '15 at 16:18

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.