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

5 Answers 5

5

You can use the following function:

json_encode($data);

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

Sign up to request clarification or add additional context in comments.

1 Comment

And exit($data)? How will the ajax recieve the response?
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?

1 Comment

header('Content-Type: application/json') did the trick, thank you!
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;

Comments

1
   `$jsonString = 'your json string'`
    $jsonArray = json_encode($jsonString);
    return $jsonArray

1 Comment

I think the question is about encoding not decoding.
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);
                         });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.