can't find previously imported js module - javascript

I'm facing an error where a jQuery code can't find a previously imported module.
I'm using jQuery and tag-it (https://github.com/aehlke/tag-it/blob/master/README.markdown)
I import the scripts in this order:
<script src="js/vendor/jquery.min.js" type="text/javascript"></script>
<script src="js/vendor/jquery-ui.min.js" type="text/javascript"></script>
<script src="js/vendor/jquery-ui-touch-punch.min.js" type="text/javascript"></script>
<script src="js/vendor/tag-it.min.js" type="text/javascript"></script>
<script src="js/tags.js" type="text/javascript"></script>
tag-it.min.js is the Tag-It provided js module and tags.js is my custom module.
tags.js is as follows:
$(document).ready(function(){
var $available_tags = $('#user_tags').val().split(",").slice(0, -1);
$('#tags').tagit({
fieldName: "tags",
availableTags: $available_tags,
placeholderText: "Enter Tags",
beforeTagAdded: function(event, ui){
var tag = ui.tag.text().slice(0, -1);
if($.inArray( tag, $('#user_tags').val().split(",") ) == -1){
$.get("/tags/add?tag=" + tag, function(data){
if(!data.error){
$("#user_tags").val( $("#user_tags").val() + tag + ",");
} else {
console.log("Eror", data);
return false;
}
});
}
},
showAutocompleteOnFocus: true
});
});
The error is in tags.js at line 6:
$('#tags').tagit({
Undefined error: tagit does not exist.
http://puu.sh/gCVUh/2d792035f6.png
How is this possible? The js loading order is fine and yet it seems not to recognice it.
Thanks in advance, if more information is needed ask for it and I'll update the thread.

Ok I found out why it wasn't working.
I just noticed that I duplicated jQuery script import some lines after these imports.
This was resseting jQuery enviroment and therefore, tag-it was removed from it.
Hope this helps someone in a future and thanks for the help!

Related

IE Uncaught ReferenceError: jQ is not defined, but works in Chrome

I get an
Uncaught ReferenceError: jQ is not defined
in the Internet Explorer and some tabs aren't being loaded.
But using Chrome it works perfectly fine.
I think it's because the script order for jquery might be wrong. This is what I have in my startpage.js
<script src="/tools/Scripts/tools/jquery/v2_1_4/jquery-2.1.4.min.js"></script>
<script src="/tools/scripts/tools/jqueryui/jquery-ui.min.js"></script>
<script src="/tools/scripts/tools/jqgrid/js/i18n/grid.locale-de.js"></script>
<script src="/tools/scripts/tools/jqgrid/js/jquery.jqGrid_5_3_0.min.js"></script>
<script src="/tools/scripts/tools/jqgrid/js/jszip.min.js"></script>
<script src="/tools/scripts/apps/cpc.js"></script>
<script src="/tools/scripts/apps/3rdParties/startPage3rdParties.js"></script>
<script src="/tools/Scripts/tools/date.js"></script>
<script src="/tools/Scripts/tools/jquerymap/dist/jquery.vmap.min.js"></script>
<script src="/tools/Scripts/tools/jquerymap/dist/maps/jquery.vmap.world.js"></script>
In this startpage.js I define jQ like this:
var jQ = jQuery.noConflict(true);
In a function loadSubtables() I call some functions from gridhandling.js:
function loadSubTables() {
if (checkNull(curuserid) == "") {
curuserid = _spPageContextInfo.userId;
}
loadGrid("AKG", "&$select=Id,Title,Projektstichwort,SD_x002d_Nummer,AKGStatus,Created,Author/Title,Author/Department,Author/WorkPhone&$expand=Author&$filter=Author eq " + curuserid + " or Projektleiter eq " + curuserid +"&$orderby=Id desc", "gridmy", cnMyEntries, cmMyEntries, true, false);
loadGrid("AKG", "&$select=Id,Title,Projektstichwort,SD_x002d_Nummer,AKGStatus,Created,Author/Title,Author/Department,Author/WorkPhone&$expand=Author&$filter=AKGStatus eq 'Aktiv'&$orderby=Id desc&$top=9999", "gridactive", cnMyEntries, cmMyEntries, true, false);
loadGrid("AKG", "&$select=Id,Title,archivFlag,Projektstichwort,SD_x002d_Nummer,AKGStatus,Created,Author/Title,Author/Department,Author/WorkPhone&$expand=Author&$orderby=Id desc&$top=9999", "gridall", cnAllEntries, cmAllEntries, true, false);
}
The error I get refers to this line from the gridhandling.js:
function loadGrid(listname, query, divname, colnames, colmdodel,showSubGrid,subGridFunction) {
jQ("#" + divname).jqGrid({
I checked if jQuery is loaded, which it is, but since 5 hours I can't figure out what the problem is and how to fix this bug. Sometimes it doesn't load anything and just says jQ( “#tabs” ).tabs(); is not a function
Can someone help me?

Sharepoint Document Library - Filename to title using javascript

Good evening!
I had a working functionality on a sharepoint document library. It's purpose was to copy the name of a file to the title column.
It was working for a long time but after an update to the sharepoint platform it stopped working and i can't figure out why.
The code:
<input type="button" onclick="updateTitleFromName()" value="Update Title from Name" />
<script type="text/javascript" src="/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="/Scripts/spjs-utility/spjs-utility.js"></script>
<script type="text/javascript">
function updateTitleFromName(){
var q, res, uRes, count;
count = 0;
q = "<Where><IsNull><FieldRef Name='Title' /></IsNull></Where>";
res = spjs_QueryItems({"listName":_spPageContextInfo.pageListId,"query":q,"viewFields":["ID","FileLeafRef"]});
if(res.count === 0){
alert("No files without title found.");
return;
}
if(!confirm("There are "+res.count+" files to update. The page will appear as frozen while the script is working.\n\nContinue?")){
return;
}
$.each(res.items,function(i,item){
uRes = spjs_updateItem({"listName":_spPageContextInfo.pageListId,"id":item.ID,"data":{"Title":item.FileLeafRef.split(";#")[1]}});
if(!uRes.success){
alert("Could not update the file: "+item.FileLeafRef+" due to the follwing error:\n\n"+uRes.errorText);
}else{
count += 1;
}
});
alert("Updated "+count+" files.");
location.href = location.href;
}
</script>
The error is: TypeError: $spjs is null. And it occurs inside the library spjs-utility library on the spjs_QueryItems call.
Maybe this could be due to a conflictuous library that as added during the updated, but how can i debug this?
Also, if this doesn't work, wouldn't it be simpler to do the same with jQuery? Thats what i'm trying right now, but i'm a beginner as you must have perceived.
Thanks in advance.
Best
I would test if JQuery is loaded or not in your updateTitleFromName function:
if (window.jQuery) {
alert('loaded');
} else {
alert('not loaded');
}
if it is not loaded, try to reference your scripts with absolute urls to see if you can load them:
<script type="text/javascript" src="http://myportal/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://myportal/Scripts/spjs-utility/spjs-utility.js"></script>

jquery cookie issue: $.cookie is not a function

I know this question has been asked multiple times. I looked at many answers but couldn't find a solution.
I am trying to load jquery.cookie.js script. Here is how:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="scripts/jquery.cookie.js"></script>
<script type="text/javascript" src="scripts/javascript.js"></script>
This is my javascript:
$(document).ready(function () {
var jobStats_class = $.cookie('jobStats');
// Add toggle feature
$('.jobStats caption').click(function () {
$('.jobStats th,.jobStats td').slideToggle('1000');
});
$('.ricSubscriptions caption').click(function () {
$('.ricSubscriptions th,.ricSubscriptions td').slideToggle('1000');
});
$('.trthJobStatus caption').click(function () {
$('.trthJobStatus th,.trthJobStatus td').slideToggle('1000');
});
});
Thanks for your help!
Since version 2.0, jquery-cookie project has moved to js-cookie project.
Now you can't handle cookies with $ variable (because this library didn't really use special functions of jQuery). Now, you have to use Cookies variable :
Create a cookie
//OLD
$.cookie('name', 'value', { expires: 7, path: '/' });
//NEW
Cookies.set('name', 'value', { expires: 7, path: '/' });
Read a cookie
//OLD
$.cookie('name');
//NEW
Cookies.get('name');
Read all cokies
//OLD
$.cookie();
//NEW
Cookies.get();
Delete a cookie
//OLD
$.removeCookie('name');
//NEW
Cookies.remove('name');
Your script path is the problem. Try this cdn:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>

How to load different html files in QUnit?

I'm using QUnit for unit testing js and jquery.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<script src="../lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.16.0.css" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<!--This is where I may have to add startPage.html--->
<script src="../login.js"></script>
<script src="../test/myTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Currently, I'm adding login.js as shown and I'm getting references correctly to objects defined in login.js.
However, functions in login.js contains references to some dom elements defined in startPage.html which is located elsewhere.
So, if I say $('#login-btn'), it is throwing an error. Is there any way to fix this?
Can I
(a) refer to startPage.html to my qunit page given above?
(b) refer to or load startPage.html in the file where I'm running tests (myTests.js):
QUnit.test( "a test", function( assert ) {
assert.equal( 1, "1", "String '1' and number 1 have the same value" );//works
assert.equal( login.abc, "abc", "Abc" );//works with attributes
assert.equal(($("#userid").val()),'', 'Userid field is present');//fails
assert.equal( login.ValidUserId(), true, "ValidUserId" );//fails with functions
});
Does QUnit provide any method to load Html/php files so they'll be defined prior to testing. Like 'fixtures' in jasmine?
EDIT: Please also tell what to do in case I have startPage.php
There are a couple of ways you can do this. The simplest is just to use the built-in QUnit "fixtures" element. In your QUnit HTML file, simply add any HTML you want in the div with the id of qunit-fixture. Any HTML you put in there will be reset to what it was on load before each test (automatically).
<html>
...
<body>
<div id='qunit'></div>
<div id='qunit-fixture'>
<!-- everything in here is reset before each test -->
<form>
<input id='userid' type='text'>
<input id='login-btn' type='submit'>
</form>
</div>
</body>
</html>
Note that the HTML in the fixture doesn't really have to match what you have in production, but obviously you can do that. Really, you should just be adding the minimal necessary HTML so that you can minimize any side effects on your tests.
The second option is to actually pull in the HTML from that login page and delay the start of the QUnit tests until the HTML loading is complete:
<html>
<head>
...
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script>
// tell QUnit you're not ready to start right away...
QUnit.config.autostart = false;
$.ajax({
url: '/path/to/startPage.html',
dataType: 'html',
success: function(html) {
// find specific elements you want...
var elem = $(html).find(...);
$('#qunit-fixture').append(elem);
QUnit.start(); // ...tell QUnit you're ready to go
}
});
</script>
...
</head>
...
</html>
Another way to do this without using jquery is as follows
QUnit.config.autostart = false;
window.onload = function() {
var xhr = new XMLHttpRequest();
if (xhr) {
xhr.onloadend = function () {
if(xhr.status == 200) {
var txt = xhr.responseText;
var start = txt.indexOf('<body>')+6;
var end = txt.indexOf('</body>');;
var body_text = txt.substring(start, end);
var qunit_fixture_body = document.getElementById('qunit-fixture');
qunit_fixture_body.innerHTML = body_text;
}
QUnit.start();
}
xhr.open("GET", "index.html");
xhr.send();
} else {
QUnit.start(); //If getting the html file from server fails run tests and fail anyway
}
}

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

I'm setting up a pretty simple app with backbone, and I'm getting an error.
Uncaught TypeError: undefined is not a function example_app.js:7
ExampleApp.initialize example_app.js:7
(anonymous function)
This is where the error is showing up in Chrome Inspector (init file - example_app.js):
var ExampleApp = {
Models: {},
Collections: {},
Views: {},
Routers: {},
initialize: function() {
var tasks = new ExampleApp.Collections.Tasks(data.tasks);
new ExampleApp.Routers.Tasks({ tasks: tasks });
Backbone.history.start();
}
};
Here's my tasks index.haml file
- content_for :javascript do
- javascript_tag do
ExampleApp.initialize({ tasks: #{raw #tasks.to_json} });
= yield :javascript
models / task.js
var Task = Backbone.Model.extend({});
collections / tasks.js
var Tasks = Backbone.Collection.extend({
model: Task,
url: '/tasks'
});
routers / tasks.js
ExampleApp.Routers.Tasks = Backbone.Router.extend({
routes: {
"": "index"
},
index: function() {
alert('test');
// var view = new ExampleApp.Views.TaskIndex({ collection: ExampleApp.tasks });
// $('body').html(view.render().$el);
}
});
And here's proof that I'm calling all of the files (I think):
<script src="/assets/jquery.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery-ui.js?body=1" type="text/javascript"></script>
<script src="/assets/underscore.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone-support/support.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone-support/composite_view.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone-support/swapping_router.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone-support.js?body=1" type="text/javascript"></script>
<script src="/assets/example_app.js?body=1" type="text/javascript"></script>
<script src="/assets/easing.js?body=1" type="text/javascript"></script>
<script src="/assets/modernizr.js?body=1" type="text/javascript"></script>
<script src="/assets/models/task.js?body=1" type="text/javascript"></script>
<script src="/assets/collections/tasks.js?body=1" type="text/javascript"></script>
<script src="/assets/views/task_view.js?body=1" type="text/javascript"></script>
<script src="/assets/views/tasks.js?body=1" type="text/javascript"></script>
<script src="/assets/views/tasks_index.js?body=1" type="text/javascript"></script>
<script src="/assets/routers/tasks.js?body=1" type="text/javascript"></script>
<script src="/assets/tasks/index.js?body=1" type="text/javascript"></script>
<script src="/assets/tasks/task.js?body=1" type="text/javascript"></script>
<script src="/assets/application.js?body=1" type="text/javascript"></script>
Any ideas would be great. Thanks!
Uncaught TypeError: undefined is not a function example_app.js:7
This error message tells the whole story. On this line, you are trying to execute a function. However, whatever is being executed is not a function! Instead, it's undefined.
So what's on example_app.js line 7? Looks like this:
var tasks = new ExampleApp.Collections.Tasks(data.tasks);
There is only one function being run on that line. We found the problem! ExampleApp.Collections.Tasks is undefined.
So lets look at where that is declared:
var Tasks = Backbone.Collection.extend({
model: Task,
url: '/tasks'
});
If that's all the code for this collection, then the root cause is right here. You assign the constructor to global variable, called Tasks. But you never add it to the ExampleApp.Collections object, a place you later expect it to be.
Change that to this, and I bet you'd be good.
ExampleApp.Collections.Tasks = Backbone.Collection.extend({
model: Task,
url: '/tasks'
});
See how important the proper names and line numbers are in figuring this out? Never ever regard errors as binary (it works or it doesn't). Instead read the error, in most cases the error message itself gives you the critical clues you need to trace through to find the real issue.
In Javascript, when you execute a function, it's evaluated like:
expression.that('returns').aFunctionObject(); // js
execute -> expression.that('returns').aFunctionObject // what the JS engine does
That expression can be complex. So when you see undefined is not a function it means that expression did not return a function object. So you have to figure out why what you are trying to execute isn't a function.
And in this case, it was because you didn't put something where you thought you did.
I have occurred the same error look following example-
async.waterfall([function(waterCB) {
waterCB(null);
}, function(**inputArray**, waterCB) {
waterCB(null);
}], function(waterErr, waterResult) {
console.log('Done');
});
In the above waterfall function, I am accepting inputArray parameter in waterfall 2nd function. But this inputArray not passed in waterfall 1st function in waterCB.
Cheak your function parameters Below are a correct example.
async.waterfall([function(waterCB) {
waterCB(null, **inputArray**);
}, function(**inputArray**, waterCB) {
waterCB(null);
}], function(waterErr, waterResult) {
console.log('Done');
});
Thanks
[Joke mode on]
You can fix this by adding this:
https://github.com/donavon/undefined-is-a-function
import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.
[joke mode off]
If in MongoDB with async-await , check if you have a missing await before the mongo call.
const [assistantError, assistant] = await assistantDb.findOneAssistant({
_id: assistantId,
});
Here if the await was missing, later when you use assistant, this issue may occur.

Categories