I'm trying to get two values (x and y) from a javascript (Virtualjoystick.js) and pass them to a (prototype.js) Ajax script. I've been reading through similar questions and answers both here and on other websites but I'm not really 'getting it'! Any help would be greatly appreciated.
Here is a simplified version of what I have so far.
<html>
<head>
<script src="JavaScripts/prototype.js"></script>
<script src="JavaScripts/virtualjoystick.js"></script>
</head>
<body>
<div id="info">
<span id="result"><b>Joystick:</b> X:0 Y:0</span>
</div>
<div id="container">
<canvas height="300" width="300"></canvas>
<canvas height="300" width="300"></canvas>
<script>
console.log("touchscreen is", VirtualJoystick.touchScreenAvailable() ? "available" : "not available");
var joystick = new VirtualJoystick({
container : document.getElementById('container'),
mouseSupport : true,
stationaryBase: true,
baseX: 150,
baseY: 150,
limitStickTravel: true,
stickRadius: 100
});
joystick.addEventListener('touchStart', function(){
console.log('down')
})
joystick.addEventListener('touchEnd', function(){
console.log('up')
})
setInterval(function(){
var outputEl = document.getElementById('result');
outputEl.innerHTML = '<b>Result:</b> '
+ ' X:'+parseInt(joystick.deltaX())
+ ' Y:'+parseInt(joystick.deltaY())
}, 1/30 * 1000);
</script>
</div>
<div>
<form>
<input type="button" value="On" onClick="go('60.30')" style="font-size:200%;"><br />
<input type="button" value="Off" onClick="go('0.0')" style="font-size:200%;">
</form>
<script type="text/javascript">
function go(qry) {
new Ajax.Request('motor_control.py?q='+ qry,
{method: 'GET'}
);
}
</script>
</div>
</body>
</html>
What I need is parseInt(joystick.deltaX()) and +parseInt(joystick.deltaY()) from the virtualjoystick.js script to be written to the end of the Ajax.Request. Something like:
new Ajax.Request('motor_control.py?q='+parseInt(joystick.deltaX())
+ '.'+parseInt(joystick.deltaY()),
I tried that but it didn't seem to work!
As you can probably tell JavaScript is a foreign language to me, so any help at all would be appreciated.
If you are wanting to use plain JavaScript you can use something like the example below. You will have to remember that when using AJAX type function that you will only be able to perform operations on the data retrieved by the function from inside a call back or promise function. Click on the following link to see the Ajax function in action.
Live Example
JavaScript:
//path to the file you are sending and retrieving data
//this will differ from the Plunker link code because
//I do not have access to the url in your example.
var url = "motor_control.py?q='+ qry";
//call get Ajax function
get(url,function(data){//begin call back function
//do something with data variable here
//change the innerHTML of the example id element.
document.getElementById("example").innerHTML = "I was rendered by an AJAX function!"
});//end call back function
function get(url,fn){//begin ajax function
var contentType;
//variable to hold the xmlhttp object
var xmlhttp = null;
//if the browser contains the object
if(window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
//create a new XMLHttpRequest object
xmlhttp=new XMLHttpRequest();
}
//add the event listenter
xmlhttp.onreadystatechange = function(){
//if the status of the request is good
if (xmlhttp.readyState===4 && xmlhttp.status===200){//begin if then
//get the response text and store it in the data variable
var data = xmlhttp.responseText;
//call the callback function
fn(data,fn);
}//end if then
};//end function
//open a the http request
xmlhttp.open("GET",url,true);
//set the request header
xmlhttp.setRequestHeader("Content-type",contentType);
//send the the request
xmlhttp.send();
}//end get function
Related
want to create a fully dynamic chat UI for my website, But it reloads the whole page if a person submits the button page should not reload like many chat website.
<form action="action.php" method="post" id="formpost">
<input type="text" id="input" value="php echo">
<input type="submit" value="send">
</form>
I want to submit this form through ajax and show the last xml <message> containing <message>talk 123<message>
<messages category="short">
<person1>
<time>
r
<message>Djssjs</message>
</time>
</person1>
<person2>
<time>
r
<message>1234fdg</message>
</time>
</person2>
<person1>
<time>
r
<message> talk 123</message>
</time>
</person1>
</messages>
i want to show that talk 123 in the html document bit confused how to do that
//for form submit
$("#formpost").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: action.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
//for xml
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "name.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var msg = "";
//how to select the last person's of the <messages> child
msg = getElementsByTagName("messages").lastChild.childNodes[1].nodeValue ;
document.getElementById("demo").innerHTML = msg;
}
$("#formpost").on('submit', function(event){
event.preventDefault();
// rest of your ajax code here...
});
Points to note
1. Make sure you have also added JQuery script source on the head tag of your chat page.
2. Make sure to put preventDefault() immediately before any other code is executed.
You can use reverse ajax method pulling data from the server.
In reverse ajax a request is auto-generated at a certain time interval or hold the request for fetching new message.
There are three technologies for reverse ajax:-
Piggyback
Polling
Comet
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)
I am using java script after making an ajax call to display the data in a div with new JS content. Please refer to the code below:
//ajax call from a.jsp
var goUrl = "/testMethod/getTestMethod;
var httpRequest=null;
var refreshContent = "null";
httpRequest = XMLHTTPObject();
httpRequest.open("POST", goUrl, true);
httpRequest.onreadystatechange = function () {ajaxFunction(refreshThisDiv,httpRequest); } ;
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(null);
function ajaxFunction(refreshThisDiv,httpRequest){
var serversideValidation = true;
if (httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
results = httpRequest.responseText; // http.responseXML; which will lead to an XML based response, if we were to have some XML output from a server file
if(results != 'null') {
var test= document.getElementById(refreshThisdiv);
test.style.display = '' ;
test.innerHTML = results;
}
//Below is in b.jsp which is new content to display.
<div id="test">
</div>
<script>
var test = document.getElementById("test");
test.innerHTML ="HI";
</script>
Results are coing fine and redirecting to the b.jsp and displaying the html content. But tags are not working :(
I want to see Hi after ajax call is completed for that div. Please help me.
The ID is not #test, but test. #test is a selector that you'd use with jQuery, CSS or document.querySelector. document.getElementById requires, unsurprisingly, the ID. :)
getElementById() just needs the name of the ID. You incorrectly used CSS-ish syntax by passing #test where only test is needed.
Corrected new code:
<div id="test">
</div>
<script>
var test = document.getElementById("test");
test.innerHTML ="HI";
</script>
The code below is commented throughout. It is my understanding that I'm retrieving the JSON data and passing it to the 'results' div in my HTML view. This actually returns nothing, and it's difficult to debug because I can't output anything to the console.
// Here is how the final url should look:
// api.openweathermap.org/data/2.5/weather?q=Chicago&APPID=2e76bb25aa22d34ca062d764f4f3114b
var weatherSearch = '';
// weather-search is my html form id. On submit, send the input
// (which is city name) to the function getWeather.
$('#weather-search').submit(function(event) {
weatherSearch = $('#weatherQuery').val();
event.preventDefault();
getWeather(weatherSearch);
});
// getWeather has params q (city name), and APPID (API key).
function getWeather(weatherSearch) {
var params = {
q: weatherSearch,
APPID: '2e76bb25aa22d34ca062d764f4f3114b'
};
// This is the url that goes before the params.
url = 'http://api.openweathermap.org/data/2.5/weather/';
// Request data using url and params above.
// Does $.getJSON format the url properly?
$.getJSON(url, params, function(data) {
// Pass JSON data to showWeather function.
showWeather(data.items);
});
}
function showWeather(weather) {
// Show JSON data (weather) in html div id="weatherResults"
$('#weatherResults').html(weather);
}
Here is the associated HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>weather</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="openweather.js"></script>
</head>
<body>
<form id="weather-search">
<input type="text" value="" id="weatherQuery" />
<input type="submit" />
</form>
<div id="weatherResults">
</div>
</body>
</html>
Here's a codepen for the program
This answer demonstrates multiple ways to request and view data.
The code snippet below queries the web service using either jQuery or plain javascript. The returned data is displayed on the screen using JSON.stringify() and Google Prettify. The data is also sent to the console. Interestingly, the OpenWeatherMap service makes a good guess when the city name is misspelled.
The problem with OP's code appears to be this line: showWeather(data.items); which tries to display an object as html.
Run the snippet to try
var url = 'http://api.openweathermap.org/data/2.5/weather?APPID=2e76bb25aa22d34ca062d764f4f3114b';
// plain javascript version
function getWeather(city) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url + '&q=' + city, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
showData( data );
}
}
xhr.send();
}
// jQuery version
function getWeather2( city ) {
$.getJSON(url + '&q=' + city, showData );
}
// display json weather data
function showData( data ) {
window.city.value = data.name;
window.stdout.innerHTML = JSON.stringify(data, false, ' ');
window.stdout.className = 'prettyprint';
PR.prettyPrint();
if (window.console) window.console.log( data );
}
// sample data
getWeather('Berlin');
input {border: 1px solid black;}
button {width: 8em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/run_prettify.js?autoload=false&skin=sunburst&lang=js"></script>
Enter City: <input id="city" >
<button onclick="getWeather(window.city.value)">Use JS</button>
<button onclick="getWeather2(window.city.value)">Use jQuery</button>
<pre id="stdout" class="prettyprint"></pre>
You can use console.log or the dom to print messages for debugging. You can run a callback like this to find out if a request fails, this will tell you more infomation:
$.getJSON(url, params, function(data) {
// Pass JSON data to showWeather function.
showWeather(data.items);
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
Using the complete URL (http://api.openweathermap.org/data/2.5/weather/?q=Chicago&APPID=2e76bb25aa22d34ca062d764f4f3114b) directly in a browser returns some JSON with data about chicago -- but that JSON does NOT contain an item property. Thus, your data.items is null and nothing is shown.
Just check what you actually get from the browser and adopt your code accordingly (e.g. data.name would give you "Chicago", or simply use showWeather(data); to show all JSON you got).
I have a heroku website with ruby, but my issue is with one page in particular. The issue with that page is javascript. The page also has ajax on it. Here is my page:
<!DOCTYPE html>
<html>
<head>
<script>
var refreshDelay = 5000000;
function createRequestObject() {
var ro;
if(navigator.appName == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq() {
var newParent = document.getElementById('2');
var oldParent = document.getElementById('target');
while (document.getElementById('target').childNodes.length > 0) {
newParent.appendChild(document.getElementById('target').childNodes[0]);
}
http.open('post', '/chatContent?n=<%=#name%>');
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
var newParent = document.getElementById('2');
var oldParent = document.getElementById('target');
while (document.getElementById('target').childNodes.length > 0) {
newParent.appendChild(document.getElementById('target').childNodes[0]);
}
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('target').innerHTML = response;
setTimeout(sndReq(), refreshDelay);
}
}
setTimeout(sndReq(), refreshDelay);
</script>
<script>
scrollDown = function() {
document.body.scrollTop = document.body.scrollHeight;
}
</script>
</head>
<body onload='scrollDown()'>
<div id='2'>
</div>
<div id='target'>
<%=#chat%> <!-- #chat is a variable from my ruby file -->
</div>
<form action="/addChat?n=<%=#name%>" method='post'>
<input name='nchat' type='text' autofill='no' style='width:100%;height:10em;vertical-align:top'>
<input type='submit'>
</form>
<a href='/home'>Go home!</a>
</body>
</html>
When I load the page, it gives me this error in the console regarding line 24:
Uncaught TypeError: Cannot read property 'childNodes' of null
But when I enter into the console document.getElementById('target').childNodes.length it gives me however many nodes there are (it changes dynamically). What is going on??
Any extra things you want to see to answer this question I will try to promptly post. Just ask!
You are calling setTimeout(sndReq(), refreshDelay); which will execute sndReq() immediately because of the way you pass the function to setTimeout.
Since your sndReq() is in your head, the HTML will not have fully loaded yet so you are receiving the selector error because the element doesn't exist (yet).
You can change setTimeout(sndReq(), refreshDelay); to setTimeout(sndReq, refreshDelay); to pass the function reference to setTimeout so sndReq() doesn't fire immediately.
Ref: setTimeout