get file contents from a url using jquery - javascript

Is there any way to get the city and state name from zip code from google api using jquery(not using ajax).
I can get the details from here http://maps.googleapis.com/maps/api/geocode/json?address=17078&sensor=true.
and my code is
var googleAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=17078&sensor=true";
$.getJSON(googleAPI, function (response) {
console.log("JSON Data: " + response.items);
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.text should have the HTML entities escaped.
//document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title;
alert(item.address_components);
}
});
but this is not working

You have to find the administrative_area_level_1 and administrative_area_level_2 which gives you the state and city names.
Read Geocoding docs
Try this,
<script>
// let you got the items.address_components
for(var a=0,len=items.address_components.length;a<len;a++)
{
ac=items.address_components[a];
if(ac.types)
{
for(var t=0,tl=ac.types.length;t<tl;t++)
{
ty=ac.types[t];
if(ty=='administrative_area_level_1')
{
alert('State'+ac.long_name);
}
if(ty=='administrative_area_level_2')
{
alert('City'+ac.long_name);
}
}
}
}
</script>

Related

Can't compare database query from flask to javascript variable

I have a flask-based site and I query the database in Flask and send that list of values to my html page. From there I have a script that compares a variable to an element in the list, but the case never works.
def start():
title = ""
paragraph = ["Cognitive Motor"]
pageType = 'start'
#if request.form.get("cognitiveAbility1" != None):
methodsQuery = db.engine.execute("select method from permutations")
motorQuery = db.engine.execute("select cognitivemotor from permutations")
motorList = motorQuery.fetchall()
data = request.stream.read()
methodList = methodsQuery.fetchall()
data2 = request.stream.read()
return render_template("start.html", title=title, paragraph=paragraph, pageType=pageType,data=data, methodList=methodList,motorList=motorList)
That is the code in flask, and below is the script I have in my html file.
The case if the if statement never works and won't print out the console.log("test").
<script>
$(document).ready(function() {
$(document).on('click', '.submitButton', function cognitiveFunction() {
var checkCog = document.getElementsByName("cognitive");
var checkMot = document.getElementsByName("motorCheck");
var resultCog = '';
var resultMot = '';
var motorQuery= "";
for(i = 0; i <3; i++) {
if(checkCog[i].checked === true) {
resultCog += checkCog[i].value + '';
console.log(resultCog);
}
}
for(i = 0; i <8; i++) {
if(checkMot[i].checked === true) {
resultMot += 'Yes';
}
else {
resultMot += 'No';
}
}
motorQuery = resultCog + resultMot ;
for(i = 0; i <19; i++) {
if ( '{{ motorList [i]}}' == motorQuery){
console.log('test');
$('body').append("{{ methodList [i] }}")
}
}
When I just print a value from the list of motorList into my html page manually, it looks like this,
(u'Cognitively intactNoNoYesNoYesNoYesYes',)
But in the database it is just
Cognitively intactNoNoYesNoYesNoYesYes
You have a basic misunderstanding of how JS and Flask interact. There is no possible way to put the JS variable i into the Jinja template variable '{{ motorList[i] }}, because Jinja is rendered on the server long before the JS runs on the client.
You will need to output the entire motorList in a format accessible to your script, ie JSON, and then iterate through that in JS.

How to do this the with Jquery instead of javascript

I've been trying to convert this section of script to jQuery instead of vanilla javascript, but I'm not sure how to loop through the elements with jQuery. Basically, I'm grabbing a data attr value from each field to be used as an error message that displays near the field.
This is all inside a click event on the submit button, FYI
What's the jQuery way?
//Set some variables
var invalidFields = $(form).querySelectorAll(':invalid'),
errorMessages = $(form).querySelectorAll('.error-message'),
parent;
// Remove any existing messages
for (var i = 0; i < errorMessages.length; i++) {
errorMessages[i].parentNode.removeChild(errorMessages[i]);
}
//Get custom messages from HTML data attribute for each invalid field
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
//Display custom messages
for (var i = 0; i < invalidFields.length; i++) {
parent = invalidFields[i].parentNode;
parent.insertAdjacentHTML('beforeend', '<div class='error-message'>' +
invalidFields[i].validationMessage +
"</div>");
}
I converted your code one-to-one to jQuery. But there might be other ways, when i will know where form, setCustomValidity and validationMessage is coming from.
var $form = $(form);
// Remove any existing messages
$(".error-message", $form).remove();
// Get custom messages from HTML data attribute for each invalid field
$(".sdForm-input", $form).each(function() {
var message = $(this).attr('data-ErrorMessage');
// i don't know where the 'setCustomValidity' function is coming from
// this is a custom function
$(this)[0].setCustomValidity(message);
});
// Display custom messages
$(":invalid", $form).each(function() {
// i don't know where 'validationMessage' is comig from
// this is a custom property
$(this).parent().append("<div class='error-message'>" + $(this)[0].validationMessage + "</div>");
});
You can simple replace this.
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
Replace with jQuery way
var fields = form.find('.sdForm-input');
$.each(fields, function(index, el){
var message = $(el).attr('data-ErrorMessage');
$(el).setCustomValidity(message);
});

Local JSON file Update

Hi trying to update the local JSON file with new input values.
Creating a posts app which is now working on local Json file.
I have a button and a text area, and a dynamic list.
once I add some input values in textarea and submit it should get appends to li and if I add another value then it should get append to another li.
What ever new values had added it should get append to the local json file.
Here is the code what I have tried.
HTML:
<ul class='Jsonlist'></ul>
<a id='postData' href='#'>Post</a>
<textarea id="tArea"></textarea>
JS:
var Json = {"three":["red","yellow","orange"]}
var items = [];
$.each( Json, function( key, val ) {
debugger;
items.push( "<li id='" + key + "'>" + Json.three + "</li>" );
});
$('.Jsonlist').append(items);
$('#postData').click(function(){
a=$('#tArea').val();
$(".Jsonlist li").append(a);
});
Working Demo
JS fiddle:
http://jsfiddle.net/JwCm9/
What's inside?
variable to hold the items
var items;
creates <ul> for items and for each item a <li>
function make_list() {
var list = $(".Jsonlist");
list.empty();
for (var i in items) {
var value = items[i];
var li = $('<li>');
li.html(value);
list.append(li);
}
};
saving and reading from local json from/into items
function save_to_local_json() {
var items_json = JSON.stringify(items);
localStorage.setItem('items', items_json);
};
function read_from_local_json() {
var items_json = localStorage.getItem('items');
items = JSON.parse(items_json);
// If the file is empty
if (!items) {
items = [];
}
};
first time calling to these functions:
read_from_local_json();
make_list();
on click event
$('#postData').click(function () {
var text = $('#tArea').val();
items.push(text);
make_list();
save_to_local_json();
});
updated my answer:
function update_json(json_data){
localStorage.setItem('json',JSON.stringify(json_data));
}
function fetch_json(){
var json_data_local = JSON.parse(localStorage.getItem('json'));
return json_data_local;
}
function display_list(json_data){
json_data.three.forEach(function(val,key) {
$('.Jsonlist').append("<li id='" + key + "'>" + val + "</li>");
});
}
console.log(localStorage.getItem('json'));
if(localStorage.getItem('json') == ""){
var Json = {"three":["red","yellow","orange"]}
update_json(Json);
}
var Json = fetch_json();
display_list(Json);
console.log(Json);
$('#postData').click(function(){
a=$('#tArea').val();
Json.three.push(a);
update_json(Json);
$('.Jsonlist li').remove();
display_list(fetch_json());
});

How to parse json into nested html list strucuture

I tried this with xml, but the behavior was odd from firefox to IE.
I haven't worked with json before, so any help would be appreciated.
here's my json:
{
"storeList":{
"state":[
{
"stateName":"Maine",
"store":[
{
"storeName":"Store 1",
"storeID":"store1",
"storeURL":"http:\/\/www.sitename.com"
},
{
"storeName":"Store 2",
"storeID":"store2",
"storeURL":"http:\/\/www.sitename.com"
},
{
"storeName":"Store 3",
"storeID":"store3",
"storeURL":"http:\/\/www.sitename.com"
}
]
},
{
"stateName":"Connecticut",
"store":[
{
"storeName":"Store 1",
"storeID":"store1",
"storeURL":"http:\/\/www.sitename.com"
}
]
}
]
}
}
and the structure I'm going for -
<div id="storeList">
<ul>
<li>
<h3>State Name 1</h3>
storename
storename
</li>
<li>
<h3>State Name 2</h3>
storename
</li>
</ul>
</div>
update
tried a solution below, loading the json from an external file, but I get an error that object is not defined:
$(document).ready(function() {
var object;
$.getJSON('xml/storeList.json', function(json) {
object = json;
});
$('#storeList').append('<ul/>')
$.each(object.storeList.state, function() {
var list = $('#storeList ul'),
listItem = $('<li/>'),
html = listItem.append($('<h3/>').text(this.stateName));
$.each(this.store, function() {
listItem.append($('<a />').attr('href', this.storeURL).text(this.storeName));
});
list.append(html)
});
});
I would use a template engine. With a template engine you can define your template (which is easy to read and maintain) like that:
<script id="template" type="text/x-jquery-tmpl">
<ul>
{{#each state}}
<li>
<h3>{{=stateName}}</h3>
{{#each store}}
{{=storeName}}
{{/each}}
</li>
{{/each}}
</ul>
</script>
and then simply call
$("#storeList").html(
$("#template").render(json.storeList)
);
to fill your div
<div id="storeList"></div>
I have a demo ready. The template engine I use here is JsRender.
Here's a simple example:
$('#storeList').append('<ul/>')
$.each(object.storeList.state, function() {
var list = $('#storeList ul'),
listItem = $('<li/>'),
html = listItem.append($('<h3/>').text(this.stateName));
$.each(this.store, function() {
listItem.append($('<a />').attr('href', this.storeURL).text(this.storeName));
});
list.append(html)
});
Example
EDIT
var object;
$.getJSON('xml/storeList.json', function(json) {
object = json;
$('#storeList').append('<ul/>')
$.each(object.storeList.state, function() {
var list = $('#storeList ul'),
listItem = $('<li/>'),
html = listItem.append($('<h3/>').text(this.stateName));
$.each(this.store, function() {
listItem.append($('<a />').attr('href', this.storeURL).text(this.storeName));
});
list.append(html)
});
});
JSON is nothing but a subset of Javascript object literal notation that allows nested objects and/or arrays, so you will want to study up on the Javascript object and array data structures.
That being said, once your "bare" json is assigned to a variable, let's assume "json" (test by prepending with "json=") you can probably begin to work with your JSON in the following manner, just as you would with an array:
for (var i=0, n=json.storeList.state.length; i<n; i++) {
var state = json.storeList.state[i];
console.log(state.stateName); //Maine, then Connecticut
for (var j=0, k=state.store.length; j<k; j++) {
var store = state.store[j]; //the object containing store name, id & URL
console.log(store.storeID);
}
}
PS....my answer is "pure" Javascript as opposed to using jQuery, so if you're committed to doing things the jQuery way, definitely consider the other answers. But it's good to get familiar with the Javascript foundation behind the various frameworks such as jQuery, ExtJS, etcetera, in case you ever have to switch.
Use jQuery's $.each() function to iterate over object properties, and just a standard for loop for iterating over the arrays.
Here's a working example: http://jsfiddle.net/qZ6U4/
And the code:
var htmlStr = '';
$.each(myObj, function(i,v){
htmlStr += '<div id="' + i + '">';
$.each(v, function(i, v){
htmlStr += '<ul>';
for(var i = 0; i < v.length; i++){
htmlStr += '<li><h3>' + v[i].stateName + '</h3>';
for(var n = 0; n < v[i].store.length; n++){
var store = v[i].store[n];
htmlStr += '' + store.storeName + '';
}
htmlStr += '</li>';
}
htmlStr += '</ul>';
});
htmlStr += '</div>';
});

Convert JSON to a Multilevel Bulleted List Using JS

Can some one help me make the following JSON data:
{
"main": {
"label":"Main",
"url":"#main"
},
"project": {
"label":"Project",
"url":"#project"
},
"settings": {
"label":"Settings",
"url":"#settings",
"subnav":[
{
"label":"Privacy",
"url":"#privacy"
},
{
"label":"Security",
"url":"#security"
},
{
"label":"Advanced",
"url":"#advanced"
}
]
}
}
into the following bullets list using JS? Assuming you don't know what the first nodes are call labeled (e.g. "main", "project" <- these will be dynamically generated):
Main (#main)
Project (#project)
Settings (#settings)
Privacy (#privacy)
Security (#security)
Advanced (#advanced)
Thanks
Let's not use HTML string-hacking, shall we? That would break as soon as any of the data had characters like < or & in (or " in attribute values). Use DOM methods and you don't have to worry about character escaping:
function createNav(navs) {
var ul= document.createElement('ul');
for (name in navs) {
var nav= navs[name];
var a= document.createElement('a');
a.href= nav.url;
a.appendChild(document.createTextNode(nav.label));
var li= document.createElement('li');
li.id= 'nav-'+name;
li.appendChild(a)
if ('subnav' in nav)
li.appendChild(createNav(nav.subnav));
ul.appendChild(li);
}
return ul;
}
document.getElementById('navcontainer').appendChild(createNav(jsondata));
Most JS frameworks offer shortcuts to make this a bit less wordy. For example with jQuery:
function createNav(navs) {
var ul= $('<ul>');
for (name in navs) {
var nav= navs[name];
var li= $('<li>', {id: name});
li.append($('<a>', {href: nav.url, text: nav.label}));
if ('subnav' in nav)
li.append(createNav(nav.subnav));
ul.append(li);
}
}
$('#navcontainer').append(createNav(jsondata));
Note that either way, you're using an Object literal which means you get no control over the order the list of navs comes out. You have no guarantee that main will be above project. If you want a defined order, you will have to have the returned JSON data be an array.
My code is on JSfiddle.
As JSON parser I used this one.
The main code is a recursive renderer of the parsed JSON:
function recursive_parse(result) {
var html = '<ul>';
for (var k in result) {
html = html + '<li>' + result[k].label + ' (' + result[k].url + ')';
html = html + recursive_parse(result[k].subnav);
html = html + '</li>';
}
html = html + '</ul>';
return html;
}
var result = json_parse($("div#test1111").html());
var html = recursive_parse(result);
$("div#test2222").html(html);

Categories