producing a GET response to an ajax POST - javascript

In javascript I am POSTing with ajax and I need to get a reply from my Python program. The following code shows the javascript, but how does I produce the desired responseText from a GET on the Python side?
In this example I am want a Yes or No reply to a question for the user as to whether to change the name provided or not.
I understand how to receive the name and value in the python POST, but I don't know how to produce the response in the associated python GET.
function changeName(name,value){
var json = '[{';
json += '"name":"'+name+'",'
json += '"value":"'+value+'"}]'
loadDoc(json,"edit")
}
function loadDoc(data,url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", ("/"+url), true);
xhttp.setRequestHeader("Content-type", "text"); #or something
xhttp.send(data);
}
My typical response in Python GETs follows one of the following 2 patterns, but neither seems to allow me to reply in this case.
self.response.out.write(template.render( template_values))
return webapp2.redirect("/templatename/%s" % variable)
(No PHP or jquery, please.)

Related

Input stops working when I change value (Node.js)

I just want to insert value in text input on https://hordes.io/clans website.
When you natively enter there characters, all elements load automatically. But when I do this:
document.getElementsByClassName("navbtn")[0].value += "d"
It neither loads new results nor works at all when you try to do anything manually afterwards.
In case with document.getElementsByClassName("navbtn")[0].value += "" it continues working.
I tried another method to enter values there: clicking input field - returns undefined.
Is there any way I can search on this page? By the way I did it just in chrome snippet
I think I've found a decent solution. Their website makes a post request to their api --> https://hordes.io/api/claninfo/list.
You can pass json to specify which clan you want!
Like this:
POST: https://hordes.io/api/claninfo/list
PAYLOAD: {"name":"dmdw","order":1}
RESPONSE:
{"clans":[{"name":"Darkmetal Dwarfs","tag":"DmDw","level":9,"gold":"42141","faction":0,"members":"2","prestige":"9446"}]}
You can try the request on reqbin.com following this link with already filled in params: https://reqbin.com/oieogjuu
Generated code from reqbin.com:
var url = "https://hordes.io/api/claninfo/list";
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
var data = '{"name":"dmdw","order":1}';
xhr.send(data);

Why does JSON.parse work on Google developer tools, but not in my js file?

I've been using the code below to get what I think is a JSON string from the openweathermap API.
var request = new XMLHttpRequest();
request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?lat=12&lon=-50&APPID=myKey');
request.send();
var data = JSON.parse(request.responseText);
The JSON string when I access it directly is this:
{"coord":{"lon":-50,"lat":12},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":301.461,"pressure":1025.84,"humidity":100,"temp_min":301.461,"temp_max":301.461,"sea_level":1025.82,"grnd_level":1025.84},"wind":{"speed":6.68,"deg":80.5004},"clouds":{"all":32},"dt":1507680994,"sys":{"message":0.0025,"sunrise":1507712963,"sunset":1507755824},"id":0,"name":"","cod":200}
However, when I used JSON.parse(request.responseText), I get a syntax error -- Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse ()
But when I use parse on Chrome developer tools it works fine and I can access the values using their keys e.g. JSON.parse(data)['coord']['lon'] returns -50
You need to wait for the asynchronous response before trying to get the response's contents. Could be achieved this way:
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(request.responseText);
}
};

How do i retrieve the data from this xml page

So im trying to get all data to display back from the request but i cant get a response it just keeps giving me [object XMLDocument] or blank if i use .responseText
This is the request URL http://www.omdbapi.com/?t=Chef&plot=full&r=xml
This is the site http://www.omdbapi.com/
This is the code i am using
<button onclick="loadXML()">Run</button>
<p id="output"></p>
<script>
function loadXML() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("output").innerHTML = this.responseXML;
}
};
xmlhttp.open("GET", "http://www.omdbapi.com/?t=Chef&plot=full&r=xml", true);
xmlhttp.send();
}
</script>
All i need is a response returned and i can go from there but nothing i try is working :/
Thankyou for looking but i figured it out. I was receiving HTML tags and when i was outputting these tags they wouldnt show because they were echoing as HTML tags. The data was there just hidden. To resolve this i just saved the file instead, or it could be cleaned before outputting

How to write a JavaScript which returns the contents of a webpage as result when the URL is given

I want to write a JavaScript to return contents of a webpage when URL is given and enter those contents as a data in table?
The alert pop up is not working.
Return HTML content as a string, given URL. JavaScript function returns a blank screen.
Here is my code:
<html>
<head></head>
<body>
<script type="text/JavaScript"> function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
document.write(httpGet("stackoverflow.com/")); </script>
</body>
</html>
You can simply get contents of a webpage by using javascript's ajax
var contents="";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
contents=this.responseText;
}
};
xhttp.open("GET", "webpage.html", true);
xhttp.send();
Although you can also manipulate HTML you should make sure that webpage.html is showing the data in a valid format for you to easily manipulate. Like JSON, xml or anything else so that you can use the data in the contents variable and iterate over it for your insert statements.
The reason because its showing a blank screen is because of the cross origin policy. stackoverflow.com does not allow CORS(cross origin requests).
And one more thing,, Until and unless you are requesting from a relative Url, specify the address with the protocol name.
Like : 'stackoverflow.com' to 'http://stackoverflow.com'
So just change the address to your file and it will work fine. :)

Adding Datas via Javascript to existing JSON file on Server

I have following problem. I know that this is discussed quiet often, and i tried a lot of possibilities, but none is working up to now.
I have some datas in my javascript file, which i want to add to a already exsiting .json file on my server. I tried to do it the following way, but whenever i open the .json file after calling ajax_get_json(), no new datas are added.
function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open('POST', 'myyjson.json', true);
hr.setRequestHeader ("Content-type", "application/x-www-form-urlencoded");
var us = document.getElementById("firstname").value;
var msg= document.getElementById("message").value;
hr.onreadystatechange= function(){
if (hr.readyState == 4 && hr.status == 200){
var obj = JSON.parse(hr.responseText);
obj['participant'].push({"user": us, "message": msg});
var sendingObj =JSON.stringify(obj);
}
}
hr.send (sendingObj);
}
My myjson.json File has following structure:
{ "participant":[
{"user":"Steven", "message":" Hey,i m in!"},
{"user":"Tim", "message":" i wrote sth."},
{"user":"lukas", "message":"example"}
]}
Does anyone have an Idea what the problem yould be or is there a better way doing it?
Thanks in advance!
With javascript on client it's not possible to write JSON on server. If that would be possible, that would be kind of bad from the security perspective. You need to write JSON on server with what ever language you are using there (PHP, Java, javaScript). Then you call that server function from client with AJAX for example. It could go like this:
Javascript on client side request for example url www.yourserver.com/writejson.php?u=steven&m=Hi
On server you catch that request and write to JSON file. username is steven and message is Hi.
By the way, you have misunderstood XMLHttpRequest.send method. You are not sending data to be saved on server. You are firing XMLHttpRequest. Here is walkthrough how your code is executed:
function ajax_get_json(){
var hr = new XMLHttpRequest(); // 1.
hr.open('POST', 'myyjson.json', true); // 2.
hr.setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); // 3.
var us = document.getElementById("firstname").value; // 4.
var msg= document.getElementById("message").value; // 5.
hr.onreadystatechange= function(){ // 6.
if (hr.readyState == 4 && hr.status == 200){ // 8. this is called every time XMLHttpRequest state changes
var obj = JSON.parse(hr.responseText); // 9. this is called when XMLHttpRequest is completed and response is gotten
obj['participant'].push({"user": us, "message": msg}); // 10.
var sendingObj =JSON.stringify(obj); // 11.
}
}
hr.send (sendingObj); // 7. sendingObj is undefined

Categories

Resources