Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
Post the code you're using to do this ! –  adeneo 22 hours ago
    
@adeneo heres is the code. please check it –  user3456241 22 hours ago
    
have you checked your browser console to see what is being passed from JSON.stringify(imgArr)? –  Sean 21 hours ago
    
when you receive it back, in what format is it? –  Paul Okeke 21 hours ago
    
i am receiving it in a string format –  user3456241 21 hours ago

1 Answer 1

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);
    }
share|improve this answer
    
There is one problem.. $imageArray is not an array and its not working in foreach loop –  user3456241 20 hours ago
    
edited the post –  Michal Hainc 20 hours ago
    
yes i am doing the same but it is giving the following warning: Illegal string offset 'name' in .... –  user3456241 20 hours ago
    
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. –  user3456241 20 hours ago
    
so for you it seems that the json_decode simply returned a string instead of parsed array right? –  Michal Hainc 20 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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