ajax call to mapped URL - javascript

I am trying to make an AJAX call to a localhost URL that I am hosting via java. The URL currently only holds a String.
But when I try to call it from my javascript, I don't get any return value. The code/URL doesn't even work.
Javascript code(For website):
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(true){
alert('hello!');
document.getElementById('newgame').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'localhost:8080/highscore', true);
xhr.send(null);`
JAVA class code(currently running):
#RestController
public class Server {
#RequestMapping("/highscore")
public String highScore() {
return "test";
}
}

Why you don't using jQuery instead, as below
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
req_url = "http://localhost:8080/highscore";
$.ajax({
type:"post",
url:req_url,
success:function(data){
alert('hello!');
document.getElementById('newgame').innerHTML = data;
}
});
});
</script>
</head>
<body>
</body>
</html>

Replace localhost:8080/highscore by http://localhost:8080/highscore

Related

http request with cookie in javascript

I'm trying to make a request with javascript but the cookie part seem to be not working. Code I'm using is below.
<script type = "text/javascript">
<!--
function SendReq(){
var request = new XMLHttpRequest();
var path="http://192.168.186.131/hello.html";
request.onreadystatechange=state_change;
request.open("GET", path, true);
request.withCredentials = true;
document.cookie="sessionid=d8e8fca2dc0f896fd7cb4cb0031ba249";
request.setRequestHeader("User-Agent", "Mozilla/5.0");
request.setRequestHeader("Cookie",document.cookie);
request.setRequestHeader("Accept-encoding",'deflate');
request.send(null);
function state_change(){
if (request.readyState==4){
alert('ready');
if (request.status==200){
alert('ok');
}
else{
alert("Problem retrieving XML data");
}
}
}
}
</script>
What could be the issue here? Are there better ways to get this done?

change p content with text file one

I'm coding my first website, now I'm trying to change a p content with the content of some text files, which contains long descriptions of what my site is about, actually I've tried many ways, like httprequest(), FileReader() and jquery get, but actually I haven't managed it,because I was running it locally and probably because of the wrong file position, so i created a new small code in witch I tried jquery get, I ran it on "web server for chrome" but it doesn't work.
this is the code:
<!DOCTYPE html>
<html>
<body>
<div><h2 id="demo">Lets change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
function loadDoc() {
$.get("hello.txt",function(data){
getElementById('demo').innerText= data;
});
}
</script>
</body>
</html>
when I load it, the p and the button are displayed, but when I click the button nothing happens; the .html and the .txt files are in the same folder.
I'have been stuck on it for many days, please help, and don't mark it as duplicate.
any help is appreciate.
You could try this out
<script>
function loadDoc() {
$.get("hello.txt",function(data){
document.getElementById('demo').innerHTML= data;
});
}
</script>
HTML:
<div><h2 id="demo">Lets schange this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<button type="button" onclick="loadDocWithHttp()">Change Content from Http request</button>
Using AJAX:
function loadDocWithHttp() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "hello.txt", true);
xhttp.send();
}
Try this
function loadDoc() {
$.ajax({
url : "hello.txt",
dataType: "text",
success : function (result) {
$("#demo").html(result);
}
});
}
First of all do one change in your script as mentioned below
function loadDoc() {
$.get("hello.txt",function(data){
$('#demo').html(data);
});
}
For that button you have to bind click with delegation method on()
$(document).on('click','<your_button_selector>', function(){
alert("hello") // replace and put your code here
});
Good Luck..!!
Instead of
getElementById('demo').innerText= data;
change to below line.
document.getElementById('demo').innerText= data;
Try this :
function loadDoc() {
$.get("hello.txt",function(data){
document.getElementById('demo').text= data;
});
}
or
function loadDoc() {
$.get("hello.txt",function(data){
document.getElementById('demo').innerHTML= data;
});
}
You can use jQuery Ajax function. The error attribute will be helpful to get the exception:
$.ajax({
url: "./seeds/hello.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
},
error: function (e){
//error print
}
});
1.can u browse http://url/hello.txt in your browner?
2.open the developer tools, does any errors show?
3.getElementById have to be used under document Object

Simple Python and Ajax Example How to Send Response with Python?

I am testing out some code with Python and Javascript trying to get an Ajax system set up. Basically I just want to input a word and have the python code send it back. Here is my html/javascript:
<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari/Chrome
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
<p>word: <input name="word" type="text">
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/ajaxtest")'></p>
<div id="result"></div>
</form>
</body>
</html>
and here is my python:
class AjaxTest(BlogHandler):
def get(self):
user = self.get_user()
self.render('ajaxtest.html', user = user)
def post(self):
user = self.get_user()
word = self.request.get('w')
logging.info(word)
return '<p>The secret word is' + word + '<p>'
#having print instead of return didn't do anything
When I do logging the word shows up correctly and when I hardcode str in:
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
It displays that correctly but right now without hardcoding it shows nothing. How am I supposed to send the response? I am using webapp2 as my Python framework and Jinja2 as the templating engine, though I don't think that has much to do with it. Do I need to send the HTTP headers?
If your problem is having difficulty returning a string from your post method, without rendering a template you can use the write method to accomplish that:
self.response.write('')
I believe you can change headers by just modifying self.response.headers

How can I parse a text file using javascript

The code below is to read a text file using javascript. it works.
However, I just want to read part of the content.
For example, the content of the file is :"Hello world!"
I just want to display "Hello".
I tried function split(), but it only works on strings. I don't know how to insert it here.
var urls = ["data.txt"];
function loadUrl() {
var urlToLoad = urls[0];
alert("load URL ... " + urlToLoad);
browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}
thank you!!!
I used
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
, and got data from my text file.
Or try this
JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.
Untested, but the general gist of it...
var HTML_FILE_URL = '/whatever/html/file.html';
$(document).ready(function() {
$.get(HTML_FILE_URL, function(data) {
var fileDom = $(data);
fileDom.find('h2').each(function() {
alert($(this).text());
});
});
});
Try this to read separate words if I understood correctly what you need.
Create a file with the contents "hello world" and browse to it with the example script.
The output is "hello".
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0]);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>
Reading directly has to be with an ajax request due to the javascript restrictions regarding safety.
This code shoudl perform the requested operation:
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState==4){
var words = xmlhttp.responseText.split(' ');
alert(words[0]);
}
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
Opening a file in javascript with ajax (without using any framework)
var urls = ["data.txt"];
xhrDoc= new XMLHttpRequest();
xhrDoc.open('GET', urls[0] , async)
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
}
}
}
xhrDoc.send() //sending the request

JavaScript + Querystring + div

How to load content in to a html page. please note IM not allowed to use php or C. Only javascript and html.
for example
load Page B in to Page A
http:myweb.com/index.html?load=pageb
thank you.
Issue an AJAX request to Page B
Get the contents using responseText
Display the contents inside a div using innerHTML property.
If you can use a js framework then I would suggest jQuery and #marcgg's answer will do it.
Just plain JavaScript:
<html>
<head>
<script>
function getUrlVars() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
return map;
}
function createRequestObject() {
var ro;
// Mozilla, Safari,...
if (window.XMLHttpRequest) {
ro = new XMLHttpRequest();
if (ro.overrideMimeType) {
ro.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) {
try {
ro = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ro) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
return ro;
}
function sndReq(param,server,handler) {
//location.href = server+"?"+action; //uncomment if you need for debugging
http = createRequestObject();
http.open('GET', server, true);
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
http.onreadystatechange = handler;
http.send(param);
}
handler_function = function()
{
if(http.readyState == 4)
{
if (http.status == 200)
{
document.getElementById("your_div_element").innerHTML = http.responseText;
}
else
{
alert('There was a problem with the request.');
}
}
}
</script>
</head>
<body>
<div id="your_div_element"></div>
<script>
var getvars= getUrlVars();
sndReq(null, getvars['action'], handler_function);</script>
</body>
</html>
html:
//Page A
<html>
<head><title>Page A</title></head>
<body>
<div id="pageB"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pageB').load('pageb.html')
});
</script>
</body>
</html>
Using jQuery:
$.ajax({
type: "POST",
url: "http://some.com/page.html",
success: function(msg){
alert( "here's your data: " + msg );
jQuery("#yourDivID").html(msg);
}
});
http://docs.jquery.com/Ajax/jQuery.ajax
edit: added how to put it into a div

Categories