Firoz
Firoz

Reputation: 486

how to capture array in ajax page when sent through JSON object

i am sending an array from one page to another through ajax.i used JSON object for this purpose.I am able to send but i am not able to capture in the ajax page.Please help me how to capture the array values. javascript:

var jsonString = JSON.stringify(dataString);
   $.ajax({
        type: "POST",
        url: "ajaxpage.php",
        data: {data : jsonString}, 
        cache: false,

        success: function(response){
            alert("ok");
           $('#test').html(response);
        }
    });

PHP page:

$data = json_decode(stripslashes($_POST['data']));

  // here i would like use foreach:

  foreach($data as $d){
     echo $d;
  }

please help me in this regard. I am stuck up here

Upvotes: 2

Views: 656

Answers (2)

iCezz
iCezz

Reputation: 634

I think this is what you want, I have tried and it works
in your php:

<?php
$data = ($_POST['data']);

foreach($data as $d){
    echo stripslashes($d);
}
?>

in your jsvascript/jquery:

<script>
$(document).ready(function(){
    $('a').on('click',function(){
    var dataString = {
        'id':'1',
        'name':'peter parker',
        'age':'unknown',
        'role':'spiderman'
    }
    $.ajax({
         url: "<?php echo $this->webroot;?>test_1.php",
         data: {'data':dataString}, 
         type: "POST",
         cache: false,
         success: function(response){
         alert("ok");
         $('#test').html(response);
        }
     });
   })
})
</script>

in your html

<a href="javascript:void(0);">Click Me</a>
<div id="test"></div>

Upvotes: 0

Ben Barkay
Ben Barkay

Reputation: 5622

If you want to decode the JSON into an associative array, you should specify that in json_decode:

Replace

$data = json_decode(stripslashes($_POST['data']));

With

$data = json_decode(stripslashes($_POST['data']), true);

See json_decode reference for more information


Also, is dataString possibly already a JSON string?

Upvotes: 1

Related Questions