This question already has answers here:
Uncaught ReferenceError: $ is not defined rails
(7 answers)
Closed 6 years ago.
I keep getting this console error when trying to load data from an API
Uncaught ReferenceError: $ is not defined
I have tried placing a JQuery script within the app and it does not work.
I just want the data to append to the #resultContainer when the page is loaded
app/views/locations/show.html.erb
<div id="resultContainer"></div>
app/assets/javascripts/application.js
var _PremiumApiBaseURL = 'http://api.worldweatheronline.com/premium/v1/';
var _PremiumApiKey = 'APIKEY';
//Get Marine Weather Data
function JSONP_MarineWeather(input) {
var url = _PremiumApiBaseURL + "marine.ashx?q=" + input.query +
"&format=" + input.format +
"&fx=" + input.fx +
"&key=" + _PremiumApiKey +
"&tide=yes&";
jsonP(url, input.callback);
}
// Helper
function jsonP(url, callback) {
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
jsonpCallback: callback,
dataType: 'jsonp',
success: function (json) {
console.dir('success');
},
error: function (e) {
console.log(e.message);
}
});
}
var resultContainer = $('#resultContainer');
var output = '';
$(document).ready(function () {
GetMarineWeather();
});
function GetMarineWeather(e) {
var marineWeatherInput = {
query: '26.13,-80.10',
format: 'JSON',
fx: '',
callback: 'MarineWeatherCallback'
};
JSONP_MarineWeather(marineWeatherInput);
e.preventDefault();
}
function MarineWeatherCallback(marineWeather) {
var allDataToday = marineWeather.data.weather[0]
output = "<br/> Date: " + allDataToday.date;
output += "<br/> Min Temp (f): " + allDataToday.mintempF;
output += " - Max Temp (f): " + allDataToday.maxtempF;
output += "<br/>";
//6AM
output += "<br/> Time: 6AM";
output += " - Surf: " + allDataToday.hourly[2].swellHeight_ft + "ft";
output += " - Swell: " + allDataToday.hourly[2].swellDir16Point + " " + allDataToday.hourly[2].swellPeriod_secs + "sec";
resultContainer.empty();
resultContainer.html(output);
}
Help
Make sure you've properly included jQuery library before calling jQuery functions Or Check any conflicting JavaScript libraries which shares jQuery $ alias.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
IF any other JavaScript libraries' $ variable has some conflicts with jQuery, You can use jQuery.noConflict() method to avoid the same.
Eg.
var jq = jQuery.noConflict();
jq( "div p" ).hide(); //Instead of $( "div p" ).hide();
If you can access jQuery by typing jQuery, you can alias it yourself with $ = jQuery;
Related
I have JS code in web page like this
<script type="text/javascript">
var jq = jQuery.noConflict();
function table_data_update() {
$jq.ajax({
url: "query_issue.php",
data: { "start_date": "20160705", "end_date": "20160706" },
success: function (data) {
var table = document.getElementById("test_table");
$jq.each(data, function (k, v) {
table.innerHTML +=
"<tr><td>" + v.id + "</td><td>" + v.D1 + "</td><td>" + v.D2 + "</td><td>";
});
},
error: function (xhr, options, error) {
}
});
}
function table_init() {
setInterval(table_data_update, 30000);
}
$jq(document).ready(table_init); //<=Uncaught ReferenceError $jq is not defined
alert($jq);
</script>
At code $jq(document).ready(table_init);, it show error uncaught referenceerror $ is not defined.
I confirm jquery has been reference in html. I use Chrome DevTools to debug and set breakpoints at var jq = jQuery.noConflict(); and $jq(document).ready(table_init);. The first breakpoint can execute successfully. BUT, the second breakpoint hit twice. First time is pass and popup tips shows jQuery has loaded. But second time is error and show uncaught referenceerror $ is not defined.
Can anyone help me? Thank you very much!
Your definition should be var $jq = jQuery.noConflict(); instead of var jq = jQuery.noConflict();. Try the code below:
var $jq = jQuery.noConflict();
function table_data_update() {
$jq.ajax({
url: "query_issue.php",
data: { "start_date": "20160705", "end_date": "20160706" },
success: function (data) {
var table = document.getElementById("test_table");
$jq.each(data, function (k, v) {
table.innerHTML +=
"<tr><td>" + v.id + "</td><td>" + v.D1 + "</td><td>" + v.D2 + "</td><td>";
});
},
error: function (xhr, options, error) {
}
});
}
function table_init() {
setInterval(table_data_update, 30000);
}
$jq(document).ready(table_init); //<=Uncaught ReferenceError $jq is not defined
alert($jq);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Good morning, I come to you guys looking for some assistance getting two functions to work. I think I'm almost there but I'm missing something. I cannot get the field in SharePoint to update but I can get my document to open no problem. Is something missing in the code below?
<script type="text/javascript">
function fnUpdateRecord(userId, id) {
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List(" + id + ")?$select=ViewBy", function (data) {
var viewby = data.d.ViewBy;
var username = userId;
var doc = new Object();
doc.ViewBy = username;
$.ajax({
method: "POST",
url: "PROGRAM/_vti_bin/listdata.svc/List(" + id + ")",
contentType: "application/json; charset=utf-8",
processData: false,
beforeSend: beforeSendFunction,
data: JSON.stringify(doc),
dataType: "json",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
}
});
});
}
function fnRecordAccess(id, path) {
$.ajax({
url: "GetCurrentUser.aspx",
context: document.body
}).success(function(result) {
var userId = $(result).find('.wtf').text()
fnUpdateRecord(userId, id);
window.open(path, "othrWn");
}).error(function(error) {
console.log(error);
});
}
</script>
I think call those functions via an OnClick:
onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a>
I can get the item/infopath form to load in another window but it doesn't seem to run the function to add the username in the ViewBy column. Any ideas? Thank you for assisting!
Edit: Added fnCountrySearch; this calls the other functions.
function fnCountrySearch(choice) {
fnWaitDialog("show");
var searchId = choice;
$("#tableBody tr").remove();
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List?$filter=Country eq '" + searchId + "'&$orderby=Name", function (data) {
var d = data.d;
if (d.results.length == 0) {
$("#noResultsAlert").show();
$("#notingQueried").hide();
}
else {
$.each(d.results, function (n, i) {
var path = i.Path + "/" + i.Name;
$("#tableBody").append("<tr><td>" + "<a class='btn btn-sm btn-default' class='pull-left' href='#' onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a></td></tr>");
});
$("#noResultsAlert").hide();
$("#notingQueried").hide();
}
})
.always(function () {
fnWaitDialog("hide");
});
}
The beforeSendFunction:
function beforeSendFunction(xhr) {
// Manipulate headers for update
xhr.setRequestHeader("If-Match", "*");
// Using MERGE so that the entire entity doesn't need to be sent over the wire.
xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
}
REST
To compare your code with published examples, you can refer to Microsoft's documentation of SharePoint 2010's REST interface here:
Data Access for Client Applications: Using the REST Interface
Reference Implementation: Client: Using the REST Interface from JavaScript
JSOM
SharePoint 2010 does have a JavaScript client object model that you can use as an alternative to the REST API. This can be an especially attractive option if you find yourself invoking the REST API via JavaScript, since the client object model does not require additional libraries.
If you were to rewrite your fnUpdateRecord method to use the JavaScript client object model it would look like this:
fnUpdateRecord(userId, id){
var listName = "List", fieldName = "ViewBy", newValue = userId + " # " + new Date() + ";\n";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listName);
var item = list.getItemById(id);
clientContext.load(item);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
// get current field value...
var currentValue = item.get_item(fieldName);
item.set_item(fieldName, newValue + currentValue);
item.update();
// update the field with the new value
clientContext.executeQueryAsync();
}),Function.createDelegate(this,function(sender,args){alert(args.get_message());}));
}
Note that when using the JavaScript Client Object Model, you need to wait for the SP.JS library to load first. This can be accomplished using the built-in ExecuteOrDelayUntilScriptLoaded method like so:
ExecuteOrDelayUntilScriptLoaded(yourFunctionName,"SP.JS");
or
ExecuteOrDelayUntilScriptLoaded(function(){
// your code here
},"SP.JS");
Hi all and thanks in advance for the help:
i got this error:
Uncaught SyntaxError: Unexpected identifier
for line 65 (the line with the "Var query"... here the third line)
and when i click on the Execute button this is the other error:
Uncaught ReferenceError: retrieveData is not defined
(retrieveData is the function i call with the click)
i have used an existing code modifyng it for my purpose.
the very strange things are:
1: the original code run without errors (and it seems to me quite the same)
2: if i paste the url and the query and &output=json on the browser, it works fine... so i think it's not an error about mispelling...
this is the code I wrote:
<script type="text/javascript">
function retrieveData() {
var query = "SELECT ?museum WHERE {?museum a <http://dbpedia.org/ontology/Museum>.?museum <http://dbpedia.org/ontology/address> ?address. FILTER contains(?address, "Firenze")}";
var url = 'http://it.dbpedia.org/sparql?default-graph-uri=&query=' + encodeURIComponent(query) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
$('#results').show();
$('#raw_output').text(JSON.stringify(data, null, 3));
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$.each(
json['results']['bindings'], function(index, value) {
var html = "";
name = value['museum']['value'].replace("http://it.dbpedia.org/resource/", "");
name = decodeURIComponent(name.replace(/_/g, " "));
html += "<div><h3><b>" + name + ":</b> () </h3></div>";
$('#output_div').append(html);
}
);
}
</script>
and this is the original code:
<script type="text/javascript">
function retrieveData() {
var query = "PREFIX : <http://dbpedia.org/resource/> PREFIX dbp: <http://dbpedia.org/ontology/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX dbpprop: <http://dbpedia.org/property/> SELECT ?person ?b_date ?d_date ?abstract ?thumbnail WHERE { ?person rdf:type dbp:Person ; dbp:birthDate ?b_date ; dbp:deathDate ?d_date ; dbp:abstract ?abstract . OPTIONAL { ?person dbp:thumbnail ?thumbnail } FILTER ( ?b_date >= '1488-01-01'^^xsd:date && ?b_date < '1600-01-01'^^xsd:date && ?d_date < '1650-01-01'^^xsd:date ) FILTER ( langMatches(lang(?abstract), 'EN')) } ORDER BY ?person ?b_date";
var url = 'http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=' + encodeURIComponent(query) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
$('#results').show();
$('#raw_output').text(JSON.stringify(data, null, 3));
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$.each(
json['results']['bindings'], function(index, value) {
var html = "";
name = value['person']['value'].replace("http://dbpedia.org/resource/", "");
name = decodeURIComponent(name.replace(/_/g, " "));
html += "<div><h3><b>" + name + ":</b> (" + value['b_date']['value'] + " - " + value['d_date']['value'] + ")</h3></div>";
if (value['thumbnail'] != null)
html += "<div class='inline thumb'><img style='width: 200px' src='" + value['thumbnail']['value'].replace("200px", "150px") + "'/></div>";
else
html += "<div class='inline thumb'><img src=''/></div>";
html += "<div class='inline abstract'>" + value['abstract']['value'] + "</div><div class='clear'></div><br>";
$('#output_div').append(html);
}
);
}
</script>
Thanks again
--UPDATE--
Obviously i 'm made a mess with quotation mark. Thanks dodl. Now it works.
A LITTLE NOTE if anyone tries to run this script:
It will come "XMLHttpRequest same domain policy error"...
Just add the '&callback=?' in the url, using the built-in support for JSONP in JQUERY.
You're not escaping your quotation marks properly, ie:
var query = "SELECT ?museum WHERE {?museum a <http://dbpedia.org/ontology/Museum>.?museum <http://dbpedia.org/ontology/address> ?address. FILTER contains(?address, "Firenze")}";
should be
var query = "SELECT ?museum WHERE {?museum a <http://dbpedia.org/ontology/Museum>.?museum <http://dbpedia.org/ontology/address> ?address. FILTER contains(?address, \"Firenze\")}";
(Or alternatively, in javascript you can use single and double quotes to differentiate quotes within strings from string definition quotes.)
This question already has answers here:
Add a loading animation to jquery ajax .load()
(5 answers)
Closed 8 years ago.
I am creating an application in Node, which pulls objects in my Schema (Mongo) and presents them in HTML. Okay, all right so far.
Now I need to create a jQuery loader, which features a picture like this while the objects do not appear in the html -> http://i.imgur.com/hq37Dew.gif while the data does not appear.
$.ajax({
type: 'GET',
url: host + '/datas',
success:function(datas) {
datas.forEach (function (data) {
var HTML = [];
HTML.push('<tr class="datas">');
HTML.push('<td>' + data.email + '</td>');
HTML.push('<td>' + name.email + '</td>');
reservasHTML.push('</tr>');
$('tbody').append(reservasHTML.join(''));
})
}
});
How I can do this?
$.ajax({
$(".datas").empty().html('<img src="http://i.imgur.com/hq37Dew.gif" />'); // SHOW THE AJAX LOADER
type: 'GET',
url: host + '/datas',
success:function(datas){
$(".datas").html(datas); // this will hide the loader and replace it with the data
datas.forEach (function (data) {
var HTML = [];
HTML.push('<tr class="datas">');
HTML.push('<td>' + data.email + '</td>');
HTML.push('<td>' + name.email + '</td>');
reservasHTML.push('</tr>');
$('tbody').append(reservasHTML.join(''));
})
}
});
I think this is it.
Assuming that you give the image an id of image_id ,
$.ajax({
type: 'GET',
url: host + '/datas',
beforeSend: function(){
// Code to show the image . e.g.
$('#image_id').show();
},
success:function(datas) {
// Code to hide image again / completely make it display-none
$('#image_id').hide // or $('#image_id').css("display","none");
reservas.forEach (function (data) {
// ........
})
}
});
$.ajax({
type: 'GET',
url: host + '/datas',
beforeSend: function() {
// Add loader here
$(placeholder).addClass('loading');
},
complete: function() {
//hide loader here/
$(placeholder).removeClass('loading');
},
success:function(datas){
datas.forEach (function (data) {
var HTML = [];
HTML.push('<tr class="datas">');
HTML.push('<td>' + data.email + '</td>');
HTML.push('<td>' + name.email + '</td>');
reservasHTML.push('</tr>');
$('tbody').append(reservasHTML.join(''));
})
}
});
hope this works
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am getting a list from C# web method with ajax (code below), the list is returned fine, but after the success method is done, it gives me an error - (Cannot read property 'length' of undefined) in the jquery (screenshot below)
Am I missing something ??
function getMainParentMenus() {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
The method above is called by the below method.
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
// var parentMenus = getMainParentMenus();
getMainParentMenus();
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
};
EDIT :
the data in the alert in the first block of code above is displayed like so
and in the chrome debugger :
Because getMainParentMenus is using AJAX it is asynchronous. Your next line of code after calling getMainParentMenus will be executed before the .success part of your AJAX call, so it will be executed before parentMenuss has been populated.
There are a few ways you can tackle this, one way would be to pass the callback function to getMainParentMenus, something like this:
function getMainParentMenus(myCallback) {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
if (callback && typeof(callback)==="function") {
callback();
}
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
Now you can call it like this:
var html = "<div id='accordian'> ddd";
getMainParentMenus(function() {
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
});
Your code for rendering the menus is being executed immediately after getMainParentMenus(); Javascript does not wait for the ajax call to complete before moving on to the next block. It is operating asynchronously, as others have mentioned in the comments.
Your code has to wait for the ajax call to complete before trying to display the data.
jQuery supports deferred execution and promises, so you can create code that will not execute until other code has completed. This is the preferred way of handling asynchronous operations.
Try this:
function getMainParentMenus() {
var request = $.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
return request;
}
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
getMainParentMenus().success(function (result) {
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
});
}