0

Ive been trying to parse and display the json data returned by a REST API without success.

Tested locally, the API is of form:

http://localhost/apiurl/get-data.php

And it returns data in form:

[{"title":"Title One","message":"Message One"},{"title":"title two","message":"message two"},....] 

Each item consist of two elements ; title and message as shown above.

I want to loop through all returned items and display the result in a div like this

<p>Title One</p>
<p>Message One</p>  

Etc.

Ive tried something like this:

<script src="path/to/jquery"></script> 

<script type="text/javascript">
 $(document).ready(function(){
var url="http://localhost/apiurl/get-data.php";
$.getJSON(url,function(json){
$.each(data,function(i,dat){
$("#resultid").append(
'<p>Title : <em>'+dat.title+'</em>'+
'<p>Message : <em>'+dat.message+'</em></p>'+
'<hr>'
);
});
});
});
</script>

but it didn't work. Any other idea?

3
  • 1
    Are you getting any errors in your JS console? Also, try logging the json variable after you get it. Does it contain the data you want? Commented Nov 9, 2017 at 19:06
  • 2
    Change $.getJSON(url,function(json) to $.getJSON(url,function(data) Commented Nov 9, 2017 at 19:07
  • @Dipen Shah This works too Commented Nov 10, 2017 at 5:03

1 Answer 1

1

it started working after changing the value to json instead of data check this out enter image description here

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

2 Comments

Passing variable and accessing variable names should be same!!
Yes. It works, even with json. But I had to remove all html tags first from the url file...<html>, <head>, <body>, seems that was the cause the cause of the problem. Thanks

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.