jinni
jinni

Reputation: 237

How can I retrieve my JSON output into a JavaScript variable?

I have my jsonOutput.php page like this :

 $response['imgsrc'] =  $filename[1];
 echo json_encode($response);

It outputs a filename like {"imgsrc":"071112164139.jpg"}

Now my question is, how can I use jQuery in my index.php to get the filename into a variable using ajax ?

Upvotes: 1

Views: 84

Answers (4)

halilb
halilb

Reputation: 4115

You can use jQuery.parseJSON to parse json output into a javascript object.

Following code would work:

var json = json_encode(<?php echo $response ?>);
var obj = jQuery.parseJSON(json);
alert("file name is: " + obj.imgsrc);

Upvotes: 1

Tom Hallam
Tom Hallam

Reputation: 1950

Try this:

$.get('<your php file>', {}, function(response) {
   var imagesrc = response.imgsrc;
   alert(response.imgsrc);
});

Have a read through http://api.jquery.com/jQuery.get/

Upvotes: 2

Pulkit Goyal
Pulkit Goyal

Reputation: 5654

$.getJSON('jsonOutput.php', function(data) {
  var filename = data.imagesrc;
});

Upvotes: 2

Lix
Lix

Reputation: 47986

All you'll have to do is execute a jQuery ajax call -

var imgSrc = '';
$.ajax(PATH_TO_PHP_SCRIPT,{},function(response){
  imgSrc = response.imgsrc;
},'json');

Your imgsrc parameter will now be a JavaScript variable called imgSrc. Don't forget to specify that your dataType is a json.

Reference -

Upvotes: 1

Related Questions