jQuery.get read values from data - javascript

I cannot seem to access the values in the returned data array from a jQuery.getJSON and I cannot understand why. I have this same code working elsewhere in my app, biggest difference being this particular instance returns one row only, as opposed to multiple in the other places.
When I manually execute the script I can see this JSON output:
[{"total_energy":"34011.920000","earliest_install_date":"2012-01-01"}]
When I execute the code below, the data array is empty / undefined. If I change the ".getJSON" to ".get" I can now see the values in data but I still cannot access them. I have tried via data.total_energy but I get "undefined". Any help is appreciated.
The Javascript code:
jQuery.getJSON(url, function(data) {
console.log("Earliest Date= " + data.earliest_install_date);
console.log("Total Energy= " + data.total_energy);
})
.done(function() {
})
.fail(function(jqxhr, textStatus, error ) {
var sysError = textStatus + ", " + error;
showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.<br/>If the issue persists please contact SMA for support...<br/>Error: " + sysError);
})
.always(function() {
});
The result in the console is:
Earliest Date= undefined
Total Energy= undefined

Your JSON is an array:
[{"total_energy":"34011.920000","earliest_install_date":"2012-01-01"}]
You need to access the first element of the array returned like so:
jQuery.getJSON(url, function(data) {
console.log("Earliest Date= " + data[0].earliest_install_date);
console.log("Total Energy= " + data[0].total_energy);
})
.done(function() {
})
.fail(function(jqxhr, textStatus, error ) {
var sysError = textStatus + ", " + error;
showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.<br/>If the issue persists please contact SMA for support...<br/>Error: " + sysError);
})
.always(function() {
});

Try this:
jQuery.getJSON(url, {})
.done(function(data) {
console.log("Earliest Date= " + data.earliest_install_date);
console.log("Total Energy= " + data.total_energy);
})
.fail(function(jqxhr, textStatus, error ) {
var sysError = textStatus + ", " + error;
showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.If the issue persists please contact SMA for support...Error: " + sysError);
})
.always(function() {
});

Related

Ajax request, when formatting the results, certain elements fail if I add over 2 lines of code

Sorry for the very weird wording of that question, I don't know how to explain it. Basically, I have a text input that acts as a search. Whenever you type a letter or word in, it makes a request to the Spotify API and returns the 5 best matching results; the code is below.
$("#SongSearch").keyup(function(){
$.ajax({
url: "https://api.spotify.com/v1/search?q=" + encodeURI(document.getElementById("SongSearch").value) + "&type=track&market=US&limit=5&offset=0",
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(InfoGained) {
document.getElementById("result1").innerHTML = InfoGained.tracks.items[0].name + ", " + InfoGained.tracks.items[0].artists[0].name;
document.getElementById("result2").innerHTML = InfoGained.tracks.items[1].name + ", " + InfoGained.tracks.items[1].artists[1].name;
document.getElementById("result3").innerHTML = InfoGained.tracks.items[2].name + ", " + InfoGained.tracks.items[2].artists[2].name;
document.getElementById("result4").innerHTML = InfoGained.tracks.items[3].name + ", " + InfoGained.tracks.items[3].artists[3].name;
document.getElementById("result5").innerHTML = InfoGained.tracks.items[4].name + ", " + InfoGained.tracks.items[4].artists[4].name;
}
});
});
This code correctly calls the API and gets the results. However, when formatting it, if I add more than two of the document.getElementByID... lines in, only two lines work. Example, this works:
$("#SongSearch").keyup(function(){
$.ajax({
url: "https://api.spotify.com/v1/search?q=" + encodeURI(document.getElementById("SongSearch").value) + "&type=track&market=US&limit=5&offset=0",
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(InfoGained) {
document.getElementById("result1").innerHTML = InfoGained.tracks.items[0].name + ", " + InfoGained.tracks.items[0].artists[0].name;
document.getElementById("result2").innerHTML = InfoGained.tracks.items[1].name + ", " + InfoGained.tracks.items[1].artists[1].name;
}
});
});
But more than two lines of the document.getElementID..., such as the first segment of code listed results in the error: "Uncaught TypeError: Cannot read property 'name' of undefined". Any help is appreciated as I truly have no idea what is causing this. Thanks in advance,
Justin
I realized after staring at it for an hour or two that InfoGained.tracks.items[4].artists[4].name; is calling the 5th artist for the 5th song. It should have been InfoGained.tracks.items[4].artists[0].name; Thank you everyone, especially Frax, for the help!

JQUERY: Uncaught error: Syntax error #

I'm programming with JQuery (v3.2.1) and I am getting an error
JQUERY: Uncaught Error: Syntax error, unrecognized expression: #
The code I have is:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "updateFieldDesc.php",
data: "idTerminal=" + idTerminal + "&aplicacion=" + aplicacion + "&nombre_campo=" + nombre_campo,
success:function (output) {
var salida = output.split("|");
var idCampo = salida[0];
var descripcion = salida[1];
//console.log("**********output :" + idCampo );
$("#" + idCampo).html(descripcion);
}
});
})
}
And the error is caused by the line: $("#" + idCampo).html(description)
How do I fix this error?
The issue is that your idCampo is a space (or other similar whitespace).
If your console log is:
console.log("**********output :" + idCampo )
and it gives " **********output : "
there's no space in your console log after the colon, but there is in your example output, which appears to be "empty". I always recommend a console log such as:
console.log("output : [" + idCampo + "]")
which, in this case should output as: [ ] (as opposed to empty [])
A quick snippet to show that $("# ") gives the same error you're getting:
try {
var space = " ";
$("#" + space).show();
} catch (e) {
console.log(e.message)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Window.onerror doesn't return info about error

I'm trying to create a custom error handler. I've got the following code to intercept the errors:
window.onerror = function (msg, url, lineNo, columnNo, error) {
console.log("msg: " + msg + "url: " + url + "lineNo: " + lineNo + "columnNo: " + columnNo);
}
Then later in the code I'm trying to console.log a variable that doesn't exist (in order to trigger the error). In the console I'm getting the custom:
msg: Script error.url: lineNo: 0columnNo: 0
And below that the default:
myjsfile.js:517 Uncaught ReferenceError: xyz is not defined(…)
How can I access this information - filename, line number, error message - and add it to my custom message? Thank you!
You really should use try-catch
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
create object with all your variables in try and throw it
try {
throw your_obj;
}
and
catch(e)
{
console.log(e); //will print whatever you made "your_obj" to be
}

Parse.com JavaScript query error handling does not work

I'm playing around with the Parse backend and NodeJS but I have a problem right now and I am not able to figure it out. I have a get request like this.
app.get("/movie", function (req, res) {
var Review = Parse.Object.extend("Review");
var query = new Parse.Query(Review);
var movie = req.query.movie;
query.equalTo("movie", movie);
query.first({
success: function (movie) {
console.log("Success");
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});});
This works fine but the error handling kinda doesn't. If, for example, I change
query.equalTo("movie", movie);
to query.equalTo("movie", "xyz");
or query.equalTo("abc", "xyz");
which does not exist in my table, I'm still getting the success statement. And yes, I have restarted the server every time.
Update
I tried the same query using the iOS SDK(Swift) and here I get into the error case. I always get the same error though, which shouldn't be, but at least I get an error while in the JS sample I always get into the success case.
I believe query.first() will not error if it does not find a "first" object. You can check for (movie == null) on the success return.
Update:
Try writing it this way:
app.get("/movie", function (req, res) {
var movie = req.query.movie;
var query = new Parse.Query("Review");
query.equalTo("movie", movie);
query.first().then(function (movie) {
// Success
console.log("Success");
}, function (error) {
// Error
console.log("Error: " + error.code + " " + error.message);
});
});
query.find() always success even if there is no match data in your table/collections
Let's try it
query.find().then(function (movies) {
if(movies.length > 0){
console.log("success");
}else{
console.log("query success but no data found");
}
}, function (error) {
// Error
console.log("Error: " + error.code + " " + error.message);
});

Unable to access vline.Message object with postMessage()

While implementing the vLine API, I came up with a problem. When using the postMessage() method of the vline.Channel class, the message was successfully received by the target user, but the the success callback of vline.Promise object did not return a valid vline.Message object. At least I don't have acess to some of the vline.Message methods, like getChannel() or getCreationTime().
Code:
$channel.postMessage(textMessage)
.done(function (message) {
console.log("Message sending successfull || Message sent to " + message.getChannel().getDisplayName() + " at " + message.getCreationTime());
},
this)
.fail(function (err) {
console.log("Message sending failed || Error Type: " + err.type + " || Error Message: " + err.message);
},
this);
Result (console log):
Message sending failed || Error Type: undefined || Error Message: Object #<Object> has no method 'getChannel'
Is this result of a API change that has not been yet referenced on the vLine Developer site or is there an error on the code?
This was a bug on our end; sorry about that. It should now be fixed.

Categories

Resources