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>
Related
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!
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
}
i want get weather forecast and conditions from wunderground , but when i run the code have error with current_observation , the current_observation in side data json of api .
$(document).ready(function($){
$.ajax({
url: "http://api.wunderground.com/api/72df18b7f213607b/conditions/forecast/lang:AR/q/CO/zmw:00000.1.WKQTZ.json",
dataType : "jsonp",
success : function(parsed_json) {
var forecast = parsed_json['forecast']['txt_forecast']['forecastday']['conditions']['current_observation'];
for (index in forecast,conditions) {
var newForecastString = 'Weather forecast for ' + forecast[index]['title'] + ' is ' + forecast[index]['fcttext_metric'];
var newconditionsString = 'Weather forecast for ' + forecast[index]['title'] + ' is ' + forecast[index]['station_id'];
var newForecastParagraph = $('<p/>').text(newForecastString);
$("body").append(newForecastParagraph);
}
}
}); });
its becauseparsed_json['forecast']['txt_forecast']['forecastday'] does not have conditions in it. So parsed_json['forecast']['txt_forecast']['forecastday']['conditions'] will be undefined and you are asking for current_observation on top of undefined.
"forecast":{
"txt_forecast": {
"date":"6:28 PM AST",
"forecastday": [{
"period":0,
"icon":"clear",
"icon_url":"http://icons.wxug.com/i/c/k/clear.gif",
"title":"السبت",
"fcttext":"صافٍ غالبًا. درجة الحرارة الصغرى 81 درجة فهرنهيت.",
"fcttext_metric":"صافٍ غالبًا. درجة الحرارة الصغرى 27 درجة مئوية.",
"pop":"0"
}]
}
}
current_observation is at the top level, e.g., parsed_json['current_observation].
Unrelated, but it might be better to post the JSON than expose your API key.
If you're looking for the conditions, they're not an array anywhere, they're a single string value, found in various places.
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() {
});
On the server side do I have 2 hashes I encode into JSON strings like so
my $j = JSON->new;
$j = $j->utf8;
my $data;
$data->{users} = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string = to_json($data);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
On the client side I have
$(document).ready(function(){
$('form').live('submit', function(){
$.ajax({
type: "GET",
url: "/cgi-bin/ajax_confirm.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: $(this).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
},
success: function(result){
if (result.error) {
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
var users = result.users;
var owners = result.owners;
...
users contains
{"ss":"Sandra Schlichting","fn":"Full name"}
but it is not an array. When I use $.each() it takes on character at a time.
Problem
How do I turn it into an array, so I can use
function makeTable(users) {
var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
which should produce
Initials Full Name
ss Sandra Schlichting
fn Full name
You should use jQuery.getJSON() as mentioned at http://api.jquery.com/jQuery.getJSON/.
There is also $.parseJSON() method to parse string to json if you want to go that way.
You don't need to turn it into an array. According to the jQuery.each() documentation it takes both arrays or objects and JSON is a subset of the object literal notation of JavaScript.
Edit: Here's an example: http://jsfiddle.net/pedrocorreia/s5UrZ/2/
You can use the JSON parser created by douglas crockford:
https://github.com/douglascrockford/JSON-js
include the json2.js in your page, the you can do:
var object = JSON.parse(string);
Then you can use it as an array.
you can use for in statement
var index = 0;
for(user in users){
result += '<tr><td>' + index + '</td><td>' + user['fn'] + '</td></tr>\n';
index++;
}