Changing variable on button-click using JQuery / JavaScript - javascript

I am attempting to build a web feature that allows the user to select a window of time to see local Earthquake information, using information found here.
https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php
As you can see here, (https://codepen.io/JoshTheGray/pen/yPmJeR) I am having success parsing the information when I statically assign the url variable for whatever timeframe I want, however I am running into trouble trying to make that url variable change, based on a user button click.
My HTML
<div>Please select a window of time to see Earthquake information.</div>
<br>
<button id="1HourButton">Past Hour</button>
<button id="1DayButton">Past 24 Hours</button>
<br>
<br>
<div id="output1">Earthquakes Around the State<br><br></div>
<br>
My JavaScript / JQuery
;(function($){
$( document ).ready(function() {
// testing document load state
console.log( "document loaded" );
var output1 =document.getElementById('output1');
var hr = new XMLHttpRequest();
// Asigns url based on button choice from user.
var url = '';
$('#1HourButton').click(function () {
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson';
console.log(url);
});
$('#1DayButton').click(function () {
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';
console.log(url);
});
hr.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
var myObj = JSON.parse(hr.response);
for(i=0; i < myObj.features.length; i++) {
if (myObj.features[i].properties.title.includes("Alaska")) {
output1.innerHTML += myObj.features[i].properties.title + '<br>';
}
}
}
}
hr.open("GET", url, true);
hr.send();
});
})(jQuery);
=========================
Currently I am seeing the correct URL information passed to the console upon button click, but the json information is no longer coming through.
What am I missing?

Related

Sending data and saving in a text field

I have a main page with a popup window.
<textarea class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
There is also a second page. (/conclusion/main)
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
I enter the text in the window and send. The window should close and the text should be sent to the second page and the text should be saved in the field "textarea". Even if they close the page or reload, the text should remain in the second page.
This code allows you to save, but after closing the page, does not save
(function(){
var textarea = document.getElementById('retro');
if (localStorage.retro)
{
textarea.value = localStorage.retro;
}
textarea.onchange = function()
{
localStorage.retro = this.value;
}
})();
Sends from the first page to the second
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params2;
}
params = getParams();
name = unescape(params["name"]);
document.getElementById('retro').innerHTML = name;
There are some questions around what you are trying to do here. What I have done is broken this down into 2 parts
Passing the local storage between 2 pages and accessing it.
Decoding Parameters in the URL and assigning them
Some assumptions that I made:
I have noticed some of the classes from bootstrap so i assume that you have jQuery on the page and also you may know how to use it.
Using chrome for testing this
PART 1 - Passing localstorage between windows:
First thing to note is you may be better using a cookie library (js-cookie) or creating one yourself that you can access. As localstorage may well be insecure depending on what data you want to store in there.
With that out of the way, you were on the right track, just needed to add your event listener to 'input' as i think then every keystroke the data in local storage is being updated.
Page 1
HTML
<textarea id="retro" class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
JS (I would recommend place this at the bottom of you page for quick testing)
<script type="text/javascript">
var textarea = document.getElementById('retro');
textarea.addEventListener('input',function(){
localStorage.setItem('retro', this.value);
})
</script>
In Chrome developer tools if you watch the variable 'localstorage' then you will see this change as you key in the value.
What I have done here is bound the event listener to the text area so that any 'input' the value changes, furthermore is am setting the item in the localstorage
PAGE 2
HTML
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
JS
<script type="text/javascript">
var textarea = document.getElementById('retro').value = localStorage.getItem('retro');
</script>
Here using the 'getItem' method for localstorage you can then retrieve it from the storage area and output it as the value of the textarea.
Obviously is the cache or localstorage is cleared then this value will disappear.
PART 2 - Decoding Parameters in the URL and assigning them
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
This function above will get you any parameter you want form the url I found this from here. This is using jQuery.
Here is how you would use it
// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
Well I hope this answers your question on both parts, and helps you further, please add any comments if I have missed anything and I will be happy to update my answer

How to compare JSON data from the same API request?

I'm still learning a lot about web development and javascript, so forgive me if my explanations are not clear.
I have a function to request from an API informations about cryptocurrency (Price, volume etc.) in a JSON file and then i display the price on the web page every 15 seconds.
I want to change the background color of the card where the price is displayed by comparing the actual price and the new one coming from the next request.
here's my javascript :
function requestPrice(url, domLocation){
var req = new XMLHttpRequest();
req.open("GET", url);
req.addEventListener("load", function() {
if (req.status >= 200 && req.status < 400) {
var data = JSON.parse(req.responseText)
domLocation.innerHTML = data.ticker.price + "$";
erreur.innerHTML = "";
} else {
erreur.innerHTML = "Erreur: " + req.status + " " + req.statusText;
}
});
req.addEventListener("error", function () {
erreur.innerHTML = "Erreur";
});
req.send(null);
}
var btcPrice = document.getElementById('boxBTC'), erreur =
document.getElementById('erreur');
setInterval(requestPrice("https://api.cryptonator.com/api/ticker/btc-eur",
btcPrice), 15000);
I was thinking of a simple comparaison between the values and put this code in my loop but i need to stock the actual price somewhere to do the comparison with the new one coming and i'm stuck with that.
if (valueOf(data.ticker.price) <= valueOf(data.ticker.price)){
document.getElementById('overviewcard').style.backgroundColor = red;
} else {
document.getElementById('overviewcard').style.backgroundColor = blue;
}
Or
var overviewcard = getElementById('overviewcard');
if (data.ticker.price <= data.ticker.price){
overviewcard.style.backgroundColor = red;
} else {
overviewcard.style.backgroundColor = blue;
}
here's the html :
<div class="overviewcard">
<span id="boxBTC">...</span>
<span id="erreur"></span>
</div>
Thanks a lot for your help
You can do this in a myriad of ways, but the simplest is to grab the data from the actual HTML DOM element.
var currValue = document.getElementById('boxBTC').innerHTML;
if(valueOf(data.ticker.price) == currValue) {
// do something
}
If you're boxBTC string is formatted too much (eg. if you make "1000" -> "1,000"), then you can always also store a data attribute of the raw value inside the DOM as a data attr.
// assigning the data
document.getElementById('boxBTC').setAttribute('data-val', price);
...
// accessing the data
document.getElementById('boxBTC').getAttribute('data-val');

Error on AJAX call PHP function with JSON return

I want to develop a News Ticker using three technologies: PHP, Javascript and AJAX.
First, I made a PHP function getFeed() to fetch data from News websites on an Array, then I made a JSON return using this code: echo json_encode($articles, true);
Secondly, I aim to use AJAX and Javascript to make repeated calls to getFeed() function, here is my javascript code:
<script type="text/javasript">
var xmlhttp=false;
function begin() {
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200){
var jsonContent=JSON.parse(this.responseText);
displayT(jsonContent);
}
};
// rssnews.inc.php contain the getFeed() function
xmlhttp.open('GET','rssnews.inc.php', true);
xmlhttp.send();
}
// displayT(content) function display the JSON element
function displayT(content){
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<h4><a href="' + arr[i].link+ '">' +
arr[i].title + '</a></h4><br>';
}
document.getElementById('item').innerHTML = out;
}
</script>
On the HTML page, I have the following components a button (id="start") - on click execute begin() function, a div container (id="Ticker") and a div (id="item") for display data with AJAX
<form>
<button type="submit" class="btn btn-default" id="start" onclick="begin();"> START </button>
</form>
<div id= "ticker" style="border: 1px solid #ccc; height: 500px; weight:600px;">
<div id="item">
<!-- I want to display the fetched data by 4 items at a specific time Interval-->
</div>
</div>
When I click on the start button, I don't get the json data.
How can I solve this problem and how can I ensure that this AJAX calls is the most appropriate way to my Ticker.
Thank you!
The error is essentially saying that the file you are trying to GET with you AJAX call, does not exist at the specified location (which is http://localhost/rss/rssnews.inc.php).
You are using a Relative path, which searches for 'rssnews.inc.php' in the same folder. To go up to the parent directory, use ../.
Or use an Absolute path, as in http://localhost/rss/rssnews.inc.php. (Replace with absolute path to your PHP script)
Update
(after HTTP 401 solved)
displayT function is taking content as input, and is then reffering to arr, which is not defined.
Assuming content is actually an array containing your data in the desired format, replace arr with content:
function displayT(content){
var out = "";
var i;
for(i = 0; i < content.length; i++) {
out += '<h4><a href="' + content[i].link+ '">' +
content[i].title + '</a></h4><br>';
}
document.getElementById('item').innerHTML = out;
}

Click "submit", send data, but keep the page from redirecting to the new URL

What my script does:
I open https://mylink.com/#script
The script in my chrome extension checks for the #script in the URL and calls a function
The function clicks some checkboxes and then a "submit" button
After 3 seconds the script refreshes the website with the hashtag to create an infinite loop
Problem:
The data from the checkboxes/submit need to go through to the server - that's why I have to wait some time before refreshing. The 3 seconds seem to be enough for that.
Sometimes the website takes 15 seconds until it redirects me to the new site after submitting, but sometimes it's lightning fast and opens the new website before the 3 seconds before the reload have passed - since the opened website doesn't have the #script, my loop stops working.
What I need help with:
How long does it take to send the information from the form so they get through to the server? I know that I don't have to wait for the server's answer and the redirection to the new page, but I think I can't refresh instantly.
Is there a way to detect at which point the new site will be opened so the script could call a function before that happens and redirect to the URL with the hashtag? Or even better: Detect the moment when the information is completely sent from the client side and then instantly refresh.
I would like to keep the time the whole loop needs as short as possible!
Code for understanding:
The submit form on the website:
<form action="/withdraw-request" method="post">
<input type="hidden" name="_csrf" value="YEZknGzr-HW1ThkFrf9bO1M_IuQRJSVk-W6M">
<div id="items">...contains checkboxes...</div>
<input class="button right blue" type="submit" value="Withdraw selected items">
</form>
My content.js (in the chrome extension):
chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
if(window.location.hash=="#script") {
var tradestatus = document.getElementsByTagName("td");
console.log("Offer-status: " + tradestatus[8].innerHTML);
var oneKeyOnly = true;
function checkItem() {
var itemsArray = ["Apples", "Bananas", "Melons", ];
var matchingItems = [];
var x = document.getElementsByClassName("item");
for(var y = 0; y < x.length; y++){
if(itemsArray.indexOf(x[y].getAttribute("data-name")) >= 0){
var id = x[y].getElementsByClassName("item-checkbox")[0].getAttribute("id");
matchingItems.push(id);
}
}
return matchingItems;
}
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
function clickButton(val)
{
var buttons = document.getElementsByTagName('input');
for(var i = 0; i < buttons.length; i++)
{
if(buttons[i].type == 'submit' && buttons[i].value == val)
{
buttons[i].click();
console.log("Trying to withdraw!");
break;
}
}
}
var result = checkItem();
var lengthOfArray = result.length - 1;
if (oneKeyOnly == true) {
var rand = randomIntFromInterval(0,lengthOfArray);
document.getElementById(result[rand]).checked = true
console.log("Found: " + result[rand]);
}
else {
for(index=0, len = result.length; index < len; ++index) {
document.getElementById(result[index]).checked = true
keynr = index + 1;
console.log("Found " + result.length + " fruits - Selected Nr. " + keynr + "!");
}
}
clickButton("Withdraw selected items");
unloadready = true;
setTimeout((function(){ location.reload(true) }), 3000);
}
}
}, 10);
});
Withdraw.js:
Pastebin: http://pastebin.com/9q72Ti2b
It gets called from somewhere. I can see it in the "network" tab next to the chrome console.
Edit_1:
I tried to use google for a while now and found an ajax documentation and a piece of code that I tried to modify so it would work for me. There is still some really basic stuff that I don't understand.
The code:
$('#submit').click(function()
{
$.ajax({
url: withdraw-request,
type:'POST',
data:
{
items,
_csrf
},
success: function(msg)
{
alert('Success!');
location.reload(true);
}
});
});
Here is the form again from that website with one of the checkboxes added.
<form action="/withdraw-request" method="post">
<input type="hidden" name="_csrf" value="YEZknGzr-HW1ThkFrf9bO1M_IuQRJSVk-W6M">
<input type="checkbox" name="items" value="34155017" class="item-checkbox" id="item-34155017" data-price="562500">
<input class="button right blue" type="submit" value="Withdraw selected items">
</form>
So if I understand it right, then the website is using POST to send "_csrf" and "items" to "withdraw-request" (added the names to "data" in the code).
Why is there nothing like ".php" on "withdraw-request"?
How can I call this code if the form doesn't have a name for its own?
How can I add something like "onClick" or "onSubmit" to a website that is not my own and where I can't change the actual code? Solved that one myself!
document.getElementsByTagName("FORM")[1].setAttribute("onsubmit", "specialFunction()");
Edit_2:
Kind of made it work:
I added this to my 'content.js' to add a name to the form and an ajax function:
var formAdd = document.getElementsByTagName('FORM');
formAdd[1].setAttribute("id", "submitthisform");
var $form = $("#submitthisform");
// register handler for submit first
$form.submit(function (event) {
$.ajax({
type: $form.attr("method"),
url: $form.attr("action"),
data: $form.serialize()
})
.done(function (data) {
})
.fail(function (r, s, e) {
});
event.preventDefault();
});
I can call this by $form.submit();. It seems to work, but it still redirects to the new page. What am I doing wrong here?

Auto Form Post With Url Function

I have a problem with javascript. I use google api and it contains ajax. The problem here is that, I need to catch values from URL like http://examplesite.com/index.php?s=some+values . I need to search values automatically. I try to do this for along time. However, I couldn't. How can I do this ?
This is my submit form:
<form id="searchForm" method="post">
<fieldset style="width: 520; height: 68">
<input id="s" type="text" name="s" />
<input type="submit" value="Submit" id="submitButton" />
Here is my javascript codes:
$(document).ready(function(){
var config = {
siteURL : 'stackoverflow.com', // Change this to your site
searchSite : true,
type : 'web',
append : false,
perPage : 8, // A maximum of 8 is allowed by Google
page : 0 // The start page
}
// The small arrow that marks the active search icon:
var arrow = $('<span>',{className:'arrow'}).appendTo('ul.icons');
$('ul.icons li').click(function(){
var el = $(this);
if(el.hasClass('active')){
// The icon is already active, exit
return false;
}
el.siblings().removeClass('active');
el.addClass('active');
// Move the arrow below this icon
arrow.stop().animate({
left : el.position().left,
marginLeft : (el.width()/2)-4
});
// Set the search type
config.type = el.attr('data-searchType');
$('#more').fadeOut();
});
// Adding the site domain as a label for the first radio button:
$('#siteNameLabel').append(' '+config.siteURL);
// Marking the Search tutorialzine.com radio as active:
$('#searchSite').click();
// Marking the web search icon as active:
$('li.web').click();
// Focusing the input text box:
$('#s').focus();
$('#searchForm').submit(function(){
googleSearch();
return false;
});
$('#searchSite,#searchWeb').change(function(){
// Listening for a click on one of the radio buttons.
// config.searchSite is either true or false.
config.searchSite = this.id == 'searchSite';
});
function googleSearch(settings){
// If no parameters are supplied to the function,
// it takes its defaults from the config object above:
settings = $.extend({},config,settings);
settings.term = settings.term || $('#s').val();
if(settings.searchSite){
// Using the Google site:example.com to limit the search to a
// specific domain:
settings.term = 'site:'+settings.siteURL+' '+settings.term;
}
// URL of Google's AJAX search API
var apiURL = 'http://ajax.googleapis.com/ajax/services/search/'+settings.type+'?v=1.0&callback=?';
var resultsDiv = $('#resultsDiv');
$.getJSON(apiURL,{q:settings.term,rsz:settings.perPage,start:settings.page*settings.perPage},function(r){
var results = r.responseData.results;
$('#more').remove();
if(results.length){
// If results were returned, add them to a pageContainer div,
// after which append them to the #resultsDiv:
var pageContainer = $('<div>',{className:'pageContainer'});
for(var i=0;i<results.length;i++){
// Creating a new result object and firing its toString method:
pageContainer.append(new result(results[i]) + '');
}
if(!settings.append){
// This is executed when running a new search,
// instead of clicking on the More button:
resultsDiv.empty();
}
pageContainer.append('<div class="clear"></div>')
.hide().appendTo(resultsDiv)
.fadeIn('slow');
var cursor = r.responseData.cursor;
// Checking if there are more pages with results,
// and deciding whether to show the More button:
if( +cursor.estimatedResultCount > (settings.page+1)*settings.perPage){
$('<div>',{id:'more'}).appendTo(resultsDiv).click(function(){
googleSearch({append:true,page:settings.page+1});
$(this).fadeOut();
});
}
}
else {
// No results were found for this search.
resultsDiv.empty();
$('<p>',{className:'notFound',html:'No Results Were Found!'}).hide().appendTo(resultsDiv).fadeIn();
}
});
}
function result(r){
// This is class definition. Object of this class are created for
// each result. The markup is generated by the .toString() method.
var arr = [];
// GsearchResultClass is passed by the google API
switch(r.GsearchResultClass){
case 'GwebSearch':
arr = [
'<div class="webResult">',
'<h2>',r.title,'</h2>',
'<p>',r.content,'</p>',
'',r.visibleUrl,'',
'</div>'
];
}
// The toString method.
this.toString = function(){
return arr.join('');
}
}
});
Look at my answer here. As you can see, it is not too difficult to set a get parameter. Now, I will show you how you can get a get parameter:
function getGetParameter(paramName)
{
var url = window.location.href;
if (url.indexOf(paramName + "=") >= 0)
{
var returnValue = url.substring(url.indexOf(paramName + "="));
if (returnValue.indexOf("&") >= 0)
{
returnValue = returnValue.substring(0, returnValue.indexOf("&"));
}
return returnValue.substring(returnValue.indexOf("=") + 1);
}
return null;
}
As about searching for values automatically, you need to specify what and how would you like to search for, as this can be needed/done literally in infinitely many ways.
maybe this is the problem: you're trying to use an API and it's no longer avaiable.
Object {responseData: null, responseDetails: "This API is no longer available.", responseStatus: 403}
More information here: https://developers.google.com/image-search/v1/jsondevguide
Now, I'm trying to find a migration to version 2.

Categories