Import JSON file to JavaScript function - django

Is it possible to import a JSON file into a JavaScript function? If yes, how can this be done the best practice way?
Below is my code with a few json rows and It'd be insane to have a million rows hardcoded in the function.
<script>
$( function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
} );
</script>

You can do this:
var availableTags = JSON.parse("{{ context|escapejs }}");
and then you can loop over normally in Javascript.
Check out the codepen. It clearly works at the front end, the issue might be at the backend.

Related

Search query in mongodb using regular expression

im building a website, using nodejs, expressjs, mongodb, mongoose, body-parser and etc..
basically i've created a search function, where you can search for users and basically it works, but the problem is, it is case-sensitive, i want to search for the user using case-insensitive.
I have found a solution here in stack overflow and tried it on my mongo shell. this is the command
db.loginusers.find({
$or:
[
{"firstname": {$regex: /^PIa$/i}},
{"lastname": {$regex: /^NAtUrE$/i}}
]
})
this works on mongoshell. so when i try to put this on my JS file,
app.post("/searchresult", function(req, res){
var thename = req.body.thename;
LoginUser.find({
$or: [
{"firstname": {$regex: /^thename$/i}},
{"lastname": {$regex: /^thename$/i}}
]
}, function(err, searchedUser){
if(err){
console.log(err);
res.redirect("back");
} else {
res.render("searchprofile", {foundUser: searchedUser});
}
});
});
it is not working, eventhough i tried to put the correct case on the name it is not functioning..
my question is, do i need to do something before i use the regex on my JS file?
THank you!
Because thename is a variable, use the RegExp object constructor to create a regex instance off the variable that you can then use in your query as:
var rgx = new RegExp("^"+ thename +"$", "i");
LoginUser.find({
"$or": [
{"firstname": rgx },
{"lastname": rgx }
]
}, callback);
can try it with $options:'i"
LoginUser.find({
$or: [
{'firstname': {$options:'i', $regex: 'PIa'}},
{'lastname': {$options:'i', $regex: 'NAtUrE'}}
]
})
or:
LoginUser.find({
$or: [
{'firstname': {$regex: /PIa/i}},
{'lastname': {$regex: /NAtUrE/i}}
]
})
also read docs: https://docs.mongodb.com/manual/reference/operator/query/regex/
it has some nice features like: $nin, $options: 'six'

How to get typeahead JS working with my json file

I would like to make a simple autocomplete with Typeahead JS but i cant make it work. I followed the instructions in the manual but I am not sure what I am doing wrong here. I cant get the right value out of the json file. Its an array with objects, and I just want the country names. Shouldnt be that hard I think. I doesnt display anything. Please help!
You can find the typeahead js files at "Getting Started" on the Typeahead Github page.
This is my code:
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="typeahead.jquery.min.js"></script>
<script src="bloodhound.min.js"></script>
</head>
<body>
<div id="prefetch">
<input class="typeahead" type="text" placeholder="Countries">
</div>
<script>
var countries = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 4,
prefetch: {
url: 'countries.json',
}
});
countries.clearPrefetchCache();
countries.initialize();
$('#prefetch .typeahead').typeahead(null, {
name: 'countries',
displayKey: 'country',
source: countries.ttAdapter(),
});
</script>
</body>`
Json file (countries.json):
[
{
"country": "Holland",
"city": "Amsterdam"
},
{
"country": "Belgium",
"city": "Brussel"
},
{
"country": "Germany",
"city": "Berlin"
},
{
"country": "France",
"city": "Paris"
}
]
Your datumTokenizer is not configured correctly. It should look like this.
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country'),
Here is a demo
I know the question is old but I hope this helps.
Another easy-way, it helped me, if your json is like this...
var data = [
{"stateCode": "CA", "stateName": "California"},
{"stateCode": "AZ", "stateName": "Arizona"},
{"stateCode": "NY", "stateName": "New York"},
{"stateCode": "NV", "stateName": "Nevada"},
{"stateCode": "OH", "stateName": "Ohio"}
];
$('#states').typeahead({
name: 'states',
limit: 10,
minLength: 1,
source: function (query, process) {
states = [];
map = {};
$.each(data, function (i, state) {
map[state.stateName] = state;
states.push(state.stateName);
});
process(states);
}
});

Ember 1.10+grunt+EAK: "Could not find <template_name> template or view" after migration from 1.9.1

I'm using Ember App Kit with grunt and I'm trying to switch to Ember 1.10 and can't get HTMLBars working :/
TL;DR
After migration, I've got my HTMLBars templates lodaded in Ember.TEMPLATES but they're not visible either by Ember nor in App.__container.lookup.cache.
Details
The steps I did:
updated ember and ember-data
updated package.json ("grunt-ember-templates": "0.5.0")
updated my Gruntfile.js (grunt.loadNpmTasks('grunt-ember-templates') added a task emberTemplates)
passed the options to emberTemplates:
{
debug: [],
options: {
templateCompilerPath: 'vendor/ember/ember-template-compiler.js',
handlebarsPath: 'vendor/handlebars/handlebars.js',
templateNamespace: 'HTMLBars'
},
'public/assets/templates.js': [
'app/templates/**/*.hbs'
],
};
removed handlebars.js from index.html and replaced ember.js with ember.debug.js
Now, I've got my public/assets/templates.js file generated in a proper way, I had several compilation errors coming from ember-template-compiler, so this part, I assume, is working fine.
Lastly, in the app, I can see all my templates loaded in Ember.TEMPLATES variable but unfortunately, they're not accessible from App.__container__.lookup.cache or App.__container__.lookup('template:<template_name>').
The way I'm trying to render the template that throws an error is (and it's working with Ember 1.9):
export default AuthRoute.extend({
renderTemplate: function() {
this.render();
this.render('user-details', {
into: 'base',
outlet: 'profile',
controller: 'user-details'
});
}
});
What am I missing? Any help would be appreciated.
Bonus question: what is debug field in emberTemplates configuration? If I don't define it, it raises an error (Required config property "emberTemplates.debug" missing.) while compiling. Could that be a possible reason?
Bonus question 2: where should templates.js file go? The intuition tells me /tmp but then, even Ember.TEMPLATES is an empty object...
EDIT [SOLUTION]:
I missed templateBasePath: "app/templates" line in the emberTemplates options. Because of that, Ember.TEMPLATES object was sth similar to this:
{
"app/templates/base.hbs": {},
"app/templates/components/component.hbs": {}
}
instead of:
{
"base.hbs": {},
"components/component.hbs": {}
}
which is the format that Ember resolver (ember-application/system/resolver) in the resolveTemplate method expects.
EDIT: using grunt-ember-templates and this Gruntfile task, I got it working:
emberTemplates: {
options: {
precompile: true,
templateBasePath: "templates",
handlebarsPath: "node_modules/handlebars/dist/handlebars.js",
templateCompilerPath: "bower_components/ember/ember-template-compiler.js"
},
"dist/js/templates.js": ["templates/**/*.hbs"]
}
Differences seem to be precompile: true and point the handlebarsPath to the dependency in node_modules. Also the templateBasePath makes the ids like application instead of templates/application. Or in your case app/templates/application.
To answer your Bonus question 2, put templates.js after you load ember.js but before your app.js. Mine script includes look like this:
<script type="text/javascript" src="/bower_components/ember/ember.debug.js"></script>
<script type="text/javascript" src="/bower_components/ember/ember-template-compiler.js"></script>
<script type="text/javascript" src="/js/templates.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
====================================
EDIT: Ignore this newbness...
It seems like the grunt-ember-templates task is outdated, or its dependencies are outdated. Remove it. I was able to hack together this solution:
Use grunt-contrib-concat instead. The money is with the process option.
concat: {
dist: {
// other concat tasks...
},
templates: {
options: {
banner: '',
process: function(src, filepath) {
var name = filepath.replace('app/templates/','').replace('.hbs','');
var Map = {
10: "n",
13: "r",
39: "'",
34: '"',
92: "\\"
};
src = '"' + src.replace(/[\n\r\"\\]/g, function(m) {
return "\\" + Map[m.charCodeAt(0)]
}) + '"';
return 'Ember.TEMPLATES["'+name+'"] = Ember.HTMLBars.template(Ember.HTMLBars.compile('+src+'));\n';
}
},
files: {
'public/assets/templates.js': 'app/templates/**/*.hbs'
}
}
},
So the whole solution is as follows:
module.exports = {
debug: {
src: "app/templates/**/*.{hbs,hjs,handlebars}",
dest: "tmp/result/assets/templates.js"
},
dist: {
src: "<%= emberTemplates.debug.src %>",
dest: "<%= emberTemplates.debug.dest %>"
},
options: {
templateCompilerPath: 'vendor/ember/ember-template-compiler.js',
handlebarsPath: 'vendor/handlebars/handlebars.js',
templateNamespace: 'HTMLBars',
templateBasePath: "app/templates"
}
};
where all my templates reside in app/templates/ directory.
I'm still using:
<script src="/assets/templates.js"></script>
in index.html.
Maybe somebody will find it useful ;)

Structuring large javascript code using RequireJS

Am very new to RequireJS here and trying to learn how to adopt to the structure. As of now, I've managed to create a structure as following
above image shows the structure of my code. Where by the folder "my" is supposed to contain all my modules, I plan to write inside each module its own models.js, views.js to be used later on by backbone.js
At this point I have couple questions as following
Can anyone by looking at the structure tell if its a good idea or if I should reconsider?
The second question is have is related to how I should manage conditionally loading my modules. Below is my config.js file
require([
"jquery",
"libs/jquery-ui/js/jquery-ui-1.9.0.custom.min",
"libs/bootstrap/js/bootstrap.min",
"my/base/module",
"my/vehicle/module"],
function($, ui, bootstrap, base, vehicle) {
//plugins have been loaded.
base.initialize();
vehicle.initialize();
});
am still not sure how to load module vehicle when am browsing or load module accounts when am browsing accounts. The backend is developed using django, I could create several config.js files for each module but am not sure if this is the correct approach or not.
This is how I setup RequireJS with JQuery within Python Django framework.
In base top level baset_site.html I have the following require.js config code between "head" tags:
<script>
requirejs.config({
baseUrl: "{% static '' %}",
paths: {
jquery: './js/jslibs/jquery-1.9.1',
jqm: './js/jslibs/jquery.mobile-1.4.0',
ajax_redirect: './js/ajax_redirect',
make_filt_sel: './app_namespace/js/make_filt_sel'
},
shim: {
"jquery": {
exports: '$',
},
"jqm": {
deps: ['jquery'],
exports: '$.mobile'
},
"make_filt_sel": {
deps: ['jquery', 'jqm'],
exports: 'make_filt_sel'
}
}
});
</script>
{% block header_scripts %}{% endblock header_scripts %}
Here's my ajax_redirect.js
/*
JQuery Ajax typically does not redirect in Django. Need middleware to
setup "class AjaxRedirect(object):" to fix redirection.
Reference:
http://hunterford.me/how-to-handle-http-redirects-with-jquery-and-django/
*/
(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( ['jquery'], function () {
factory();
});
} else {
// Browser globals
factory();
}
}( this, document, function ( ) {
$(document).ajaxComplete(function(e, xhr, settings){
if (xhr.status == 278){
window.location.href =
xhr.getResponseHeader("Location")
.replace(/\?.*$/, "?next="+window.location.pathname);
}
});
}));
Then I typically setup "block header_scripts" in the inherited templates as follows:
{% block header_scripts %}
{{ block.super }}
<script>
if ( typeof define === "function" && define.amd ) {
// AMD {# Configure requirejs.config in base_site.html #}
require(["./app_namespace/js/module_namespace/js_module"]);
} else {
// No AMD
$.ajax({
async:false,
type:'GET',
url: "{% static "app_namespace/js/make_filt_sel.js" %}",
data:null,
dataType:'script'
});
$.ajax({
async:false,
type:'GET',
url: "{% static "app_namespace/js/module_namespace/js_module.js" %}",
data:null,
dataType:'script'
});
}
</script>
{% endblock header_scripts %}
Here's an example of setting up a js_module.js with dependencies:
(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( ['jquery', 'jqm', 'ajax_redirect', 'make_filt_sel'], function () {
factory();
});
} else {
// Browser globals
factory();
}
}( this, document, function ( ) {
// A bunch of code
$.mobile.document.on( "pagebeforecreate", function(e){
// a bunch of code
// Shorthand for $( document ).ready()
$(function(){
// a bunch of code
}); // end of $( document ).ready()
}); // end of $(document).on( "pagebeforecreate",
})); // end of (function ( root, doc, factory )
The essence of requireJS is modularization . IF you are loading any scripts , you should put path configs into the rquireJS config section. However if you are want conditional use /loading of files . Then you have to wrap your code around define module . somewhat like this
require.config({
paths:
{
jquery: 'libs/jquery/jquery-1.7.2.min',
jqueryui: 'libs/jquery/jquery-ui-1.8.20.min',
bootstrap: 'libs/bootstrap/bootstrap.min',
},
shim: {
'underscore': {
exports: '_'
},
'bootstrap': {
deps: ['jquery'],
exports: 'jquery'
}
}
});
require(['app/jquery.app','jquery.bootstrap'], function (AppRouter) {
var app_view = new AppRouter;
}
Your app/jquery.app should be your starting point of your application.
You have to write this into main.js file and call it like this
<script data-main="/Scripts/main" src="/Scripts/libs/require/require.js" type="text/javascript"></script>
and your jquery.app which is your starting point should look like this
define(['jquery','my/base/module','my/vehicle/module']],
//plugins have been loaded.
base.initialize();
vehicle.initialize();
});
Note that in define module I havent defined anything to be loaded for jquery ui and bootstrap . The reason is since jquery ui loads of its own and it uses jquery syntax . And bootstrap file actually depends on jquery . So use the shim config to load bootstrap.min.js. Basically Your config and starting point should define the paths + starting point . So thats how make it .

jqgrid with JSON input rendering empty

I'm trying to generate a jqgrid which populates from a JSON feed, being output from a django backend.
The python handling the request is as follows:
from django.http import HttpResponse
from django.utils import simplejson
def json_test(request):
results = {'total':'1',
'page':'1',
'records':'2',
'rows':[{'id':'1','field1':'blah','field2':'bleh'},
{'id':'2','field1':'bloo','field2':'blum'}]}
json = simplejson.dumps(results)
return HttpResponse(json, mimetype='application/json')
So going to http://127.0.0.1:8000/json_test/ returns the following:
{"records": "2", "total": "1", "rows": [{"field2": "bleh", "field1": "blah", "id": "1"}, {"field2": "blum", "field1": "bloo", "id": "2"}], "page": "1"}
The jquery code is as follows:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url:'http://127.0.0.1:8000/json_test/',
datatype: 'json',
mtype: 'GET',
colNames:['field1','field2'],
colModel :[
{name:'field1', width:55},
{name:'field2', width:90},
],
pager: '#pager',
rowNum:10,
rowList:[10,20],
sortname: 'field1',
sortorder: 'desc',
viewrecords: true,
caption: 'Test Grid'
});
});
</script>
On loading the page, the grid renders correctly, and it briefly displays 'loading data', but it then displays no rows.
Any ideas where I've gone wrong? I've tried to strip this back to as simple a case as possible to determine the cause.
According to the jqGrid Documentation, by default the grid expects JSON data in the following format:
{
total: "xxx",
page: "yyy",
records: "zzz",
rows : [
{id:"1", cell:["cell11", "cell12", "cell13"]},
{id:"2", cell:["cell21", "cell22", "cell23"]},
...
]
}
So basically it looks like you need to set an ID for each of your columns. If this is not feasible you would need to specify your own jsonReader.
Additionally, having your total/page/records sections out-of-order might cause problems - if you still have trouble after adding the ID's then this would be the next thing to look at.
Solved - I put the html page inside the django app, so that the jqgrid url became just url:'/json_test/' and then it worked. Must be something harcoded into jqgrid that only permits local urls?
try this...
loadError: function(xhr,status,error){alert(status+" "+error);}