Trying to send value from javascript to python server - javascript

I have multiple input tags, my task is to collect the values entered by the user and send it back to the server. I am using Django as my framework. I am successful in sending the data to the client side (javascript).
To return back the data from javascript function to my python function, I used XMLHttpRequest.
I have added my code below:
<html>
<head>
<style>label{ text-align:center; width:250px; color:blue; display:inline-block}</style>
<script type="text/javascript" src="'+url_read+'"></script>
<script>
function submit_this()
{
var i,j;var arr=[];
for(i=0; i<Hello.length; i++)
{
arr[i]=[];
for(j=0;j<Hello[i].length; j++)
{
arr[i].push(document.getElementById(Hello[i][j]).value);
}
}
alert(document.getElementById(Hello[1][0]).value);
xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open('POST', '/button_click',true);
xmlHttpReq.send('w=' + encodeURI(arr));
}
</script>
</head>
<body>
<center>
<button id="submit_button" onclick="submit_this();" value="Submit">Submit</button>
</center>
</body>
</html>
The above code is stored in a string called html_string.
Hello is a json object read from the file denoted by the varible url_read. It was dumped using Python.
The plan was to use HttpResponse to send the html_string and render the html page in return.
I understand that I need to make one POST function in one of the classes in views.py. But unable to understand how to approach this problem.
I have to somehow send the javascript data structure named arr back to the server side. The main doubt is where can I put my code where I can read the value posted by the javascript function.
I want to navigate to a new page once submit button has been pressed and in Django each url has a new function (in views.py) associated with it. Should I place it in that ?

Here is an example where in I am sending values to (Django)python server using JS, and receiving html rendered template.
I am using ul tag with id #Nearby to load html inside an html.
Ajax success is returning html from django view rendered through url endpoint '/getGopoints/'
template.html
<div class="row">
<div>
<ul id="Nearby">
</ul>
</div>
</div>
<script>
$(document).ready(function(){
$('#dataTables-example1').DataTable({
responsive: true
});
getLocation();
});
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position) {
$.ajax({
url : '/getGopoints/', // the endpoint
type : 'GET', // http method
data : { 'lat' : position.coords.latitude,
'lon' : position.coords.longitude,
'csrfmiddlewaretoken': '{{csrf_token}}'
}, // data sent with the post request
// handle a successful response
success : function(data) {
$('#Nearby').html(data);
},
dataType: 'html'
});
}
</script>
urls.py
url(r'^getGopoints/$',views.getGopoints, name='getGopoints'),
views.py
def getGopoints(request):
lat = str(request.GET['lat'])
lon = str(request.GET['lon'])
pnt=fromstr('POINT(%s %s)' %(lon,lat))
with_in_distance = 20
go_points = GoPoint.objects.filter(point__distance_lte=(pnt, D(km=with_in_distance)))
context = RequestContext(request,
{'go_points':go_points,
'with_in_distance':with_in_distance,
})
return render_to_response('nearby.html',
context_instance=context)

Related

Pass data between two HTML pages (Google Apps Script)

I'm trying to pass var 'id' from the page 'a.html' to 'b.html'. The var content comes from 'code.gs' as below:
code.gs
function data(){
var id = 1;
return id;
}
Next, I get this var and I show it in 'a.html':
a.html
<?
var id = data();
?>
<h1><?= id ?></h1>
Go to B.html
By clicking 'Go to B.html', the system directs the user to there. I need to bring the same value of var 'id' from the page 'a.html' to 'b.html'.
Ps: searching for a little, I saw that there's a kind to send this var by the command 'localStorage', but it's not working for me. :(
Can anybody help me?
Use localstorage
a.html
localStorage.setItem('id',1)
b.html
var id = localStorage.getItem('id')
the other way is to put it in a js file and import it in both html
Storing & Retrieving html data on the server
Client Side JavaScript:
<script>
function saveId(v) {
google.script.run.saveKeyValue({key:'id',value:v});
}
function getId() {
google.script.run
.withSuccessHandler(function(v){
alert('The value is ' + v );
})
.getKeyValue('id');
}
</script>
Server Side Google Apps Script:
function saveKeyValue(obj) {
PropertiesService.getScriptProperties().setProperty(obj.key,obj.value);
}
function getKeyValue(key) {
return PropertiesService.getScriptProperties().getProperty(key);
}
You could also replace PropertiesService with CacheService.
Client To Server Communications
Properties Service

Flaskr url_for with javascript variable as parameters is not working to python

I'm trying to use flask with url_for. The problem is that when I try to launch an alert with the value of the javascript variable everything seems ok, but when I try to launch a alert with the url_for the content of the variable is not printed. What I'm doing wrong? or What is missing in my code?
How can I pass a JavaScript variable into the url_for function?
html code:
<a class="dissable_user_btn" data-user_id="{{user.id}}" href="#" title="Change Status"><i class="fa fa-plug"></i>
</a>
JS Code:
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id) //everything ok
alert ('{{url_for('.dissable', _id=user_id)}}'); //dont print the valur of user_id
</script>
Short answer: you can't. Flask & Jinja2 render the template on the server side (e.g. Flask is translating all of the {{ }} stuff before it sends the HTML to the web browser).
For a URL like this where you're including a variable as part of the path you'd need to build this manually in javascript. If this is an XHR endpoint I'd recommend using GET/POST to transfer the values to the server as a better best practice than constructing the URL this way. This way you can use Jinja:
$(document).ready(function(){
var baseUrl = "{{ url_for('disable') }}";
$('.dissable_user_btn').click(function(event) {
var user_id = $(this).data("user_id");
// first part = url to send data
// second part = info to send as query string (url?user=user_id)
// third parameter = function to handle response from server
$.getJSON(baseUrl, {user: user_id}, function(response) {
console.log(response);
});
});
});
I found another solution for this. My problem started when I needed to pass a variable with space.
First I created a function to remove trailing and leading spaces
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
After that, I used the function and encoded the URL
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id)
user_id = strip(user_id).replace(" ","%20");
alert ('{{url_for('.dissable', _id='user_id')}}.replace('user_id',user_id);
</script>
It worked pretty nice for me!
This is how I applied to my problem
<script>
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
$(document).ready(function() {
$('#exportcountry').click(function() {
var elemento = document.getElementById("countryexportbtn");
var country = strip(elemento.textContent).replace(" ","%20");
$('#exportevent').load("{{ url_for('get_events',country = 'pais') }}".replace('pais',country));
});
});
</script>

how to store state using in sinatra using json/javascript without databases

The html view of the app contains a variable which is by default set to 20. This temperature is then increased or decreased using a up/down button when running the app in the browser. However if the browser or page is refreshed (or redirected) temperature does not remain but instead always resets to 20.
Here is the view:
<!DOCTYPE html> <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'> <html> <head>
<link rel="stylesheet" type="text/css" href="style.css"> </head> <body>
<section class="display">
<h1>Thermostat</h1>
<input id='city' type='text' placeholder="city name">
<button id='submit'>Submit</button>
<p id='weather'></p>
<h1 id="temperature"></h1>
<h4 id="psm"></h4>
<form action='/temperature' method='post'>
<button class="icon icon-up" id="up" name='temp'></button>
<button class="icon icon-down"id="down" name='temp'></button>
<button id="reset" name='temp'>reset</button>
<button id="switchpowersaving">PSM</button>
</form>
</section>
<script src="jquery.js"></script>
<script src="thermostat.js"></script>
<script src="interface.js"></script>
<script src="weatherAPI.js"></script> </body> </html>
When we visit the page we are directed to the index. Here we then increase/decrease the temperature. Every time temperature is changed a 'POST' method is sent to our /temperature page. This then creates a hash using JSON, sessions and parameters. This in the interface.js file there is an ajax GET function which stores this new temperature as data.temp. This should then set the thermostat.temperature to the stored data.temp everytime the page is reloaded. However it continually gets reset to 20.
This is the controller:
require 'sinatra'
require 'json'
enable :sessions
get '/' do
send_file 'views/index.html'
end
post '/temperature' do
p params[:temp]
session[:temp] = params[:temp].to_i
redirect '/temperature'
end
get '/temperature' do
p session[:temp]
if session[:temp]
JSON.generate({temp: session[:temp]})
else
JSON.generate({temp: 20})
end
redirect '/'
end
Here is the interface.js file:
$(document).ready(function() {
var thermostat = new Thermostat();
var temp = thermostat.temperature;
$.ajax({
type: 'GET',
url: 'http://localhost:4567/temperature',
success: function(data){
temp = data.temp;
},
error: function(){
alert('Error loading temp');
}
});
updateTemperature();
$('#up').click(function() {
thermostat.increaseTemperature();
updateTemperature();
});
$('#down').click(function() {
thermostat.decreaseTemperature();
updateTemperature();
});
$('#reset').click(function() {
thermostat.tempReset();
updateTemperature();
});
$('#switchpowersaving').click(function() {
thermostat.switchModePowerSaving();
updateTemperature();
});
function updateTemperature() {
$('#temperature').text(thermostat.currentTemperature() + "\xB0C");
$('#up').attr('value', thermostat.currentTemperature());
$('#down').attr('value', thermostat.currentTemperature());
$('#reset').attr('value', thermostat.currentTemperature());
$('.display').css('background-color', thermostat.displayColor());
$('#psm').text(thermostat.displayPowerSaveMode());
}
});
Here is the thermostat.js :
function Thermostat(){
this.temperature = 20;
this.MINTEMP = 10;
this.isPowerSaving = true;
this.thermostatDisplay = 'yellow';
}
Thermostat.prototype.currentTemperature = function(){
return this.temperature;
};
Thermostat.prototype.increaseTemperature = function(){
if ( this.currentTemperature() >= this.maxTemp()) {
throw 'Max. temp reached';
}
this.temperature ++;
};
Thermostat.prototype.decreaseTemperature = function(){
if ( this.currentTemperature() <= this.MINTEMP ) {
throw 'Min. temp reached';
}
this.temperature --;
};
Thermostat.prototype.maxTemp = function(){
if(this.isPowerSaving === true) {return 25;}
else
{return 32;}
};
Thermostat.prototype.switchModePowerSaving = function() {
if (this.isPowerSaving === true)
{this.isPowerSaving=false;}
else
{this.isPowerSaving=true;}
};
Thermostat.prototype.tempReset = function() {
this.temperature = 20;
};
Thermostat.prototype.displayColor = function() {
if(this.temperature <= 18) {return 'green';}
if(this.temperature <= 25) {return 'yellow';}
if(this.temperature > 25) {return 'red';}
};
Thermostat.prototype.displayPowerSaveMode = function(){
if(this.isPowerSaving === true) {return 'Power Save Mode: ON';}
else {return 'Power Save Mode: OFF';}
};
The increaseTemperature/decreaseTemperature functions simply increase and decrease thermostat.temperature by +1/-1.
The new temperature when the button is pressed can be accessed when directly accessing '/temperature' in the browser however when redirected to the '/' the new thermostat.temperature is not set to the new temperature and always resets to the default temperature (20).
How can this be stored in state without using databases. (Store the new temperature so when the page is refreshed the new temperature remains rather than resetting to 20.
A couple of issues here:
send_file is not the preferred way of loading a HTML file using Sinatra. The alternative to this is to rename the index.html to index.erb and then use the following as the route descriptor:
get '/' do
erb :index
end
ERB is a superset of HTML and adds ruby interpolation tags that can be used to pass variables from Sinatra or simply run ruby commands in the view. These tags are similar to JSP's <%%> or PHP's <?php ?> if you're familiar with those. In ERB, <%%> would run a ruby command, <%= %> can be used to print out the result of a ruby command onto the view.
It's important to figure out the data type of request/response upfront while designing the routes. For instance, when interface.js loads, it makes a GET request via jQuery to the '/temperature endpoint. Since you haven't specified the data type, the response would be a string and data.temp will be null. So in the ajax call, you'd need to add a dataType: 'json' setting:
$.ajax({
type: 'GET',
url: 'http://localhost:4567/temperature',
dataType: 'json',
success: function(data){
// same as earlier
});
One more good thing to do is not to mix and match AJAX calls and redirect calls in sinatra. This is a problem especially in this case because when you redirect to the index page, although the session data is present, it's not getting loaded/displayed anywhere. Ideally, in Sinatra you'd have to assign the value to an instance variable and print it out in the view:
# app.rb
get '/' do
#temp = session[:temp] || 20
erb :index
end
# views/index.erb
# truncating common code
<h1 id="temperature"><%= #temp %></h1>
That way, when the get '/' route loads, initial temperature is displayed. The $.ajax GET request can be removed entirely.
When buttons are clicked, by default the form submit happens which will do a full reload. This can mess up with any JS based rendering you are doing (I'm unable to understand that part entirely for now). So instead of doing a full page redirect, it's better to an AJAX post (like pointed out in the comments) to '/temperature' route. Note that you'd have to disable the default action of a button click. So:
$('#up').click(function() {
thermostat.increaseTemperature();
updateTemperature();
});
and other click handlers should be changed to:
$('#up').click(function(event) {
event.preventDefault();
event.stopPropagation();
thermostat.increaseTemperature();
updateTemperature();
});
This will ensure that the default HTML form submit doesn't happen when you click on the button. And updateTemperature() will make an ajax POST call. I've put up a sample here: https://gist.github.com/kgrz/9320d1682e682a9930c30e34c979a306

Using YQL to get JSON data from cross-domain server, how to create a table with retrieved data

I did a cross-domain JSON request with YQL and it returns me the JSON code in a table <div> in the html file.
Now my problem is that I don't know to get this data and put it in a table.
This is the code (in JS file):
// JavaScript Document
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
// if it is an external URI
if(url.match('^http')){
// call YQL
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
// this function gets the data from the successful
// JSON-P call
function(data){
// if there is data, filter it and render it out
if(data.results[0]){
var data = filterData(data.results[0]);
container.html(data);
// otherwise tell the world that something went wrong
} else {
var errormsg = "<p>Error: can't load the page.</p>";
container.html(errormsg);
}
}
);
// if it is not an external URI, use Ajax load()
} else {
$('#target').load(url);
}
}
// filter out some nasties
function filterData(data){
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
});
and here is the html code:
<body>
<div id="doc" class="yui-t7">
<div id="hd" role="banner">
<h1>
Ajax with jQuery - using YQL
</h1>
</div>
<div id="bd" role="main">
<h2>
Demo
</h2>
<ul>
<li>
<a class="ajaxtrigger" href="ajaxcontent.html">
Load Ajax Content
</a>
</li>
<li>
<a class="ajaxtrigger" href="linkpage">
Get cspro.json
</a>
</li>
</ul>
<div id="target">
<!-- <script>window.alert(container)</script> -->
</div>
<h2>
Formatted List
</h2>
</div>
<div id="placeholder"></div>
<!-- <script> document.getElementById("placeholder").innerHTML = container.html(data);
</script> -->
<h2>
TEST
</h2>
</div>
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script src="code.js"></script>
<script src="using-yql3.js"></script>
</body>
I've try with:
// $.getJSON(data, function(json){
// figure out the format of the answer here...
//
document.getElementById("placeholder").innerHTML=prova.buy.currency+" "+prova.sell.currency+" "+prova.offer[0].amount+" "+prova.offer[0].rate+" "+prova.offer[0].seller.name;
but it didn't work.
(UPDATE) after your indications, I've tested this:
// TEST
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=json'&callback=?", // QUESTO รจ URL cui segue la "," e poi function(data)
// this function gets the data from the successful
// JSON-P call
function(data){
document.getElementById('placeholder').value = JSON.stringify(data,null,' '); //MIO
// if there is data, filter it and render it out
if(data.results[0]){
var data = filterData(data.results[0]);
container.html(data);
alert(data); //MIO TEST
// otherwise tell the world that something went wrong
} else {
var errormsg = "<p>Error: can't load the page.</p>";
container.html(errormsg);
}
}
);
but it works up to alert(data) simply "jumping" the part of the code related to document.getElementById.
I've also changed the "xml" request into "json" request...
SECOND UPDATE
I've solved the problem with the "div id=placeholder" in the html table. Seems it has some problems with this div, considering that changing the "div id" with a "texture id=placeholder" it works.
So, now I have the whole json string in my text area.
I've tried the getJson command to recover a parte of the data and get it in a table, but again I've having some problems.
I can't understand with the code you suggested to me, I have a json code, why I can't extract it and show the part i need?
FINAL PARTIAL UPDATE
The problem was that the "data" filter wasn't eliminating "" tag from data, so that the parse.Json(data) was unable to read the format!
Right know I retrieve the information I need.
Here's the final .js code:
// JavaScript Document
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
// if it is an external URI
if(url.match('^http')){
// call YQL
// TEST
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=json'&callback=?",
// this function gets the data from the successful
// JSON-P call
function(data){
// if there is data, filter it and render it out
if(data.results[0]){
**var data = filterData(data.results[0]);**
container.html(data);
alert(data); // TEST VERIFY (after FILTER before data extraction)
document.getElementById("prova1").value = data; // TEST full data return in a textarea
var obj = $.parseJSON(data); // JSON elements retrieve
alert(obj.sell.currency); // TEST for element retrieve
// TEST END
// otherwise tell the world that something went wrong
} else {
var errormsg = "<p>Error: can't load the page.</p>";
container.html(errormsg);
}
}
);
// if it is not an external URI, use Ajax load()
} else {
$('#target').load(url);
}
}
// filter out some nasties
function filterData(data){
**data = data.replace(/<body>/,'');** // INTERTED THIS ONE TO REMOVE body tag
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
});
Your main problem is that you are requesting data in XML format. Suggest changing your query string to format=json. That will return a javascript object that you can work with more easily.
Since you are already using jQuery I highly recommend the DataTables plug-in.
Here's a code snippet that illustrates the data formats returned from Yahoo. And the Yahoo Console is also very helpful when testing.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<button onclick="json()">GET JSON</button><button onclick="xml()">GET XML</button>
<textarea id="stdout" style="width:100%;height:40em;"></textarea>
<script type="text/javascript">
function json() {
var url = 'https://query.yahooapis.com/v1/public/yql?q=show%20tables&format=json&diagnostics=true&callback=?';
$.getJSON( url, function(data) {
document.getElementById('stdout').value = JSON.stringify(data,null,' ');
});
}
function xml() {
var url = 'https://query.yahooapis.com/v1/public/yql?q=show%20tables&format=xml&diagnostics=true&callback=?';
$.getJSON( url, function(data) {
document.getElementById('stdout').value = JSON.stringify(data,null,' ');
});
}
</script>
</body>
</html>
You may want to look at this library: https://github.com/IonicaBizau/jQuery-cross-domain-requests

Post Javascript to PHP and then retrieve in another javascript

I m trying to post the value from my java_post.js into php_post.php and then retrieve in another javascript page, index.html. So far i can post the value into the php_post.php and retrieve back into my java_post.js as alert(data)
but i cannot retrieve from my index.html
Java_post.js
var url_link ="index.html";
//On Click Select Function
$("#table_hot").on('click', 'tbody tr',function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
$.post('PHP_post/php_post.php',
{
postvalue:value
},
function(data){
alert(data);
}
);
});
//Window Pop Out Function
function hotspot_pop(url_link){
newwindow = window.open(url_link, '', "status=yes,
height=500; width=500; resizeable=no");
}
The value is retrieve when the client click the selected table and then post into the php_post.php. The php_post.php will filter the result and return to index.html.
$filtered_students = array_filter($ARRAY, function($row) {
$hotspot_value = $_POST['postvalue'];
if($row['name'] == $hotspot_value){
return true;
}
});
echo $filtered_students;
So now i m able to retrieve the value and post into as an alert for my java_post.js but the value is no pass into index.html and i receive the error for undefined postvalue.
<html>
<script src="js/jquery-1.11.1.min.js"></script>
<body>
<div id="result"></div>
<script>
var xmlhttp_user = new XMLHttpRequest();
var url_user = "PHP_post/php_post.php";
xmlhttp_user.onreadystatechange=function() {
if (xmlhttp_user.readyState == 4 && xmlhttp_user.status == 200) {
document.getElementById("result").innerHTML=xmlhttp_user.responseText; }
}
xmlhttp_user.open("GET", url_user, true);
xmlhttp_user.send();
</script>
</body>
</html>
So my problem is now, is there any method that allow me to show the value in index.html from php_post.php. As a reminder the alert(data) from java_post.js is just a testing purpose to show the value did post and return from php_post.php
The issue you're having is that when you pass the data into your PHP file and receive the data back in your JavaScript, the information only lasts as long as your current request.
To fix this issue, consider using PHP Session variables to store your data, so that you can retrieve it later.
Example:
// php_post.php
<?php
start_session(); // initializes session for persistent data
$filtered_students = array_filter($ARRAY, function($row) {
$hotspot_value = $_POST['postvalue'];
if($row['name'] == $hotspot_value){
return true;
}
});
$_SESSION["filtered_students"] = $filtered_students; // You can now retrieve this in
// Another PHP file
?>
Now in another file (you would switch your HTML file to get from php_get.php):
//php_get.php
<?php
start_session(); // Don't forget to start the session
echo $_SESSION['filtered_students'];
?>
More information here: http://www.w3schools.com/php/php_sessions.asp
You can set the desired value into PHP session while at php_post.php.
This way, you can retrieve the session's value on any page you desire.

Categories

Resources