window location href not reloading - javascript

I am working with javascript and php, and I want to send variables from an html file to a php file continuously, but the method window.location.href only send it one time, despite I call the function every second. How do I keep sending data continuously using window.location.href?
HTML file:
<head>
<script type="text/javascript" src="zepto.min.js"></script>
<script type="text/javascript">
function refresh() {
var wind = 255;
var rain = 1;
var speed = 56;
window.location.href = "http://localhost/getData.php?s1=" + wind +"&s2=" + rain + "&s3=" + speed;
}
</script>
</head>
<body onload="setInterval(refresh, 1000);">
</body>

when you use window.location.href = 'http://somewhere, the browser looses context and your variables are lost.
a smarter way to keep sending variables to your server is by using the ajax function of zepto or jquery
$.get("http://localhost/getData.php?s1=" + wind +"&s2=" + rain + "&s3=" + speed", function(){
console.log('server received information');
})

Related

Trying to pass javascript arrays to Python Flask

I am trying to pass some javascript arrays to Flask to set my templates page but all I get in the out put page is "In the Host text box, you entered: None" message, here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="static/script.js"></script>
<title>Comms Checker</title>
</head>
<body>
<form name="ResultPage" action = "passFails.html" onsubmit="return validateTestPage()" method="post">
Number of Hosts/Ports:<br><input type="text" id="Number"><br/><br/>
Enter Comms Details
<div id="container"/>
</form>
</body>
</html>
the code above calls the javascript function below:
function addFields(){
// Number of inputs to create
var number = document.getElementById("Number").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (var i=1;i<=number;i++){
container.appendChild(document.createTextNode("Host: " + i));
var host = document.createElement("input");
host.type = "text";
host.id = "Host " + i;
container.appendChild(host);
container.appendChild(document.createTextNode("Port: " + i));
var port = document.createElement("input");
port.type = "text";
port.id = "Port " + i;
container.appendChild(port);
// Append a line break
container.appendChild(document.createElement("br"));
container.appendChild(document.createElement("br"));
}
var button = document.createElement("input");
button.setAttribute("type", "button");
button.setAttribute('value', 'Check');
button.setAttribute('onclick', 'checkVal()');
container.appendChild(button);
return true;
}
function checkVal() {
var myHost=[];
var myPort=[];
// Number of inputs to create
var number = document.getElementById("Number").value;
for (var i = 1; i <= number; i++) {
//pass myHost and myPort to first.py for further processing.
myHost.push(document.getElementById('Host ' + i).value);
myPort.push(document.getElementById('Port ' + i).value);
/*alert("Value of Host: " + i + " is: " + myHost[i]);
alert("Value of Port: " + i + " is: " + myPort[i]);*/
}
for (var i=0; i<number; i++){
alert("Value of Host: " + i + " is: " + myHost[i]);
alert("Value of Port: " + i + " is: " + myPort[i]);
}
$.get(
url="/passFails",
data={host: myHost},
success = function (data) {
alert('page content: ' + data);
}
);
return true
}
the javascript code should pass the array/list "myHost" to Python, but for some reason it fails to do so with no error messages.
the python script is as follows
from flask import Flask, render_template, request
import json
import jsonify
app = Flask(__name__)
#app.route('/Results')
def Results():
return render_template('Results.html')
#app.route('/passFails')
def passFails():
data = request.args.get('host')
print("The Value in passFails is :%s " % data)
return render_template('/passFails.html', Value=data)
if __name__=='__main__':
app.run(debug=True)
and finally, the above python script should pass the data to the last HTML page passFails.html where all the values in the array/list gets printed.
the passFails page is as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>In the Host text box, you entered: {{Value}}</h1>
</body>
</html>
I just want to know why the code in javascript part is not able to pass the list to python OR if there is anything wrong in the Python script which is causing problem in receiving the array?
Any Help will be greatly appreciated.
If you add a debug printing as a first line in a passFails, you'd see something like that:
def passFails():
print(request.args)
# Out: ImmutableMultiDict([('host[]', '1'), ('host[]', '2'), ('host[]', '3')])
As you've said, you've trying to pass some javascript arrays, so your requests looks something like:
$.get(
url="/passFails",
data={host: [1,2,3]},
success = function (data) {
alert('page content: ' + data);
}
);
And it'll be converted (what you can and totally should see in your browser debug console) to a request-url like:
http://localhost/passFails?host[]=1&host[]=2&host[]=3
So, your value couldn't be found at a host key. To make it work you could use request.args.getlist('host[]'). Another option is to serialize the myHost value from array to a JSON string before sending a request, so you'd be able to access value as request.args.get['host'], but you'll have to deserialize it from a JSON representation in Flask.
Change .get to .getlist
request.args.getlist('host')
examples
Peace
Finally, I found the answer, all I had to do was to include the following script tag in my HTML file for the javascript to to user the $.get() function to send data to python. that was the problem and it is successfully solved:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Thanks to all of you guys for sharing your responses.
In python file, you need to add methods = ['POST'], so your app route should be:#app.route('/passFails', methods = ['POST']), and then you can check
if request.method == 'POST':
#write you code

How do i auto refresh my div class content?

My code is as follows -
<div class="huge">
<?php echo date ("g:i:s A"); ?>
</div>
How do i set <div class="huge"> to refresh every second?
Assuming that you need to get the update from the server (noted the PHP code in your original post), there are two things you need to implement:
A Server-Side script (in this case written in PHP) to be requested by the client for fresh data.
A Client-Side javascript to fetch fresh data from the server and update your div.
Let's make an example.
index.php
<html>
<head>
<title>My date updater</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<div class="huge"><?php echo date ("g:i:s A"); ?></div>
</body>
</html>
Javascript (using jQuery)
setInterval(function(){
$.ajax({
url:'loadData.php'
}).done(
function(data){
$('.huge').html(data);
});
},1000);
loadData.php
<?php echo date ("g:i:s A"); ?>
Initially your page named in this example index.php will load and show the initial date (using a bit of php code inline).
Then the javascript will start to get data from the server (using an ajax request to loadData.php) every second and the div will be updated with the fresh data.
Hope it helps a bit!
P.S: Date and time information can also be fetched using pure javascript code on the client-side, but for some applications the date and time information on the client-side is not reliable enough since it relies on the date and time settings that are set by the client browser.
You could use Ajax, something like this:
If it's just simple text, or simple HTML being loaded then you could use
setInterval(function(){
$("#huge").load("now_playing.php");
...
}, 5000);
You could also use something like:
function reload() {
jQuery.ajax({
url: "fetch_message.php",
type: "POST",
success:function(data){
$('#huge').innerHTML(data);
setTimeout(function(){
reload()
}, 1000);
}
});
This will update the content of the element with id="huge" every second. you don't need any initial php value.
If you need other elements like minutes and seconds of course you can add dt.getMinutes() and dt.getHours() to the string.
<div id="huge"></div>
<script language="javascript">
function refreshSomething(){
var dt = new Date();
document.getElementById('huge').innerHTML = dt.getSeconds();
}
setInterval(function(){
refreshSomething() // this will run after every second
}, 1000);
</script>
This works too -
<script>function getTime(){
var date = new Date();
date.setTime(Date.now());
return (date.getHours() % 12) + ':' + leadingzero(date.getMinutes()) + ':' + leadingzero(date.getSeconds()) + (date.getHours() < 12 ? ' AM' : ' PM'); ;
}
function leadingzero(n) {
return (n < 10) ? ("0" + n) : n;
}
function updateDiv(){
var d = document.document.getElementsByClassName('yourDivClassname')[0];
d.innerHTML = getTime();
}
setInterval(updateDiv, 1000);</script>

Javascript - How to get script to run with Ajax requested data

Battlefield Page
In the image above, there is a page that has a battlefield with 20 users on it. I have written JavaScript to capture the data and store it in a MySQL db. The problem comes into the picture when I need to hit next to go to the next page and gather that data.
It fetches the next 20 users with an Ajax call. Obviously when this happens, the script can't log the new information because the page never loads on an Ajax call which means the script doesn't execute. Is there a way to force a page load when the Ajax link is clicked?
Here's the code:
grabData();
var nav = document.getElementsByClassName('nav')[0].getElementsByTagName('td')[2].getElementsByTagName('a')[0];
nav.addEventListener("click", function(){
grabData();
});
function grabData(){
var rows = document.getElementsByClassName('table_lines battlefield')[0].rows;
var sendData = '';
for(i=1; i < rows.length -1 ; i++){
var getSid = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].getElementsByTagName('a')[0].href;
var statsID = getSid.substr(getSid.indexOf("=") + 1); //Grabs ID out of stats link
var name = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].textContent.replace(/\,/g,"");
var tff = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[3].textContent.replace(/\,/g,"");
var rank = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[6].textContent.replace(/\,/g,"");
var alliance = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[1].textContent.trim();
var gold = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[5].textContent.replace(/\,/g,"");
if(alliance == ''){
alliance = 'None';
}
if(gold == '??? Gold'){
gold = 0;
}else{
gold = gold.replace(/[^\/\d]/g,'');
}
sendData += statsID + "=" + name + "=" + tff + "=" + rank + "=" + alliance + "=" + gold + "#";
}
$.ajax({
// you can use post and get:
type: "POST",
// your url
url: "url",
// your arguments
data: {sendData : sendData},
// callback for a server message:
success: function( msg ){
//alert(msg);
},
// callback for a server error message or a ajax error
error: function( msg )
{
alert( "Data was not saved: " + msg );
}
});
}
So as stated, this grabs the info and sends to the php file on the backend. So when I hit next on the battlefield page, I need to be able to execute this script again.
UPDATE : Problem Solved. I was able to do this by drilling down in the DOM tree until I hit the "next" anchor tag. I simply added an event listener for whenever it was clicked and had it re execute the JavaScript.
Yes, you can force a page load thus:
window.location.reload(true);
However, what the point of AJAX is to not reload the page, so often you must write javascript code that duplicates the server-side code that builds your page initially.
However, if the page-load-code-under-discussion runs in javascript on page load, then you can turn it into a function and re-call that function in the AJAX success function.
Reference:
How can I refresh a page with jQuery?

twitter sharing button bit.ly integration on a static website

I am trying to integrate bit.ly on my website in JS to short my url. All my url are too long, what will be the most straight foward way to use the bit.ly restful api for sharing button on a static website in HTML/javascript.
The result I want to get is when my user click share on my website the url is automatically shortened by bit.ly
here is the code I am currently using to share my pages dynamically on twitter:
<script type="text/javascript" charset="utf-8" src="http://bit.ly/javascript-api.js?version=latest&login=LOGINID&apiKey=APIKEY"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
function tweetCurrentPage()
{ window.open("https://twitter.com/share?url=" + escape(window.location.href) + "&text=" + document.title, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600'); return false; }
var TweetThisLink = {
shorten : function(e) {
e.preventDefault();
var url = this.href.substr(this.href.indexOf('http:',5))
BitlyClient.shorten(url, 'TweetThisLink.response');
},
response : function(data) {
var bitly_link = null;
for (var r in data.results) {
bitly_link = data.results[r]['shortUrl'];
break;
}
var tweet_text = "I am reading documentation of"
document.location = "http://twitter.com/share?url=" + encodeURIComponent(tweet_text + ' ' + bitly_link);
}
}
jQuery('.tweetlink').bind('click', TweetThisLink.shorten);
</script>
tweet this link
Not sure if this is on purposefully obfuscated for the sake of the question, but
In your script tag the src is:
"http://bit.ly/javascript-api.js?version=latest&login=LOGINID&apiKey=APIKEY".
LOGINID & apiKey are placeholders are in-place. You need to replace them with the appropriate keys you should receive from bitly.
if this is on purpose for the sake of the question please ignore this answer.
don't know why but my function "tweetCurrentPage()" for dynamic url won't work it's giving me a respond INVALID_URI from bit.ly, but if I hard code the href value like this twitter.com/share?url=+exemple.com"; it's working...

Variable url in json-script

Messing around for days know. Learning javascript and jquery a few weeks, it goes well, but sometimes...
For an mobile app i'm trying to get the coordinates. Showing them on page isn't a problem, but I want them elsewhere.
In the main.js
var getLocation = function() {
var suc = function(p) {
document.getElementById("locatie").innerHTML = "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20";
};
var locFail = function() {
};
navigator.geolocation.getCurrentPosition(suc, locFail);
};
And in the htmlfile
<body onload="getLocation();" >
<p id="locatie">Finding geolocation...</p></ul>
<div id="geolocation">
Bezig met laden. Momentje geduld</div>
<script type="text/javascript">
jQuery(function(){
var script=document.createElement('script');
script.type='text/javascript';
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
$("body").append(script);
});
function processTheseTerraces(jsonData){
var shtml = '';
var results = jsonData.results;
if(results){
$.each(results, function(index,value){
shtml += "<li class='store'><a class='noeffect' href='#'><span class='image' style='background-image: url(pics/terras1.jpg)'></span><span class='comment'>" + value.address + "</span><span class='name'>" + value.building_name + "</span><span class='stars5'></span><span class='starcomment'>132 Beoordelingen</span><span class='arrow'></span></a></li>";
});
$("#geolocation").html( shtml );
}
}
</script>
Now I want the coordinates passing through json and load the data. I thought to change
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
in
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20";
But that doesn't work. Anyone suggestions how I can solve this.
This: http://www.192.168.1.111 is just a wrong URL. I guess you need just this: http://192.168.1.111
Geolocation can take a long time (multiple seconds). It is an asynchronous request which means that the other javascript code may execute before the geolocation has grabbed the address. The solution is to put any code or function calls that use the location inside the callback function on the navigator.geolocation.getCurrentPosition
The JQuery is building the URL before the lat and lng have been defined.
onload="getLocation();" tells that when the document is loaded call getLocation function and inside this function you set the innerHTML of <P id="locatie"> TAG as: http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20
So problems are:
If you make a script tag and assign source then browser fetch the source data but writing an url on inner html of a <p> tag won't do this and it doesn't make sense.
Code fragment below is loaded before the document is loaded but i guess you do not want this:
jQuery(function(){
var script=document.createElement('script');
script.type='text/javascript';
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
$("body").append(script);
});
If you want: script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20"; then you have to define p.coords first and before calling this otherwise p.coords is undefined.
Solution i am not sure what you exactly asking so could not answer. Do you want to assign inner HTML of the #locatie element or do you want to load customized script as tag?
Either ways, you have to make an ajax call to server which maybe like this:
$.ajax({
url: "http://www.192.168.1.111/tools/gpslocation.php",
data: "lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20",
success: function(Result){
// use Result variable in came from the success function.
document.getElementById("Your_ID_Goes_Here").innerHTML = "do_Something";
}
});

Categories

Resources