Import JSON via ajax and looping through - javascript

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/

Related

How can I do a conditional statement so ajax fetchs the correct xml document

I have a simple code to fetch a xml file and display it as a drop down list. However, I would like to fetch the xml file according to a condition. If it equals to study1 then .ajax selects ctc3.xml, else it selects ctc5.xml.
My code was working fine if I was fetching a specific xml file, but the conditional does not work.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script lang="Javascript"> $.noConflict();
jQuery(document).ready(function($) {
var myField = $("#myList") var myOutputField = $("#myOutput").parent().parent().find("input");
myOutputField.attr("readonly",true);
var studyID="${studyName}";
if (studyID!="Test"){
$.ajax({
type: "GET",
url: "includes/ctcae3.xml",
dataType: "xml",
success: parseXML
});
}
else {
$.ajax({
type: "GET",
url: "includes/ctcae5.xml",
dataType: "xml",
success: parseXML
});
}
function parseXML(xml){
$(xml).find("atccode").each(function(){
myField.append($("<option />").val($(this).attr("code")).text($(this).find("description").text()));
});
myField.val(myOutputField.val());
}
myField.change(function(){
myOutputField.val(myField.val());
myOutputField.change();
});
});
</script><select id="myList"> <option val="None"/>None </select> `
problem resolved. Clearly my brain was already fried. It was just a matter of adding the ';' to var myField = $("#myList");

Not getting a response for an AJAX call to PHP (with JSON data)

I have a PHP running on a server, and i call to it via jQuery.Ajax() but it always return to the error portion of it.
If i call the PHP address directly from my browser, i get the response i need, it only breaks in the jQuery call.
The PHP (simply saying) is this:
<?php
if(isset($_GET['getcodenode']))
{
echo json_encode
(
array
(
'itens'=>
array
(
0=>array('id'=>100,'lb'=>'300','ds'=>'300 mm'),
1=>array('id'=>105,'lb'=>'400','ds'=>'400 mm')
)
)
);
die();
}
?>
And on the javascript side i call for it like this:
<html>
<head>
<script type="text/javascript">
function loadcall(data)
{
jQuery.ajax({
async:false,
method:'POST',
crossDomain:true,
dataType:'jsonp',
url:'http://example.com/ajax.php?getcodenode',
data:{'arg':data},
success:function(result){
var ret=JSON.parse(result);
var el=jQuery('#abc');
for(en in ret.itens)
{
el.Append('<div id="item_'+en.id+'">'+en.lb+', '+en.ds+'</div>');
}
},
error:function(result){alert('Error (loadcall)');}
});
}
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>
How to read JSON objects from PHP and display in browser?
There are lots of comments on your code:
While you already getting a json return from server; you don't to parse that. Its already a json object.
You can set async:true to get a promise data
The way you loop through objects you need to do that properly. see image how to get the object path correctly.
You can use $ token instead of jQuery token; unless you purposely need that.
I am not sure if this is the best approach; but it give the needed result as explained in your question.
The code is bellow tested with some comments:
<script type="text/javascript">
loadcall("test");
// as pointed you need to call the function so it runs
function loadcall(data) {
$.ajax({
async: true,
method: 'POST',
crossDomain: true,
dataType: 'json', //your data type should be JSON not JSONP
url: 'page.php?getcodenode',
data: {
'arg': data
},
success: function(result) {
console.log(result);
// see attached image how to get the path for object
var ret = result;
var el = $('#abc');
for (en in ret.itens) {
console.log(ret.itens[en].ds);
el.append('<div id="item_' + ret.itens[en].id +
'">' + ret.itens[en].lb + ', ' + ret.itens[en].ds + '</div>');
}
},
error: function(result) {
console.log(result);
}
});
}
</script>
Open you developer tool in your browser hit F12 (In Chrome, Firefox or Edge):
Go to Console tab and find the results.
Expand the results tell you get to the object you need.
Right click and `copy property path'.
Use the object path as needed in your code.
you need to call loadcall(data)
<html>
<head>
<script type="text/javascript">
function loadcall(data)
{
jQuery.ajax({
async:false,
method:'POST',
crossDomain:true,
dataType:'jsonp',
url:'http://example.com/ajax.php?getcodenode',
data:{'arg':data},
success:function(result){
var ret=JSON.parse(result);
var el=jQuery('#abc');
for(en in ret.itens)
{
el.Append('<div id="item_'+en.id+'">'+en.lb+', '+en.ds+'</div>');
}
},
error:function(result){alert('Error (loadcall)');}
});
}
loadcall('somethingData')
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>

Javascript Variable to PHP via AJAX (GET Method)

I am trying to pass a Javascript variable to a PHP file using AJAX.
I have the below Javascript code;
<script type="text/javascript">
var route_id = 'travelling-from'; //Route ID
$('#'+route_id).change(function(e) {
//Grab the chosen value on route change
var selectroute = $(this).val();
$.ajax({
type: "GET",
url: 'ajax-getvalues.php',
data: { selectroute : selectroute }
});
});
</script>
In my ajax-getvalues.php, I have;
$selectroute = mysqli_real_escape_string($connection, $_GET['travelling-from']);
When I try to use $selectroute, it seems to be empty.
Do I need to add something else in order for this to work? Or have I gone wrong at some point?
When I try to use $selectroute, it seems to be empty
The AJAX request will be sent to ajax-getvalues.php with the query string:
?selectroute=somevalue
In PHP you are trying the get the value of a parameter called travelling-from, this parameter does not exist in the query string.
You need to change selectroute to travelling-from
$.ajax({
type: "GET",
url: 'ajax-getvalues.php?travelling-from=' + encodeURIComponent(selectroute)
});
Or of you prefer:
$.ajax({
type: "GET",
url: 'ajax-getvalues.php',
data: {"travelling-from": encodeURIComponent(selectroute)}
});
This produces the query string ?travelling-from=somevalue which can now be accessed with $_GET['travelling-from']
In your example the key should be route_id instead of selectroute
<script type="text/javascript">
var route_id = 'travelling-from'; //Route ID
$('#'+route_id).change(function(e) { //Grab the chosen value on route change var selectroute = $(this).val();
var data = {};
data[route_id] = selectroute;
$.ajax({
type: "GET",
url: 'ajax-getvalues.php',
data: data }
}); </script>

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

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>

Store current page data in a variable, in the same format/structure as an Ajax html response

I'm storing/saving my History Ajax call responses in an array (jQuery). So on ajax load success I store the response data in an array so I can use it and apply/clone later on (for js side cache).
page_cache = [];
$.ajax({
url: url,
type: 'get',
dataType: 'html',
success: function (data) {
var $response = $(data);
page_cache[url] = $response;
}
});
So far so good, BUT now I need the equivalent of the ajax call response data, but on the current page so that I can stor/save it already on page load.
But struggled finding a way..
Been trying:
page_cache[url] = $('html').data();
... but no luck..
Any suggestions?
If you want the entire page in the variable, you can use it:
var $html = $('html').clone();
$html.find('body').html($response);
page_cache[url] = $html;
Regards.
you can try like this
var page_cache =[];
$.ajax({
type: 'get',
dataType: 'html',
success: function (data) {
page_cache[url] = data;
$('html').html(data);
}
});
for searching:
$('html').html(page_cache[url]);
for current page html:
url = window.location;
page_cache[url] = $('html').html()
Did you tried to get the body part with $('body').html(); ?
You can save the html with page_cache[url] = $('body').html();
and get it back with $('body').html(page_cache[url]);

Categories

Resources