How do I automatically clear/reset the page upon next search? - javascript

I'm working on a simple program which displays the weather conditions of queried/searched places. All is well, though I'd like to know how to automatically reset/clear the DOM (or at least the relevant section displaying the results) and populate it with results of the new search. At the moment, it appends the results unless I clear them manually (clear button).
Rather than copy/paste the all the codes (HTML/CSS/JS-jQuery), I preferred having them at JSBin. So here is a link to the 'app', and thus the rest of the codes (HTML and CSS).
JS/jQuery Code
$(function() {
function showWeather() {
let $title = $("#station"),
$description = $("#description"),
$temperature = $("#temp"),
$chill = $("#chill"),
$wind = $("#wind"),
$humidity = $("#humidity"),
$units = $(".units").text(),
$apiPath1 = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22",
$query = $('input#city').val(),
$apiPath2 = "%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
$url = $apiPath1 + $query + $apiPath2;
$("input#city").val("");
$.ajax({
type: "GET",
url: $url,
success: function(data) {
$title.append(`
<h3>${data.query.results.channel.item.title}</h3>
`)
$description.append(`
<p>${data.query.results.channel.item.condition.text}</p>
`)
$temperature.append(`
<h1><span id="temp1">${data.query.results.channel.item.condition.temp}</span> °<span class="units">F</span></h1>
`)
$chill.append(`
<p>Feels like: <span id="temp2">${data.query.results.channel.wind.chill}</span> °<span class="units">F</span></p>
`)
$wind.append(`
<p>Wind speed: ${data.query.results.channel.wind.direction} km/h; Wind direction: ${data.query.results.channel.wind.speed}</p>
`)
$humidity.append(`
<p>Humidity: ${data.query.results.channel.atmosphere.humidity} %</p>
`)
}
});
}
//Converting Fahrenheit to Celsius
function fahrToCels(F) {
return Math.round((5/9) * (F - 32));
}
//Converting Celsius to back to Fahrenheit
function celsToFahr(C) {
return Math.round((C * 9/5 + 32));
}
$("#submit").on("click", function() {
showWeather();
});
$("input#city").on("keypress", function(event) {
if (event.which === 13) {
showWeather();
}
});
$('#clear').on('click', function (event) {
event.preventDefault();
$('#station, #description, #temp, #chill, #wind, #humidity').empty('');
});
$("#tempUnits").on("click", function() {
let temp1 = Number($("#temp1").text());
temp2 = Number($("#temp2").text());
if ($(".units").html() === "C") {
$(this).html("Temperature in Celsius")
$("#temp1").html(celsToFahr(temp1));
$("#temp2").html(celsToFahr(temp2));
$(".units").html("F");
}
else {
$(this).html("Temperature in Fahrenheit")
$("#temp1").html(fahrToCels(temp1));
$("#temp2").html(fahrToCels(temp2));
$(".units").html("C");
}
});
});
Cheers!

Try using html instead of append
$.ajax({
type: "GET",
url: $url,
success: function(data) {
$title.html(`
<h3>${data.query.results.channel.item.title}</h3>
`)
$description.html(`
<p>${data.query.results.channel.item.condition.text}</p>
`)
$temperature.html(`
<h1><span id="temp1">${data.query.results.channel.item.condition.temp}</span> °<span class="units">F</span></h1>
`)
$chill.html(`
<p>Feels like: <span id="temp2">${data.query.results.channel.wind.chill}</span> °<span class="units">F</span></p>
`)
$wind.html(`
<p>Wind speed: ${data.query.results.channel.wind.direction} km/h; Wind direction: ${data.query.results.channel.wind.speed}</p>
`)
$humidity.html(`
<p>Humidity: ${data.query.results.channel.atmosphere.humidity} %</p>
`)
}
});

Use
$title.html('<h3>${data.query.results.channel.item.title}</h3>')
instead of
$title.html('<h3>${data.query.results.channel.item.title}</h3>')
Replace other $.append(content) with $.html(htmlString)

Related

Ajax passing value to PHP

I would like to pass multiple values to php via ajax (on same page), here's my code:
HTML (user_list.php):
<button type="submit" class="button button-block savebutton" name="save_changes"/>
Save changes</button>
Javascript (user_list.php):
$(".savebutton").on("click", function (event) {
event.preventDefault();
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
return false;
});
PHP (user_list.php):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['delete_selected'])) { // Button to delete selected user(s)
if (!empty($_POST['check_list'])) {
foreach ($_POST['check_list'] as $id) {
$sql = "DELETE FROM users WHERE id=$id";
$mysqli->query($sql);
header("Refresh:0"); //Refresh page
}
}
}
// Other if above works fine
elseif (isset($_POST['result'])){
// I want to get the js array with the values here after ajax
}
else {
// But I get here, and I don't get the js array
}
}
So I have 2 problems, the first is that I pass the elseif, and the second is that I dont get the array. I think the problem is with ajax, since filling the array works properly
EDIT: I moved the php to a different page, now it's working.
Though your Ajax request is initiated, a "normal" submit request is also started, when you press the button. To prevent the second request (thus keeping only the Ajax request), you have to return false; at the end of your onclick callback.
Solution #1:
$(".savebutton").on("click", function () {
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
return false;
});
Solution #2 (as also suggested by #charlietfl):
$(".savebutton").on("click", function (event) {
event.preventDefault();
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
});
It seems that when you're submitting the POST request, the data is coming as their own POST fields. Simply check for the values of what you submitted. For example, if you had done the same, but put foo as bar and hello as world, you could check for foo and hello with something like this:
elseif (isset($_POST['foo'], $_POST['hello']) {
# your code
}
$('.savebutton').click(function (e) {
e.preventDefault()
var js = []
var i = 0
$('select').each(function (i) {
var a = {}
a.id = $(this).val()
a.permission = $(this).children(':selected').text()
js.push(a)
alert(js[i].permission + ' - ' + js[i].id)
})
js = JSON.stringify(js)
$.post('user_list.php', {result: js}
})
Try with this
<button type="submit" class="button button-block savebutton" name="save_changes[]"/>Save changes</button>

JQuery Ajax returns Source code

I'm using JQuery Ajax on my website. I've tested it on our test server it worked perfectly, but when I tried to put it on our productive server the Ajax just returns the source code of the website itself.
JS File:
$(document).ready(function () {
$('#sshin').keyup(function () {
var query = $(this).val();
console.log(query);
if (query != '') {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function (data) {
console.log(data);
}
});
}
});
$(document).on('click', 'article', function () {
var text = $('#sshin').val();
text = text.substring(0, text.lastIndexOf(',') + 1);
text += $(this).text();
var uniq = text.match(/\b\w+\b/g).filter(function (el, idx, a) {
return idx === a.lastIndexOf(el);
});
text = uniq.join(',');
$('#sshin').val(text);
$('#sshout').fadeOut();
});
});
PHP File:
<?php
if(isset($_POST["query"])){
$query = $_POST["query"];
return '<ul><li>1</li><li>2</li></ul>';
}
?>
Any idea why it returns something different than it should?
This method once worked for me, hope it might help. Let me know.
this->output->set_content_type('application/json');
return $this->output->set_output(json_encode('<ul><li>1</li><li>2</li></ul>'));

Using Jquery/SetTimeout to Update Div - Update Not Working

What I am Trying to Do:
I am trying to use settimeout to loop/run after a function is called to automatically update/refresh a div.
What Isn't Working:
To be clear settimeout is working, but the div is not automatically refreshing/updating when I enter new test data into the db. In other words, If I refresh the page, I see the new test data, but not if I let the update function run.
Code:
function update(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
console.log("Queried Database...");
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#login-box").hide();
//$("#trades").html(' ');
localStorage.setItem("wings_lastsignal", v.candel);
var lastsignal = localStorage.getItem("wings_lastsignal");
console.log(v.candel);
if(lastsignal == v.candel) {
console.log("No New Signals");
localStorage.getItem("wings_currentsignals");
if(v.signal == 'Buy') {
console.log("Current Buy Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowup"></span>'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'" onClick="var a = this.innerHTML; tsclick(a);" value="'+v.symbol+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
} else {
console.log("Current Sell Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowdown"></span>'+v.time+'<span style="color:#fb5350;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
}
} else {
playChing();
console.log("New Signal");
if(v.signal == 'Buy') {
console.log("Buy Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowup"></span>'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'" onClick="var a = this.innerHTML; tsclick(a);" value="'+v.symbol+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
} else {
console.log("Sell Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowdown"></span>'+v.time+'<span style="color:#fb5350;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
}
}
});
}
//alert(response);
//console.log(response);
}
}).then(function() { // on completion, restart
var a = localStorage.getItem("wingsaccnum");
//setTimeout(update, 10000);
setTimeout(function(){ update(a) }, 20000); // function refers to itself
console.log("Timeout");
});
}
This function is called when I a button is pressed, using this Jquery snippet:
$( "#rbuttonon" ).click(function() {
var acc = localStorage.getItem("wingsaccnum");
//refresh_box();
update(acc);
console.log('Interval set');
});
Other Notes:
To be clear, I don't mind if there is a way to always make sure this div is updated every xx amount of time, without the need to press any buttons. I believe the problem is in my code's logic, but I would greatly appreciate some assistance!

Nested $.getJSON() can not get correct answer? [duplicate]

This question already has answers here:
Calling an asynchronous function within a for loop in JavaScript
(10 answers)
Closed 6 years ago.
I am just learning Jquery from freecode.camp and I am writing some code to Use the Twitchtv JSON API ( https://www.freecodecamp.com/challenges/use-the-twitchtv-json-api).
When I want to get five channels logo on Twitch.tv ,but when I write the code ,I just found there was four same logo ,it was never what I want .
I have a codepen at http://codepen.io/zhangolve/pen/JKOXwW?editors=1111 ,if you like ,please check it out.
this is the JS code:
$("#click").on("click", function() {
var channel = ['OgamingSC2', 'FreeCodeCamp', 'terakilobyte', 'storbeck', 'RobotCaleb'];
for (var i = 0; i < channel.length; i++) {
var url = 'https://api.twitch.tv/kraken/streams/' + channel[i] + '?callback=?';
var thechannelurl = 'https://api.twitch.tv/kraken/channels/' + channel[i] + '?callback=?';
$.getJSON(url, function(data) {
if (data.stream == null) {
$.ajax({
dataType: "json",
url: thechannelurl,
//data: data,
type: "GET",
success: function(w) {
$("#content").append('<img src=' + w.logo + '> </img>')
}
});
} else {
var logo = data.stream.channel.logo;
//console.log(logo);
$("#content").append('<img src=' + logo + '></img>');
}
})
}
})
I forked your pen ...
Here is the code working:
http://codepen.io/rafaelcastrocouto/pen/rLYWXV
One channel in your list has no logo ... so I used a placeholder image.
var channelAPI = 'https://api.twitch.tv/kraken/';
var channels=['OgamingSC2',
'FreeCodeCamp',
'terakilobyte',
'storbeck',
'RobotCaleb'];
var getJSONCallback = function (data, url) {
if (data && data.logo) {console.log('1', data.logo)
appendLogo(data.logo);
} else if (data &&
data.stream &&
data.stream.channel &&
data.stream.channel.logo) {console.log('3', data.stream.channel.logo)
appendLogo(data.stream.channel.logo);
} else if (url && url.channel) {console.log('2', url.channel.toString())
$.getJSON(channelAPI+'channels/'+url.channel, getJSONCallback);
} else {
appendLogo('https://placeholdit.imgix.net/~text?txtsize=63&bg=FF6347&txtclr=ffffff&txt=No Logo Found&w=302&h=302');
}
};
var appendLogo = function (logo) {
$("#content").append('<img class="img" src="'+logo+'"></img>');
};
var clickFunction = function() {
for(var i=0;i<channels.length;i++) {
var channel = channels[i];
$.getJSON(channelAPI+'streams/'+channel, function (data) {
getJSONCallback(data, {channel: this});
}.bind(channel));
}
};
$("#click").on("click", clickFunction);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click" class="btn btn-primary" >click</button>
<div id="content"></div>

CouchDB document attachments via html form and jquery

I'm trying to create web form that, when submitted will create a couchdb document and add attachment(s) to the doc. I've seen from tutorials/other forums that it's necessary to do this with a two stage process (as futon does). I can get the document to upload, but can't seem to get the attachment to upload. I've tried a number of ways, currently I do something like:
html file with:
<!DOCTYPE HTML>
<html>
<head>
<title>Document submission</title>
<style type="TEXT/CSS" media="all">
</style>
</head>
<body>
<table>
<form id="form" name="form" action="">
<tr>
<td>Field</td>
<td><input type="text" required="required" name="field">
<span id="required">*</span></td>
</tr><tr>
</tr><tr>
<td></td><td><button type="button" id="submit">Select Attachment</button><td>
</tr>
</form>
</table>
</body>
<script src="/_utils/script/json2.js"></script>
<script src="/_utils/script/jquery.js"></script>
<script src="/_utils/script/jquery.couch.js"></script>
<script src="/_utils/script/jquery.form.js"></script>
<script src="/_utils/script/jquery.dialog.js"></script>
<script type="text/javascript" src="basic.js"></script>
</html>
and then a file called basic.js with:
function create_document(){
var db_name = 'uploader';
var db = $.couch.db(db_name);
var data={}
data['fname']=document.form.field.value;
db.saveDoc(data, {
success: function (data) {
add_attachment(db,data);
},
error: function () {
alert("Cannot save the thread.");
}
});
}
function add_attachment(db,data){
var docID = data.id;
var dbName = db.name;
var form = $("#upload-form");
$.showDialog("dialogue.html", {
load: function(elem) {
$("input[name='_rev']", elem).val(data._rev);
},
submit: function(data, callback) {
if (!data._attachments || data._attachments.length == 0) {
callback({_attachments: "Please select a file to upload."});
return;
}
var form = $("#upload-form");
form.find("#progress").css("visibility", "visible");
form.ajaxSubmit({
url: db.uri + $.couch.encodeDocId(docID),
success: function(resp) {
form.find("#progress").css("visibility", "hidden");
location.href = "?" + encodeURIComponent(dbName) +
"/" + $.couch.encodeDocId(docID);
}
});
}
});
}
$(document).ready(function() {
$("button#submit").click(function(event) {
create_document();
});
});
This javascript is pretty much taken from the futon.browse.js uploadAttachment segment. The dialogue.html file is also just straight copy of couchdb's www/dialog/_upload_attachment.html. All files (the main html, basic.js and dialogue.html) are then uploaded to a CouchDB design document (in a database called uploader).
The document is created fine, but no matter what I do, the attachment is never saved. The various methods I've tried either result in an error about multi-part forms or, in this case, no discernible error at all.
Does anyone know what I'm doing wrong?
I inherited this code, so I don't know if it's optimal or not. But it does work:
jQuery.fn.sendForm = function(itemID, itemType) {
// Get all of the values from the form fields
var itemTitle = $('.settingsForm input#title').val(),
itemAuthor = $('.settingsForm input#author').val(),
itemDescription = $('.settingsForm textarea#description').val(),
itemDate = $('.settingsForm input#date').val(),
itemRev = $('.settingsForm input#_rev').val(),
itemDelete = $('.settingsForm input#delete:checked').val(),
itemType = $('.settingsForm select').val(),
itemFilename = $('.settingsForm input:file').val();
// Check for new uploaded file
if (itemFilename == undefined || itemFilename == ""){
$('.settingsForm input:file').remove();
itemFilename = "";
}
else {
itemFilename = itemFilename.replace(/^C:\\fakepath\\/i, '');
}
// If no new file, then fall back on the old filename
if (!itemFilename || itemFilename.length == 0) {
itemFilename = $('.settingsForm input#filename').val();
}
// Force to add a title (the only required field)
if (!itemTitle || itemTitle.length == 0) {
alert(libLang.addTitle); // Get text for language
return;
}
// Check if size of db is above the limit
dbSize = maxDBSize;
$.ajax({
url: "/"+ homeURL,
dataType: 'json',
async: false,
success: function(dbInfo){
dbSize = dbInfo.data_size;
}
});
if (itemDelete != 'Yes' && dbSize >= maxDBSize){
alert(libLang.noSpace);
return;
}
if (itemDelete != 'Yes'){
if (itemID != 'add'){
// Update existing record
$(this).ajaxSubmit({
url: "/"+ homeURL +"/"+ itemID,
data: {"filename":itemFilename},
success: function(resp) {
$.getJSON("/"+ homeURL +"/"+ itemID, function(revData) {
itemRev = revData._rev;
itemAttachment = revData._attachments;
user = revData.user;
if (!revData._attachments || revData._attachments.length == 0) {
$.couch.db(homeURL).saveDoc({
"_id": itemID,
"_rev": itemRev,
"filename":itemFilename,
"title":itemTitle,
"author":itemAuthor,
"type":itemType,
"description":itemDescription,
"date":itemDate,
"user":user
}, {
success: function() {
alert(libLang.saved); // Get text for language
window.location.replace("index.html");
}
});
}
else {
$.couch.db(homeURL).saveDoc({
"_id": itemID,
"_rev": itemRev,
"filename":itemFilename,
"title":itemTitle,
"author":itemAuthor,
"type":itemType,
"description":itemDescription,
"date":itemDate,
"user":user,
"_attachments":itemAttachment
}, {
success: function() {
alert(libLang.saved); // Get text for language
window.location.replace("index.html");
}
});
};
});
}
});
}
else {
// Add new record
uniqueID = $.couch.newUUID();
itemID = itemTitle.replace(/[\s]/g,'_');
itemID = homeUser +'-'+ itemType.charAt(0).toUpperCase() + itemType.slice(1) +'-'+ encodeURI(itemID) +'-'+ uniqueID;
itemID = itemID.replace(/[^a-z 0-9 _ -]+/gi,'');
$('form .settingsForm').attr({"action":"/"+ homeURL +"/"+ itemID});
// Save information
$.couch.db(homeURL).saveDoc({
"_id": itemID,
"filename":itemFilename,
"title":itemTitle,
"author":itemAuthor,
"type":itemType,
"description":itemDescription,
"date":itemDate,
"user":homeUser
}, {
success: function(){
// Get saved info, then add attachment to item
$.getJSON("/"+ homeURL +"/"+ itemID, function(revData) {
$('.settingsForm input#_rev').val(revData._rev);
var data = {};
$.each($("form :input").serializeArray(), function(i, field) {
data[field.name] = field.value;
});
$("form :file").each(function() {
data[this.name] = this.value.replace(/^C:\\fakepath\\/g, ''); // file inputs need special handling
});
itemFilename = data._attachments;
$('form.settingsForm').ajaxSubmit({
url: "/"+ homeURL +"/"+ itemID,
success: function(resp) {
$.getJSON("/"+ homeURL +"/"+ itemID, function(saveData) {
itemRev = saveData._rev;
itemAttachment = saveData._attachments;
// Resave all information
$.couch.db(homeURL).saveDoc({
"_id": itemID,
"_rev": itemRev,
"filename":itemFilename,
"title":itemTitle,
"author":itemAuthor,
"type":itemType,
"description":itemDescription,
"date":itemDate,
"user":homeUser,
"_attachments":itemAttachment
}, {
success: function() {
alert(libLang.saved); // Get text for language
window.location.replace("index.html");
}
});
});
}
});
});
}
});
};
} else {
// Delete the item from the library
$.couch.db(homeURL).removeDoc({'_id': itemID, "_rev": itemRev});
window.location.replace("index.html");
}
};

Categories

Resources