Trouble displaying data from ajax json parse - javascript

This is the link to my codepen: http://codepen.io/dsemel/pen/VamEyE
This is the section of code that seems to be the problem:
function success(position){
var WeatherKey = '6068dffce2f44535a07202457162103';
var lat = position.coords.latitude;
var long = position.coords.longitude;
var weatherUrl = "http://api.apixu.com/v1/current.json?key=" + WeatherKey +
"&q=" + lat + "," + long;
$.ajax({
url : weatherUrl,
type: 'GET',
dataType : 'json',
success : function(data) {
var city = data['location']['name'];
var tempFar = data['current']['temp_f'];
var img = data['condition'][0]['icon'];
var desc = data['condition']['text'];
$('#weatherInfo2').text(tempFar);
}
});
}

Make sure you check your developer tools console when you encounter these errors. Your code is throwing this error Uncaught TypeError: Cannot read property '0' of undefined.
The condition object is part of the current object, therefore you have to access the current object before accessing the condition object.
Updated working codepen

I think your code works fine you just missed a small thing in your code i corrected that
http://codepen.io/rahulchaturvedie/pen/RagGdR
$.ajax({
url : weatherUrl,
type: 'GET',
dataType : 'json',
success : function(data) {
console.log(data);
var city = data['location']['name'];
var tempFar = data['current']['temp_f'];
var img = data.current.condition.icon; // correct this
var desc = data.current.condition.text; // correct this
$('#weatherInfo2').text(tempFar);
}
});

Related

How can I resolve XML Parsing Error: not well-formedLocation?

On load of my page I execute this function
function getConnection() {
$.ajax({
type: "GET",
url: "../webservice/anonymous_PS.asmx/Get",
data: { "PSname": "LISTE_CONNEXTION" },
async : false ,
success: function (response) {
var data = response.getElementsByTagName("NewDataSet")[0]
for (let i = 0; i < data.children.length; i++) {
var c1Nb = $(data.children[i]).find('c1').text()
var c2Nb = $(data.children[i]).find('c2').text()
var c1 = document.getElementById("cs" + c1Nb)
var c2 = document.getElementById("cs" + c2Nb)
var line = $("#l_" + c1Nb + "_" + c2Nb)
}
}
})
}
But when I do that I have this error on Firefox :
XML Parsing Error: not well-formed
Location:
Line Number 1, Column 131:
and on chrome sometimes I have this error :
devtools was disconnected from the page
How can I resolve my issue ?
Try parsing your response, you can use $.parseXML(response) if you want to parse your response to xml or $.parseHTML(response) if you want to parse your response to html.
Once the parsing is done then your getElementsByTagName("NewDataSet")[0] will work and you will not get any error.
The final code will look something like:
var parsedResponse = $.parseXML(response);
var data = parsedResponse.getElementsByTagName("NewDataSet")[0];

Trying to pass values from Javascript to Java

I'm using this Javascript to send x, y values to Java from front-end (Javascript).
Sometimes this code pass the x any y values to Java and sometimes it's doesn't.After pressing the 'save' button, the function saveObjectMovingPath() will be called.
I don't know why it doesn't work sometimes! Can anyone help me to solve this issue?
<script type="text/javascript">
function saveObjectMovingPath() {
var building_Id = $("#building").val();
var floor_Id = $("#floor_level").val();
console.log('building_Id :' + building_Id + ', floor_Id : ' + floor_Id);
var json = {};
json["building_Id"] = building_Id;
json["floor_Id"] = floor_Id;
json["dataset"] = dataset;
$.ajax({
type: "post",
url: "savepath?pathConfig=" + unescape(JSON.stringify(json)),
success: function(data) {
alert("response data : " + data);
var response = JSON.parse(data);
}
});
}
</script>
This is sample data passing on URL:
"http://localhost:8080/Track/savepath?pathConfig={%22building_Id%22:%223%22,%22floor_Id%22:%2224%22,%22dataset%22:[{%22x%22:785.260498046875,%22y%22:624.4688720703125},{%22x%22:783.3544921875,%22y%22:624.4688720703125},{%22x%22:781.4485473632812,%22y%22:624.4688720703125},{%22x%22:779.5425415039062,%22y%22:624.4688720703125},{%22x%22:777.6365966796875,%22y%22:624.4688720703125},{%22x%22:775.7306518554688,%22y%22:624.4688720703125},{%22x%22:773.8246459960938,%22y%22:624.4688720703125},{%22x%22:770.9656982421875,%22y%22:624.4688720703125},{%22x%22:769.0596923828125,%22y%22:624.4688720703125},{%22x%22:767.1537475585938,%22y%22:624.4688720703125},{%22x%22:764.2947998046875,%22y%22:624.4688720703125},{%22x%22:763.341796875,%22y%22:624.4688720703125},{%22x%22:762.3887939453125,%22y%22:623.5159301757812},{%22x%22:760.4828491210938,%22y%22:623.5159301757812},{%22x%22:759.5298461914062,%22y%22:623.5159301757812},{%22x%22:757.6239013671875,%22y%22:623.5159301757812},{%22x%22:756.6708984375,%22y%22:623.5159301757812},{%22x%22:755.7178955078125,%22y%22:623.5159301757812},{%22x%22:754.7649536132812,%22y%22:623.5159301757812},{%22x%22:752.8589477539062,%22y%22:623.5159301757812},{%22x%22:751.9059448242188,%22y%22:623.5159301757812},{%22x%22:750.9530029296875,%22y%22:623.5159301757812},{%22x%22:749.0469970703125,%22y%22:623.5159301757812},{%22x%22:748.0940551757812,%22y%22:623.5159301757812},{%22x%22:747.1410522460938,%22y%22:624.4688720703125},{%22x%22:745.2350463867188,%22y%22:624.4688720703125},{%22x%22:744.2821044921875,%22y%22:625.421875},{%22x%22:743.3291015625,%22y%22:625.421875},{%22x%22:741.423095703125,%22y%22:625.421875},{%22x%22:740.4701538085938,%22y%22:626.3748779296875},{%22x%22:739.5171508789062,%22y%22:626.3748779296875},{%22x%22:738.5641479492188,%22y%22:626.3748779296875},{%22x%22:737.6112060546875,%22y%22:627.327880859375},{%22x%22:736.658203125,%22y%22:627.327880859375},{%22x%22:735.7052001953125,%22y%22:627.327880859375},{%22x%22:734.752197265625,%22y%22:627.327880859375},{%22x%22:733.7992553710938,%22y%22:628.2808227539062},{%22x%22:732.8462524414062,%22y%22:628.2808227539062}]}"
you try to send GET parameters on POST method
first you need to call the error function in your AJAX declaration and console.log it , if there is no error and the problem not resolved please check your java side (server side , maybe you try to save something need to parse ... )
second : make ajax statement look like this :
$.ajax({
type: "post",
data : {
building_Id : $("#building").val(),
floor_Id : $("#floor_level").val()
dataset: dataset;
}
url: "savepath?pathConfig=" + unescape(JSON.stringify(json)),....
....
instead of this :
var json = {};
json["building_Id"] = building_Id;
json["floor_Id"] = floor_Id;
json["dataset"] = dataset;

Push Local File From Electron to Server PHP

js and electron. I have a problem to push my local images file to my remote server. The server is using php. Here's my client side code :
var documentList = [];
var stmtDoc = db.prepare("SELECT * FROM `tb_dokumen_pasien`");
while(stmtDoc.step()) {
var rowDoc = stmtDoc.getAsObject();
var data = fs.createReadStream(__dirname + "/resources/" + rowDoc['id'] + "/" + rowDoc['doc_name']);
var document = {
"document_name" : rowDoc['doc_name'],
"data" : data
}
documentList.push(document);
}
And after that I create an ajax post request to my remote server :
$.ajax({
url: "http://url/web_api.php?action=test_upload",
type: 'POST',
data : { "document_list": documentList },
dataType: "json",
success: function(response) {
console.log(response);
}
});
When I test it, in my developer tools console I've got this message :
internal/streams/BufferList.js:15 Uncaught TypeError: Cannot read property 'length' of undefined
And the file is not sent to the server. Can anyone help me how can I solve this? Thanks
for a while I found the working solution for this problem is use base64 format to send it to the remote server :
var documentList = [];
var stmtDoc = db.prepare("SELECT * FROM `tb_dokumen_pasien`");
while(stmtDoc.step()) {
var rowDoc = stmtDoc.getAsObject();
var data = fs.createReadStream(__dirname + "/resources/" + rowDoc['id'] + "/" + rowDoc['doc_name']);
var base64 = Buffer.from(data).toString('base64');
var document = {
"document_name" : rowDoc['doc_name'],
"data" : base64
}
documentList.push(document);
}
And I still finding the best approach instead of using base64, Thanks

How to read data using JSONP, Ajax and jquery?

I am trying to read data from this API, but it is not working, I have an input box where I enter the isbn number and then get the data, using jsonp. Could you possibly help me in identifying where my error("Cannot read property 'title' of undefined") is?
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(isbn){
var infoUrl = isbn.info_url;
var thumbnailUrl = isbn.thumbnail_url;
var title = isbn.details.title;
var publishers = isbn.details.publishers;
var isbn13 = isbn.details.isbn_13;
console.log(isbn.info_url);
}
});
}
Open Library's API expects bibkeys to be prefixed with their type and a colon, rather than just the number alone:
function add(){
var isbn = 'ISBN:' + $("#isbn").val();
// ...
The colon also means the value should be URL-encoded, which jQuery can do for you:
$.ajax({
url: "https://openlibrary.org/api/books?jscmd=details&callback=?",
data: { bidkeys: isbn },
dataType: "jsonp",
Then, the data it returns reuses the bibkeys you provided as properties:
{ "ISBN:0123456789": { "info_url": ..., "details": { ... }, ... } }
To access the book's information, you'll have to first access this property:
success: function(data){
var bookInfo = data[isbn];
console.log(bookInfo.details.title);
// etc.
}
Example: https://jsfiddle.net/3p6s7051/
You can also retrieve the bibkey from the object itself using Object.keys():
success: function (data) {
var bibkey = Object.keys(data)[0];
var bookInfo = data[bibkey];
console.log(bookInfo.details.title);
// ...
}
Note: You can use this to validate, since the request can be technically successful and not include any book information (i.e. no matches found):
success: function (data) {
var bibkeys = Object.keys(data);
if (bibkeys.length === 0)
return showError('No books were found with the ISBN provided.');
// ...
Example: https://jsfiddle.net/q0aqys87/
I asked a professor, and this is how she told me to solve it:
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
var thumb=data["ISBN:"+isbn+""].thumbnail_url;
....
}
});
}

Why is this $.ajax function successful only the second time it's called?

I'm experimenting with the Rotten Tomatoes API. On a click event, a search returns JSON data for the closest matched movie title and thumbnail image to the search input.
Upon completion of that first $.ajax request, a second $.ajax request is made, using var resultID, which was declared at the top and set upon 'success' of the first $ajax request.
As of now, when I click for the first time, it runs the first request successfully, but it can't run return json.total (upon 'complete') because the resultID is returned as 'undefined'. But the second time I click, resultID has apparently been set, since it will return json.total successfully.
I'm guessing this a simple problem related to how I'm declaring and calling resultID (or the asynchronous firing of ajax), but I'm not sure what it is. Can anyone explain?
var apiKey = '***********';
var resultID = "";
$('#search-submit').click(function(){
var queryText = $('#movie-search').val();
var queryURI = encodeURI(queryText);
var searchApiRequest = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=" + queryURI + "&page_limit=10&page=1&apikey=" + apiKey;
var reviewApiRequest = "http://api.rottentomatoes.com/api/public/v1.0/movies/" + resultID + "/reviews.json?review_type=top_critic&page_limit=10&page=1&country=us&apikey=" + apiKey;
$.ajax({
url: searchApiRequest,
type: 'GET',
dataType: 'jsonp',
error: function() {
console.log('there was error in processing the search request.');
},
success: function(json) {
var movieInfo = json.movies[0];
var noResultsMessage = 'your search returned no matches. Please try again.';
var resultTitle = movieInfo.title;
var resultThumb = movieInfo.posters.thumbnail;
var resultDesc = movieInfo.critics_consensus;
var reviewsPublicURL = movieInfo.links.reviews;
var reviewsRequest = reviewsPublicURL;
resultID = movieInfo.id; // supposed to set global var resultID to movieID
$('.search-results').find('img').attr('src',resultThumb).end().find('h1').text(resultTitle).end().find('p').text(resultDesc);
},
complete: function() {
$.ajax({
url:reviewApiRequest,
type: 'GET',
dataType: 'jsonp',
error: function(json) {
console.log('for whatever reason, we could not find any reviews of this movie');
},
success: function(json) {
console.log(json.total);
}
});
}
});
});
You need to not only set a global resultID but also refresh a reviewApiRequest as well. It doesn't magically change its value by itself when you update resultID.

Categories

Resources