Can't read JSON data correctly by $.each jquery - javascript

I am trying to use $.getJSON to get data from the NHTSA recall API and append the Component object from the Results array to a div with the id="data". Here is the URL I am trying to get JSON for:
http://www.nhtsa.gov/webapi/api/Recalls/vehicle/modelyear/2000/make/honda/model/accord?format=json
Here is the snippet that I am using:
`var url = 'http://www.nhtsa.gov/webapi/api/Recalls/vehicle/modelyear/2000/make/honda/model/accord?format=json';
$.getJSON( url, function(data) {
console.log(data.Results);
$.each(data.Results, function(i,Results){
var component = this.Component;
$('#data').append('<h4>' +component+ '</h4>');
}
}
I have used this similar format for a few other API's and it worked so I am not sure why the call isn't going through.

I ran into a cross origin request problem using $.getJSON (as I often do), so I tried jsonp and succeeded. Please give it a try and let me know if you have questions.
$(document).ready(function() {
var http = 'http://www.nhtsa.gov/webapi/api/Recalls/vehicle/modelyear/2000/make/honda/model/accord?format=json';
$.ajax({
url: http,
dataType: 'jsonp',
jsonpCallback: "callback",
type: "GET",
success: function (data) {
var div = $('#data');
for(var i = 0; i < data.Results.length; i++) {
$(div).append('<div>' + data.Results[i].Component + '</div>');
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data"></div>

Related

How can I refresh a PHP file with itself using Ajax?

Alright guys I'm trying to make a filter system for posts using ajax and a select box. I am able to get the value from the select box no problem. But my issue is that when I try to include the selected value in my PHP file it doesn't do anything. I have a file called public_wall.php. This file contains PHP, Javascript, and HTML. How can I refresh this div whenever a user selects a different filter option? Basically I need the selected value to be passed onto my public_wall.php file and then I want to plug it into the PHP function that fetches the posts thats's in the same file and then I want to refresh that same file to display the filtered results. Here is my Javascript code.
$("#postRatings").on("click", function(e) {
selectedRatingFilter = $("#postRatings option:selected").val();
var dataString = "timeFilter="+selectedRatingFilter;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response){
hideSpinner();
jQuery('#postsPagingDiv').remove();
jQuery('#wsc_midbox').html(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
jQuery('#paging_in_process').val(0);
}
});
});
When the dataType is set to "json" nothing happens. But when it is set to html it prints some javascript code. Please help. The PHP file is too large to include here, but it basically contains PHP, HTML, and Javascript and some PHP functions that do sql queries. What is the best way to achieve a filter mechanism for my setup?
And on the public_wall.php file I want to get the value like so:
$ratingFilter = isset($_REQUEST['timeFilter']) ? intval($_REQUEST['timeFilter']) : 0;
And then plug it into the PHP function that fetches the posts which is in the public_wall.php file also so that I can filter the posts based on the selected value. And then finally I want to refresh the public_wall.php file with the new results. I hope that makes sense. Please help.
This is the output when I set my dataType to "html"
<script>
function refreshPosts() {/* only posts comments likes and count updated. */
var posts = jQuery("#all_post_id").val();
var arrays = posts.split(',');
var dataString = "postids="+posts;
jQuery.ajax({
type: "POST",
url: site_url+"includes/update_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
var x = response;
//############ skip posts whose comments are being read by users
var ExemptedPostsIDs = jQuery("#exemptedPostsID").val();
var ExemptedArray = ExemptedPostsIDs.split(',');
ExemptedArray = ExemptedArray.sort();
//////////////
for (i=0; i<arrays.length; i++) {
var val = 'row'+arrays[i];
if(x[val]) {
if(!inArray(arrays[i], ExemptedArray))
jQuery("#ajax_wall_"+arrays[i]).html(x[val]);
} else {
jQuery('#PostBoxID'+arrays[i]).parent().fadeOut(500);
}
}
}
});
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function refreshWall() {/* loads new posts real time */
var posts = jQuery("#all_post_id").val();
var pageUsing = jQuery('#pageUsing').val();
var dataString = "update_posts=1&postids="+posts+'&pagex='+pageUsing;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
if(response.all_post_id) {
jQuery('#wsc_midbox').prepend(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
}
}
});
}
</script>
I suggest you keep the form with select element and any JavaScript on the outer frame.
Via ajax, only load the results to a seperate DIVision below that.
When you put an Ajax response to a div, any JavaScript inside it will not be executed.
For the best throughput with Ajax, you should consider loading a json response via Ajax and create HTML elements on the client side. That way it becomes much easier to pull additional variables to front-end JS from server side along with the same request/response.
But that becomes bit difficult when you have a template engine in the back-end. You can still send the HTML content in a json value, so you can easily pass the "all_post_id" as well..

How to make post request using javascript

I am trying to make a POST request in javascript. But response is not getting.
http://xecutehr.com/api/HRMSService.svc/PostAttendance?input={"Header":{"CompanyId":"MTF","LicenceKey":"MTF-4525"},"Body":{"E_Code":"01330","AttendanceDateTime":"2016-04-27T13:00:30","Mode":"I","DeviceId":"MTF1330"}}
This is the url format and this is the code I have written:
if(valid){
var values = form.serializeObject();
var e_code = values.staff_code.substring(3);
var device_id = values.staff_code;
var date_time = datetime;
var url = "http://xecutehr.com/api/HRMSService.svc/PostAttendance?input=";
$.ajax({
url:url,
headers: {
"CompanyId":"MTF",
"LicenceKey":"MTF-160427-RHGB-4525"
},
type: "POST",
data:{
"E_Code":"0"+e_code,
"AttendanceDateTime":date_time,
"Mode":"I",
"DeviceId":device_id
},
datatype: "jsonp",
success: function(data) {
alert(response);
}
});
}
I tried a lot I am missing some basics in in . How can I handle this? suggest some solutions or links
You can't have jsonp and do a POST.
A jsonp request loads as a <script>.
E.g.
request: /url?callback=something&E_Code=0something
The response will be something like:
something({E_Code: '0something'})
Where something() is your ajax response handler.

Import JSON via ajax and looping through

obviously I am newbie. I am trying to load a json file via ajax, then loop through that array to populate a graph using a cytoscape.js package (another question for another day).
Before I begin my loop to create new nodes and edges, I am trying to test my loop to verify the output. However, nothing it's not working.
<html>
<head>
<title>Springy.js image node demo</title>
</head>
<body>
<script src="jquery-1.11.3.js"></script>
<script src="springy.js"></script>
<script src="springyui.js"></script>
<script src="bluebird.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
// get exported json from cytoscape desktop via ajax
var graphP = $.ajax({
url: 'https://rawgit.com/theresajbecker/CompBio/master/TokyosmallTest/Tokyosmall2.json', // tokyo-railways.json
type: 'GET',
dataType: 'json'
});
console.log(graphP);
var node = graphP.nodes;
//var employee2 = elements.edges;
for ( var i in node) {
var id = nodes[i].id;
var station_name = nodes[i].station_name;
console.log(id);
console.log(station_name);
}
</script>
</body></html>
This should produce the output of node id and station name but it's not. The console.(log) produces: Object {readyState: 1}
What am I doing wrong here?
Thanks
It is because $.ajax
is async.
Try:
// get exported json from cytoscape desktop via ajax
$.ajax({
url: 'https://rawgit.com/theresajbecker/CompBio/master/TokyosmallTest/Tokyosmall2.json', // tokyo-railways.json
type: 'GET',
dataType: 'json'
}).done(function (graphP) {
console.log(graphP);
var node = graphP.nodes;
//var employee2 = elements.edges;
for ( var i in node) {
var id = nodes[i].id;
var station_name = nodes[i].station_name;
console.log(id);
console.log(station_name);
}
});
See demo
Ajax queries are asynchronous, you must wait for it to complete :
var query = $.ajax({url: url', // tokyo-railways.json
type: 'GET',
dataType: 'json'
})
.done(function( graphP ) {
//Your code here
console.log(graphP);
});
jsFiddle Demo
The main problem is that $.ajax isn't going to return the json. It is going to inject it into a success callback function. So what you need to do is move your expected code below which uses the "value" from $.ajax to be inside of the success function.
$.ajax({
url: 'https://rawgit.com/theresajbecker/CompBio/master/TokyosmallTest/Tokyosmall2.json', // tokyo-railways.json
type: 'GET',
dataType: 'json',
success: function(graphP){
console.log(graphP);
//the structure of the json is slightly different than your mappings
//for example
var firstNodeId = graphP.elements.nodes[0].data.id;//is the first id
}
});
Try using this:
$.getJSON( "https://rawgit.com/theresajbecker/CompBio/master/TokyosmallTest/Tokyosmall2.json", function( data ) {
for (var i = 0; i < data.elements.nodes.length; i++) {
var node = data.elements.nodes[i];
console.log(node.data.id);
}
});
For further reading:
http://api.jquery.com/jquery.getjson/

Automatically create listview items with an anchor tag in it

I am making a webapp with Jquery Mobile. I got my data back from a webservice function.
Now to get this data in my web page I am using a ajax call.
$('[data-role=page]').live('pageshow', function () {
var userId = $("#userId").val();
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getNieuwtjes",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'userId':'" + userId + "'}",
success: function (response) {
var nieuwtjes = response.d;
if (nieuwtjes.length > 0) {
$.each(nieuwtjes, function (i, entity) {
$('#nieuwtjesList').append(
//Here come's the data from web function
});
}
}
});
});
Now in #nieuwtjesList should come all the data that I get back from the server. These data is a newsTopic. And it should show it like this.
<li>~ITEM.ONDERWERP~ </li>
My question is, how can I create the line above for every record I got back from my webservice function.
Kind Regards.
Stef
You can use this code to create the HTML to append for each line
$("<li/>").append($("<a/>")
.attr("href", <HREF FROM YOUR DATA>)
.text(<TEXT FROM YOUR DATA>)
);
You can use jQuery.tmpl to easily implement this.
var nieuwtjes = response.d;
if (nieuwtjes.length > 0) {
var html ='';
$.each(nieuwtjes, function (i, entity) {
html += '<li>'+ i.ONODERWERP+'</li>';
});
$('#nieuwtjesList').append($(html));
}

js how to make my array be visible by other functions

my first alert shows the list of items but the second is not. I've never done anything in ajax/js before so i don't know how to return my array so it would be visible by other functions.
var mycarousel_itemList = [];
$(document).ready(function () {
$.ajax({
type: "GET",
url: "xml/images.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('image').each(function () {
var id = $(this).attr('id');
var url = $(this).find('url').text();
mycarousel_itemList.push('{url:"' + url + '",' + 'id:"' + id + '"}');
alert(mycarousel_itemList);
});
}
});
alert(mycarousel_itemList);
});
This is how my xml looks like
<images>
<image id="1">
<title>item</title>
<url>images/image.gif</url>
<desc>description of an item</desc>
</image>
<image id="2">
<title>anotheritem</title>
<url>images/images.gif</url>
<desc>description of an item</desc>
</image>
</images>
The mycarousel_itemList array is not declared within a function and thus is global. You should be able to access the array in your success event function.
There's something borked with your specific example (e.g., the success function isn't getting hit because the server doesn't respond).
If I copy and paste your code and simply replaced the server-side component with a JSONP service (just so I can do AJAX across domains), I have no problem accessing the array:
var mycarousel_itemList = [];
$(document).ready(function () {
var url = "http://github.com/api/v2/json/user/show/yui";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function (data) {
mycarousel_itemList.push(data.user.company + ' - ' + data.user.blog);
alert(mycarousel_itemList[0]);
}
});
});
You can test it out here.
To answer the direct question: it's not possible to make the array populated when the second alert is called because by that time the AJAX call didn't have time to complete.
What function exactly need that array?
Just call it from within the success method after you populate the array and it will work just fine.

Categories

Resources