Get request doesn't display value in HTML document - javascript

I think this is my stupidity and the problem is really slight but it just doesn't display anything after get request. I have no errors and I am getting return call 200. So everything in request seems to be fine.
if('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(function(position){
loadWeather(position.coords.latitude + ',' + position.coords.longitude);
});
} else {
loadWeather('Berlin, DE', '');
}
function loadWeather(location, woeid) {
$.simpleWeather ({
location: location,
woeid: woeid,
unit: 'c',
succes: function(weather) {
city = weather.city;
temp = weather.temp + '°';
wcode = '<img class="weathericon" src="assets/weatherimg' + weather.code + '.svg">';
wind = '<p>' + weather.wind.speed + '</p><p>' + weather.units.speed + '<p>';
humidity = weather.humidity + ' %';
$('.location').text(city);
$('.temperature').html(temp);
$('.climate_bg').html(wcode);
$('.windspeed').html(wind);
$('.humidity').text(humidity);
},
error: function(error) {
$('.error').html('<p>' + error + '</p>');
}
});
};
$(document).ready(function() {
loadWeather();
});
This is my html code.
<section>
<div class='mainContentHeader'>
<h2> Weather App </h2>
</div>
<div class='mainContent'>
<div class='container'>
<p class='location'></p>
<p class='temperature'></p>
<div class='climate_bg'>
</div>
<div class='info_bg'>
<img class='dropicon' src='/assets/Droplet.svg'>
<p class='humidity'></p>
<img class='windicon' src='/assets/Wind.svg'>
<div class='windspeed'></div>
</div>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js'> </script>

Related

Outsourcing jQuery request on solr in external javascript

I am trying to outsource my inline javascript into an external one. The inline code looks like this and it works fine.
<script type="text/javascript">
$.getJSON('../servlets/solr/select?q=mods.genre:issue_a&state:published&rows=1&
fl=returnId,id,search_result_link_text,parentLinkText,mods.title&sort=modified
desc&wt=json',
function (data) {
$(data.response.docs).each(function(i, doc){
let ausgabe = "Ausgabe: ";
let titelmain = doc['search_result_link_text'];
let titelall = doc['mods.title'];
for (let i=0, item; item=titelall[i]; i++) {
if (item.indexOf(titelmain)>=0) {
titelall.splice(i,1);
}
}
let titel = titelall.join(' ' + '|' + ' ');
$('#periodicals').append($('<div class="modified"></div>')
.append('<p class="lastmod-p interline text-content">' +
'<span class="fa fa-arrow-right text-info" />' + ' ' +
'<span style="font-weight:bold">' + (doc['parentLinkText']) +
'</span>' + '<br/>' + '<a class="navbar-link" style="font-weight:bold" href="../receive/'+doc['returnId']+'">' + doc['search_result_link_text'] + '</a>' + '<br/>' + titel + '</p>' + '<p/>')
);
});
});
</script>
The external javascript (new.js) looks like this.
It is stored inside the same folder as the html (index.html) invoking it.
$(document).ready(function(){
jQuery.getJSON('http://localhost:8282/mir/servlets/solr/select?q=mods.genre:journal&state:published&rows=2&fl=id,search_result_link_text,mods.title,mods.title.main,sb_amt,sb_ort&sort=modified desc&wt=json',
function (data) {
$(data.response.docs).each(function(i, doc){
let amt = doc['sb_amt'] ? doc['sb_amt'] : ' ';
let ort = doc['sb_ort'] ? doc['sb_ort'] : ' ';
let alletitel = doc['mods.title'];
let titel = alletitel.slice(1);
titel = titel.join(' ' + '|' + ' ');
let meta = [titel,amt,ort];
let text = meta.join(' ' + '|' + ' ');
$('#periodicals').append($('<div class="modified"></div>')
.append('<p class="lastmod-p interline text-content">' +
'<a class="navbar-link" style="font-weight:bold" href="../receive/'+doc['id']+'">' + doc['search_result_link_text'] + '</a>' + '<br/>' + text + '</p>')
);
});
});
alert('New Documents');
});
I added alert to be sure that the external javascript is beeing resolved.
The alert text pops up correctly but there is no data displayed.
In my HTML Code I have this:
<script src="new.js"></script>
<div class="col-md-4">
<h4 class="text-dark font-weight-bold" style="">PERIODICALS</h4>
<div id="periodicals"></div>
<a style="vertical-align:top" href="../servlets/solr/select?q=mods.genre:journal&
state:published&sort=modified desc"></a>
</div>

Im getting "JavaScript critical error at line 692" in internet explorer

I have a problem in IE with my forEach, it is working in Google Chrome and Microsoft Edge but IE is giving me this error.
Code :
function jsFiltreleme(GelenDeger) {
$('#myDiv').html('');
var cnt = 1;
$.ajax({
type: 'GET',
url: '/Ajax/ContractedServiceAdd2?serviceName=' + GelenDeger.serviceName + '&&cityCode=' + GelenDeger.cityCode + '&&countryCode=' + GelenDeger.countryCode + '&&markCode=' + GelenDeger.markCode + '',
dataType: "json",
success: function (response) {
response.forEach(acente => { //Problem is Here line 692
const $div = $('<div></div>').addClass("well well-sm").attr('style', 'border-style:ridge;');
$div.html(`
<div class = "numberCircle"> ` + cnt++ + ` </div> <strong>Acente Adı : </strong> ` + acente.name + `<br>
<strong>Yetki :</strong> ` + acente.category + `<br>
<strong>Adresi : </strong> ` + acente.address + `<br>
<strong>Telefon :</strong> ` + acente.phone + `<br>
<a href=\"mailto:`+ acente.email + `\"><strong> >E-Mail Gönder</strong><br>
<a href=\"https://maps.google.com/maps?q= `+ acente.lat + "," + acente.lng + `\"><strong> >Yol tarifi al</strong>
`);
$("#myDiv").append($div);
});
if (response.length == 0) {
alert("Kayıt Bulunamadı");
}
},
});
}
The arrow function expression doesn't support IE browser, you could change your code as below:
response.forEach(function (acente) { //Problem is Here line 692
});
if (response.length == 0) {
alert("Kayıt Bulunamadı");
}
Edit:
not change this time is say javascript critical error at line 693
This issue is related to the code about the dynamically add html elements. You could build the DOMString first, then insert the string into a div container using the append method. Code like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">
</div>
<script>
var response= [your response array];
var cnt = 1;
response.forEach(function (acente) {
var textnode = document.createTextNode(acente);
document.getElementById("output").appendChild(textnode);
var newdiv = "<div class = 'well well-sm' style='border-style:ridge;'><div class = 'numberCircle'> " + cnt++ + " </div> <strong>Acente Adı : </strong> " + acente.name + "<br />" +
"<strong>Yetki :</strong> " + acente.category + "<br>" +
"<strong>Adresi : </strong> " + acente.address + "<br>" +
"<strong>Telefon :</strong> " + acente.phone + "<br>" +
"<a href='mailto:" + acente.email + "'><strong> >E-Mail Gönder</strong>" + "<br/>" +
"<a href='https://maps.google.com/maps?q= " + acente.lat + "," + acente.lng + "'><strong> >Yol tarifi al</strong>" +
"</div>"
$("#output").append(newdiv);
});
</script>

How to create a clone of Search field?

I have a search field in my app. I need to clone this search field with the same functions. One search field at the left side of the page and another, the same search field, at the right side of the page.
How I can make the clone using JS?
Below my JS code
document.querySelector('#city').addEventListener(click,'keyup', function(e) {
if (e.keyCode === 13) {
var city = $(this).val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
});
} else {
$("#error").html("<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>Field cannot be empty</div>");
}
};
});
function show(data) {
return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
"<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
"<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
"<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
"<h3><strong>Temperature</strong>: " + data.main.temp + "°C</h3>" +
"<h3><strong>Wind Direction</strong>: " + data.wind.deg + "°</h3>";
}
and part of HTML code
<body>
<div class="jumbotron" id="jumbo">
<h2 class="text-center" id="th2">Weather</h2>
</div>
<div class="container" id="cont">
<div class="row">
<h2 class="text-center text-primary">Your City</h2>
<span id="error"></span>
</div>
<div class="row form-group form-inline" id="rowDiv">
<input type="text" name="city" id="city" class="form-control" placeholder="City Name">
<button id="submitWeather" class="btn btn-primary">Search City</button>
</div>
<div id="show"></div>
</div>
As an option, I would suggest to create some function or class that creates input and description nodes and append to whatever container id (or class) you pass to it. In html you would only need element with rowDiv id. Obviously you can tailor it to your needs, but it's just an idea.
I thought something like this:
// rough example based of your code
class citySearch {
constructor(parentContainerId) {
this.searchField;
this.displayArea;
this.setStage(parentContainerId);
this.hookListener();
}
setStage(parentContainerId) {
this.searchField = document.createElement('input');
this.displayArea = document.createElement('div');
var parentContainer = document.getElementById(parentContainerId)
parentContainer.appendChild(this.searchField);
parentContainer.appendChild(this.displayArea);
}
show(data) {
return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
"<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
"<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
"<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
"<h3><strong>Temperature</strong>: " + data.main.temp + "°C</h3>" +
"<h3><strong>Wind Direction</strong>: " + data.wind.deg + "°</h3>";
}
hookListener() {
this.searchField.addEventListener('keypress', this.onClick.bind(this));
}
onClick(e) {
if (e.keyCode === 13) {
var city = this.searchField.value;
if (city !== '') {
fetch('http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=bb037310921af67f24ba53f2bad48b1d")
.then( async(res) => {
const data = await res.json();
var widget = this.show(data);
this.displayArea.innerHTML = widget;
this.searchField.value = '';
})
} else {
this.displayArea.innerHTML = "<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>Field cannot be empty</div>";
}
}
}
}
var firstSearch = new citySearch('rowDiv');
var secondSearch = new citySearch('rowDiv');
Html
<div class="row form-group form-inline" id="rowDiv"></div>
Here is some sample code that allows 1 code base, 2 search boxes and keeps the two search boxes in sync.
const searchBoxes = () => document.getElementsByClassName('searchbox');
document.addEventListener('DOMContentLoaded', function() {
Array.from(searchBoxes()).forEach(element => {
console.log(element.id);
element.addEventListener('keyup', function(event) {
let text = event.target.value;
// This is just a demo
document.getElementById("searchResult").innerHTML = text;
// Loop other search boxes
Array.from(searchBoxes()).forEach(e => {
if (e.id != event.target.id) e.value = text;
});
// ANY CODE HERE TO APPLY SEARCH
});
});
});
.searchbox {
border: 1px solid black;
background-color: wheat;
}
#searchResult {
height: 100px;
width: 100px;
background-color: yellow;
font-weight: bold;
}
<div>
<span>Some Text Here</span>
<input id="search1" class="searchbox" type="text" />
</div>
<div id="searchResult">ALL MY PAGE STUFF</div>
<div>
<span>Some Text Here</span>
<input id="search2" class="searchbox" type="text" />
</div>

Trying to reload page after clicking similar product

Im pulling items from a JSON file. I have a class called "showProduct" and once clicked it executes a function and shows the item information on the page. I am trying to call this same function again later in my code on the similar product. I need the page to refresh with that new items contents. Below is my code really hope someone can help me out im not sure what I am doing wrong. I did not include the JSON but i hope just by looking at the class and my code someone will know why it wont work.
function openNav() {
document.getElementById("productsSideBar").style.width = "250px";
}
function closeNav() {
document.getElementById("productsSideBar").style.width = "0";
}
'use strict';
$.ajax({
dataType: "jsonp",
url: '',
success: function(json){
//check for window hash and display appropriate product category
var currentHash = window.location.hash;
switch(currentHash)
{
case '#tomatoes':
displayTomatoes();
break;
default:
displayAll();
break;
}
//display all products function
function displayAll() {
var categoryImage = '';
$.each(json, function (i, item) {
if (item.itemBrandLetter == "C") {
categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">' + '' + '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">' + '<h3>' + item.itemName + '</h3>' + '' + '</div>';
}
});
$('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
//show individual product function on click
$(".showProduct").click(function(event){
//hide all current products
$('#productCategories').hide();
//get passed data from other function
var clickedItemName = '<h1>' + $(this).data('itemname') + '</h1>';
var clickedItemUPC = $(this).data('itemupc');
var clickedItemOZ = '<h2>' + $(this).data('itemoz') + '</h2>';
var clickedItemDescription = '<p>' + $(this).data('itemdescription') + '</p>';
var clickedItemImage = '<img class="img-responsive img-rounded center-block" src="' + $(this).data('itemimage') + '">';
var clickedItemGluten = $(this).data('itemgluten');
var clickedItemBPA = $(this).data('itembpa');
var clickedItemGMO = $(this).data('itemgmo');
var clickedItemPageURL = $(this).data('itempageurl');
//check if clicked data equals correct item
$.each(json, function (i, item) {
if (item.itemName === clickedItemName) {
clickedItemName
}
if (item.itemFullUPC === clickedItemUPC) {
clickedItemUPC
}
if (item.itemPackSize === clickedItemOZ) {
clickedItemOZ
}
if (item.itemDescription === clickedItemDescription) {
clickedItemDescription
}
if (item.imageURL === clickedItemImage) {
clickedItemImage
}
if (item.itemGlutenFree === clickedItemGluten) {
clickedItemGluten
}
if (item.itemBPAFree === clickedItemBPA) {
clickedItemBPA
}
if (item.itemGMOFree === clickedItemGMO) {
clickedItemGMO
}
//assign window hash to each product
if (item.itemName === clickedItemPageURL) {
event.preventDefault();
clickedItemPageURL = clickedItemPageURL.replace(/\s/g, '');
window.location.hash = clickedItemPageURL;
}
});
//remove extra characters from UPC
var originalUPC = clickedItemUPC;
var strippedUPC = '<h2>' + originalUPC.slice(1, -1); + '</h2>';
//show individual product information
$('#productSocialShare').show();
$('#individualProduct').show();
$('#relatedProducts').show();
//append product information to appropriate DIV
$('#productTitle').html(clickedItemName);
$('#productUPC').html(strippedUPC);
$('#productOZ').html(clickedItemOZ);
$('#productDescription').html(clickedItemDescription);
$('#productImage').html(clickedItemImage);
//check if gluten free is true and show image
if (clickedItemGluten == "Y") {
clickedItemGluten = '<img class="img-responsive img-rounded img-margin" src="../images/misc/gluten_free_test.jpg">';
$('#productGlutenFree').html(clickedItemGluten);
$('#productGlutenFree').show();
} else {
$('#productGlutenFree').hide();
}
//check if bpa free is true and show image
if (clickedItemBPA == "Y") {
clickedItemBPA = '<img class="img-responsive img-rounded img-margin" src="../images/misc/bpa_free_test.jpg">';
$('#productBPAFree').html(clickedItemBPA);
$('#productBPAFree').show();
} else {
$('#productBPAFree').hide();
}
//check if gmo free is true and show image
if (clickedItemGMO == "Y") {
clickedItemGMO = '<img class="img-responsive img-rounded img-margin" src="../images/misc/gmo_test.jpg">';
$('#productGMOFree').html(clickedItemGMO);
$('#productGMOFree').show();
} else {
$('#productGMOFree').hide();
}
//show random recipe for each item
var url = '';
$.getJSON(url, function(json) {
var randomRecipe = json[Math.floor(Math.random() * json.length)];
randomRecipe += '<div>' + '' + '<img class="img-responsive img-hover similarProductImagesCategory" src="' + randomRecipe.recipeImageCategoryURL + '">' + '' + '' + '<h3 class="similarProductSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>';
$('#featuredRecipe').append(randomRecipe);
});
//show similar products
var categoryItems = [];
$.each(json, function(i, item){
if(window.location.hash.indexOf('Tomatoes') >= 0) {
if(item.itemCommodity == '1120' && item.itemBrandLetter == "C") categoryItems.push(item);
}
if(window.location.hash.indexOf('Olive') >= 0) {
if(item.itemCommodity == '2120' && item.itemBrandLetter == "C") categoryItems.push(item);
}
});
var similarProduct= '';
$.each(json, function(i,item){
similarProduct = categoryItems[Math.floor(Math.random()*categoryItems.length)];
similarProduct += '<div>' + '' + '<h3 class="similarProductSubCategoryImgCaption">' + similarProduct.itemName + '</h3>' + '' + '</div>';
});
$('#productSimilar').append(similarProduct);
});
closeNav();
}
}
});
});
<section>
<div id="productsSideBar" class="sidenav">
×
<h3>View All</h3>
Tomatoes
Sauce
Olive Oil
Red Wine Vinegar
Balsamic Vinegar
Peppers
Artichokes
Olives
Beans
Capers & Pignoli Nuts
Specialties
Spices
Fish
Broth, Stocks & Soups
Breadcrumbs
Grated Cheese
</div>
</section>
<section id="productCategories">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<br>
<span class="expandSidebar" onclick="openNav()">☰ Categories</span>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div id="imagesCategoryProducts"></div>
</div>
</div>
</div>
</section>
<!-- Product Row Start -->
<section id="individualProduct">
<div class="container topmargin">
<div class="row">
<div class="col-md-7 col-sm-6">
<!-- Product Title Div -->
<div id="productTitle"></div>
<!-- Product UPC Div -->
<div class="displayInlineBlock" id="productUPC"></div>
<span class="displayInlineBlock"><h2>•</h2></span>
<!-- Product OZ Div -->
<div class="displayInlineBlock" id="productOZ"></div>
<span class="displayInlineBlock"><h2>•</h2></span>
<!-- Where to Buy Icon -->
<div class="displayInlineBlock"><h3><span rel="popover" data-content="View Product Availability"><span class="fa-stack"><i class="fa fa-square fa-stack-2x"></i><i class="fa fa-map-marker fa-stack-1x fa-inverse"></i></span></span></h3></div>
<hr>
<!-- Product Description Div -->
<div id="productDescription"></div>
<div class="row center">
<!-- Gluten Free Div -->
<div class="displayInlineBlock" id="productGlutenFree"></div>
<!-- BPA Free Div -->
<div class="displayInlineBlock" id="productBPAFree"></div>
<!-- GMO Div -->
<div class="displayInlineBlock" id="productGMOFree"></div>
</div>
</div>
<div class="col-md-5 col-sm-6">
<!-- Product Image Div -->
<div id="productImage"></div>
</div>
</div>
</div>
</section>
<!-- Product Row End -->
<section id="relatedProducts">
<div class="container topmargin">
<div class="row">
<div class="col-md-7">
<h1 class="center">Featured Recipe</h1>
<div id="featuredRecipe"></div>
</div>
<div class="col-md-5">
<h1 class="center">Similar Product</h1>
<br>
<div id="productSimilar"></div>
</div>
</div>
</div>
</section>
Ok, there are a lot of things that are wrong in the code but I am not going to into that right now. To do what you want to achieve is rather simple, you already got all the code you need, you just need to make some adjustments to make it work.
Step one. Bind the click events to the body instead of to the element.
$("body").on('click', ".showProduct", function(event){
That way, any element on the page with the class showProduct that is clicked will trigger the function, not just the elements that were bound to when the initial function ran.
The rest is really simple, you already have the similar product's information available, you just didn't put it in the data attributes when you created the element. Now obviously there are better ways of doing this... but here is how you would do it:
similarProduct = '<div>' +
'<a href="#" class="showProduct"' +
'data-itempageurl="' + similarProduct.itemFullUPC + '"' +
'data-itemgmo="' + similarProduct.itemGMOFree + '"' +
'data-itembpa="' + similarProduct.itemBPAFree + '"' +
'data-itemgluten="' + similarProduct.itemGlutenFree + '"' +
'data-itemlowsodium="' + similarProduct.itemLowSodium + '"' +
'data-itemorganic="' + similarProduct.itemOrganic + '"' +
'data-itemimage="' + similarProduct.imageURL + '"' +
'data-itemname="' + similarProduct.itemName + '"' +
'data-itemoz="' + similarProduct.itemPackSize + '"' +
'data-itemdescription="' + similarProduct.itemDescription + '"' +
'data-itemupc="' + similarProduct.itemFullUPC + '"' + '>' +
'<img class="img-responsive img-hover similarProductImagesCategory" src="' + similarProduct.imageURL + '">' +
'<h3 class="similarProductSubCategoryImgCaption">' + similarProduct.itemName +
'</h3>' + '</a>' + '</div>';
});
That should do it... now you will notice when you click on one of the similar products it should show you the information like you wanted, however it will add the new similar product to the already existing similar product list and this will keep on growing the more you click. I am sure you can figure out how to clear the list. If not just shout.
Here is the codepen: http://codepen.io/anon/pen/oYJpve
EDIT: As a side note... normally you want to store the json data with the product id as key. Then you only save the key inside the data attribute. On click you simply use the product id (key) to access the information in your stored object.
It is really easy to do. Just create a global variable
var product_data = {};
Then you populate the object when you get the data with a function. So on success of your ajax call you could have something like this:
product_data = json;
or even better you could have a function that changes the data into the structure you want:
product_data = restructureDataFunction(json);
Then you have a nice data set which you can pull from. If you need to make updates to the dataset you can do it in one place instead of in each element.
If you want, have a look at Angular 2, it should teach you a lot and also help you with future projects. It is really strong tool especially if you have html elements representing data.

How can I add a function call to my collapsible and display the function return into the collapsible textblock

I want to add this function
function list(){
var html=" "
for(var i =0; i<movements.length;i++){
html+=("<p>" + movements[i][0]+ " " + movements[i][1] + " " + movements[i][2] + "</p>")}
document.getElementById("listSpace").innerHTML = html;
}
to the click of the collapsible and display the return of list() into the textblock:
<div data-role="collapsible-set" id="myCollapsible">
<div data-role="collapsible" data-collapsed="true" >
<h3>
10 Last movements
</h3>
<div data-controltype="textblock">
<p>
<b id="listSpace">
10 last movements
</b>
</p>
</div>
</div>
</div>
Made a few changes to your code
function list() {
var html = " ", movements = [['10', 'next', 'movements'],['10', 'next', 'movements'],['10', 'next', 'movements']];
for (var i = 0; i < movements.length; i++) {
html += ("<p>" + movements[i][0] + " " + movements[i][1] + " " + movements[i][2] + "</p>")
}
document.getElementById("listSpace").innerHTML = html;
}
$(document).ready(function () {
$('div[data-role="collapsible"]').click(list);
});
check out the fiddle

Categories