1

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 ?

4 Answers 4

2
$.getJSON('jsonOutput.php', function(data) {
  var filename = data.imagesrc;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, $.getJSON is a shorthand for $.ajax() call with dataType as json. See api.jquery.com/jQuery.getJSON
Oh... hehe sorry! Posted the comment on the wrong answer :P I was looking at the answer with $.get :)
2

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/

3 Comments

Are you sure that you don't have to specify a dataType parameter when dealing with json data?
Not if your server is correctly sending back the application/json Content-Type, I believe.
Well I would say its always better to be verbose. As we are not talking about servers here but client side technologies, I would recommend always specifying the dataType. This will also increase readability.
1

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 -

Comments

1

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);

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.