Can't get data from Ajax response - json

So I'm having this ajax GET request to my API:
$(document).ready(function() {
//id=$("#id").val();
url="api.php/fcomment/"+5;
$.ajax({
type: "GET",
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data)
{
console.log(data);
alert(data);
$('.greeting-content').append(data.comment);
}
});
});
I get JSON data, results of it is:
[{"id":"5","comment":"Test","post_date":"18:17 18.05.2017","forum":"2","user":"0"},{"id":"8","comment":"Test2","post_date":"18:05 24.05.2017","forum":"2","user":"7"}]
I would like to get values out of JSON format, but nothing is added to div. If i add JSON.stringify around data then I get entire JSON but I need each attribute by itself

your accessing data.comment it's is undefined access like this data[0].comment
$('.greeting-content').append(data[0].comment);
You can use $.each to get all data
data = [{"id":"5","comment":"Test","post_date":"18:17 18.05.2017","forum":"2","user":"0"},{"id":"8","comment":"Test2","post_date":"18:05 24.05.2017","forum":"2","user":"7"}];
console.log(data[0].comment);
$.each(data,function(i,v){
console.log(data[i].comment);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You are getting collection you need loop over it
$.each(JSON.parse(data), function (i, data) {
var row = data; // data.comment
console.log(row);
});
OR
$.each(data, function (i, data) {
var row = data;
console.log(row);
});

Related

Codes are displayed instead of html elements

I have called ajax request in some interval of time. Now, if I pressed the back button after success ajax then, the browser displayed all of my HTML code instead of displaying HTML elements.
<script>
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('devices.index')}}',
dataType: 'json',
success: function (data) {
}
});
}, 1000);
</script>
if($request->ajax()){
foreach ($devices as $device){
$latestUpdate = Carbon::parse($device->updated_at);
$diff = Carbon::now()->diffInMinutes($latestUpdate);
if($diff > 2){
Device::where('id',$device->id)->update(['status'=>'3']);
}
}
return response()->json(['msg' => "successfully checked"]);
}
I had expected to render the HTML elements, but it displayed.
{
"msg": "successfully checked"
}
Same things happened when I send HTML in json.
if($request->ajax()){
$returnHtml = view('alerts.index', compact('threshold'))
->with('alerts', $alerts)->render();
return response()->json(['html' => $returnHtml, 'data' => $alerts]);
}
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('alerts.index')}}',
dataType: 'json',
success: function (data) {
var formatedhtml = $('<div>').html(data.html).find('table');
$('table').html(formatedhtml);
}
});
}, 5000);
In this case it display
Instead of returning as json return data as array:
Try something like this
return ['html' => $returnHtml, 'data' => $alerts];
There's nothing wrong with how you are receiving the data when you use return response()->json(['html' => $returnHtml, 'data' => $alerts]);
If you want to actually put the html that you received from your server into an element in your page, you will need to use Element.innerHTML (https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) so that the html will not be escaped by the browser.
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('devices.index')}}',
dataType: 'json',
success: function (data) {
// this is the table where you want to place the received table contents
var my_table=$('#my-table')
// we turn the data we received from the server into a jQuery object, then find the table we want data from
var received_table=$(data.html).find('table')
// switch out the table contents
my_table.html(received_table.html())
}
});
}, 1000);
EDIT: Since you are using jQuery, I changed the answer to fit.

Get value from an odata property in a JSON response using ajax

I need to get the value for #odata.context property from the following Json response in ajax:
{
"#odata.context":"https://site.sharepoint.com/_api/",
"#odata.type":"#oneDrive.permission",
"#odata.id":"https",
"link":{"scope":"anonymous"}
}
I would like to do something like that in code:
$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Bearer ' + bearerToken);
},
url: serverUrl,
data: JSON.stringify(params),
dataType: 'json',
contentType: " application/json",
success: function (data) {
var myvalue= data.#odata.context; // ****???
var jsonObject = JSON.parse(data); //this line throws an error Unexpected token o in JSON at position 1
}
});
I think you can get data by this:
data["#odata.context"]
And about the JSON.parse throw exception, it caused by the data is not a JSON string.
Example

JSON API to HTML

I try using different instructions to use a JSON API from a Wordpress-System in a HTML-Teamplate. Unfortunately I do not succeed. Does anyone have any idea how I can read the section "Content" of http://www.earnyour21.de/api/get_page/?id=1588?
blog: function () {
$.ajax({
url: 'http://www.earnyour21.de/api/get_page/?id=1588',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
If the data structure of the JSON will always be the same, you can simply access the object directly using the objects name in JS.
blog: function(){
$.ajax({
url: 'http://www.earnyour21.de/api/get_page/?id=1588',
type: 'GET',
dataType: 'json',
success: function(data){
$('#content_test').append(data['page']['content']);
},
error: function(data){
$('#content_test').append(data['page']['content']);
}
});
}
Basically you need to use jquery to grab the div with an id of content_test and then append your data from the json. http://api.jquery.com/append/ and http://www.json.com/ for further reference.

JSON data not parsing in node.js displays undefined in console

JSON data not parsing in node.js displays undefined in console..
Here is HTML code:
var jsonObjects = [{id:1, name:"amit"}];
jQuery.ajax({
url: 'http://localhost:8081',
type: "POST",
data: {"id":"1", "name":"amit"},
dataType: "json",
success: function(result) {
alert("done")
}
});
Here is Nodejs code:
http.createServer(function (request, response)
{
response.writeHead(200, {"Content-Type":"text/plain"});
var urlObj = JSON.stringify(response.data, true);
console.log(urlObj)
response.end();
}).listen(8081);
Try using GET method Instead of Post. Try this
var jsonObjects = [{id:1, name:"amit"}];
$.ajax({
type: 'GET',
url: 'http://localhost:8081',
data: {
jsonData: JSON.stringify(jsonObjects)
},
dataType: 'json',
complete: function(validationResponse) {
}
});
The data will be held in the request, not the response as it has come from the client request.
If you are using express to create your http server you will also need to tell it to use the bodyParser middle wear.

Using jQuery to get jsonp data returns invalid label error

I have been using jquery ajax method to get the json data. I have used both jQuery.getJSON
and jquery.ajax methods but I keep getting the same error in my console. Invalid label meta I just want to display the some of the json data inside a div , is there something
wrong with the json file the java script works fine with other json files. I dont know how to parse this particular json file.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type = text/javascript>
$(document).ready(function(){
$.ajax({
url: 'http://api.yipit.com/v1/deals/?key=TMBYhd3hkzfCntMb&limit=20&division=boston',
dataType: 'jsonp',
success: function(data){
console.log(data);
}
});
return;
});
</script>
I just tried to parse the data but I am not able to see the result.
In the console I get a error saying field.deals.url not defined ?
I am also able to see jQuery16209054896509423064_1311611178838({ on top of the
meta how can I parse this file ?
<script type = text/javascript>
$(document).ready(function(){
$.ajax({
url: 'http://api.yipit.com/v1/deals/?key=TMBYhd3hkzfCntMb&limit=20&division=boston&callback=?',
dataType: 'jsonp',
success: function(data){
$.each(data.response, function(i, field){
$('#display').append('<p>url : ' + field.deals.url+ '</p>');
if ( i == 3 ) return false;
});
}
});
return;
});
</script>
Delete jsonp: false, you have to use JSONP in this cross domain case.
This will work:
$(document).ready(function(){
$.ajax({
url: 'http://api.yipit.com/v1/deals/?key=TMBYhd3hkzfCntMb&limit=20&division=boston',
dataType: 'jsonp',
success: function(data){
console.log(data);
}
});
});
Working example: jsFiddle
EDIT:
deals is your iterator not response
success: function(data){
$.each(data.response.deals, function(i, field){
$('#display').append('<p>url : ' + field.url+ '</p>');
if ( i == 3 ) return false;
});