2

I have been using $.getJSON in order to verify if a script has done its job properly, using exit("{'status':true}") (or false) but now I need the script to return a value (or an array). I see that I can't use exit('{ "status": $myarray}');. What can I use instead? I am new to php- is it possible to do something like return '{ "status": $myarray}'; or something alike? Thanks in advance

Mihai Bujanca
  • 4,089
  • 10
  • 43
  • 84

5 Answers5

5

You can use the following function:

json_encode($data);

See: http://php.net/manual/en/function.json-encode.php

Rijndael
  • 3,683
  • 2
  • 24
  • 26
4

In your php, use json_encode as such:

<?php
    header('Content-Type: application/json');
    echo json_encode($myarray);
    // or, `exit(json_encode($myarray))` if global scope (see *REF)
?>

and in your jQuery use getJSON normally:

$.getJSON("test.php",function(result){
    ...
});

(*) REF: PHP - exit or return which is better?

Community
  • 1
  • 1
mg007
  • 2,888
  • 24
  • 29
2

If you want return data just like as array or single data in json then Try this code

In php file write like this

$value = 'welcome';
echo json_encode($value);exit;

or

$value = array("Saab","Volvo","BMW","Toyota");
print_r(json_encode($value));exit;
Ashish Jain
  • 760
  • 1
  • 8
  • 23
1
   `$jsonString = 'your json string'`
    $jsonArray = json_encode($jsonString);
    return $jsonArray
0

I will post the way I did it, seems quite simple to me now. Thank you for your answers

$json_array=array('status'=>$row);
exit(json_encode($json_array));

AJAX call:

   $.getJSON( "savefunctions/getVideos.php", function(response) {
                         if( response.status ) alert(response.status);
                         });
Mihai Bujanca
  • 4,089
  • 10
  • 43
  • 84