samedi 25 avril 2015

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


Aucun commentaire:

Enregistrer un commentaire