Retrieve a variable from server using alert - javascript

this is my first attempt to retrieve a value using an alert box. Here what I am doing is having a file at the server and I want to retrieve that file value in an alert box.
Before that, I am able to get that value through a link. That working code is here-
<!DOCTYPE html>
<html>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "localhost:8080/TemperatureReading/", true);
xhttp.send();
</script>
<body>
test
</body>
Request data
</html>
Now, what am I trying to do is have that value in an alert box every time I hit that button.
That code is here---
First I added a return statement in the function so that a variable is returned inside it.
xhttp.send();
return variable;
Than, I added another function for alert box---
<script>
function myFunction() {
alert(variable);
});
</script>
and in the body, I added
<button onclick="myFunction()">Try</button>
But till now I am not succeeded in that.
I am not understanding what am doing wrong here.
Can anyone help me with this thing. Thank you in advance.
EDIT : I have edited the code. Also, I have to only create a HTML file. I am not generating the number. So, what I have to do is just give an HTML and with the help of retrieve value

Do this when you get the response:
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
if(window.localStorage){
window.localStorage.setItem['resp'] = JSON.stringify(xhttp.responseText);//set it here
}
}
now in the function where variable is required:
function myFunction() {
if(window.localStorage){
var resp = JSON.parse(window.localStorage.getItem['resp']); // get it here
alert(resp); // alert it here.
}
}

Related

Rapidapi Api request with XMLHttpRequest

this is my second post, I hope to be luckier than last time end get some reply. 🙂
I’m trying to make a Rapidapi api request working with javascript ”XMLHttpRequest”
I must say that the api works perfectly with ios siri shortcut.
this is the code provided from apirapit site on the "XMLHttpRequest" section:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://download-video-youtube1.p.rapidapi.com/mp3/medPORJ8KO0");
xhr.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "[my key here]");
xhr.send(data);
And this is my code:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", url);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "[my key here]");
xhttp.send();
}
</script>
</body>
</html>
Just to testing I created a simply bank html page to have the JSON response beneath the button just after pressing it. The result is just the string “ciao” i set before the this.responseText. If I remove the apikey or modify it with a wrong value an JSON error message appear ( so like the case posted, as I intentionally removed it).
Otherwise as said noting but “ciao” string
Is there any syntax error? Is there a logical reason why it behave like this?
Thanks
Franco
Trying adding a data variable as null. That's what RapidAPI provides in their code snippet.
function loadDoc() {
const data = null
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", URL);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "my key here");
xhttp.send(data);
}

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

How to trigger a variable/method in python from a html file with javascript

I want to have a hyperlink on a html page run a variable that is defined in my python file. The variable is going to clear my database. Here is the code I am trying to use.
Python
#app.route('/log')
def log():
cleardb = db.session.delete()
return render_template('log.html', cleardb=cleardb)
Html
<a onclick="myFunction()">Clear database</a>
Javascript
<script>
function myFunction()
</script>
I don't know what javascript I need to run the variable. I want to make the cleardb get triggered so that it will delete the database.
Thanks
You need to make an ajax request with javascript to /log, it would look something like this:
function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//Do Success functionality here
}
else if (xmlhttp.status == 400) {
//Handle 400 errors here
}
else {
//All other errors go here
}
}
};
xmlhttp.open("GET", "/log", true);
xmlhttp.send();
}

how to make when button click event in ajax

I want to make a page that the user put any word on textbox and returns all books with that word in (books is in mysql and i am gone to convert the query in xmlconvert.php)
<form id="keyword" >
<input type="text" name="value" id="book"/>
<br/>
<button onclick="showhint(functionvalue())">Search By Title</button>
</form>
there is the a function to get the word that user put and send it to ajax showhint();
<script>
function functionvalue() {
var bookname = document.getElementById('book').value;
return bookname;
}
</script>
there is the ajax code that get the responsetext from xmlconvert.php file where I got the q where is the word that user put and make a query with that word and return the books in xml
<script type="text/javascript">
function showhint(str) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("keyword").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET","xmlconvert.php?q="+str,true);
xmlhttp.send();
}
</script>
I don't know if my thought is correct let me know if I can do that and how is possible to make it.
Sorry my English is not so good
You are assigning your new XMLHttpRequest to the variable ajax but then calling its commands with other names. If you named it ajax, you need to do ajax.readyState, ajax.status, ajax.open, ajax.send, etc.
So this should work:
<script type="text/javascript">
function showhint(str){
var ajax=new XMLHttpRequest();
ajax.onreadystatechange=function{
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("keyword").innerHTML = ajax.responseText;
}
};
ajax.open("GET","xmlconvert.php?q="+str,true);
ajax.send();
}
</script>
Need to make the following changes:
ajax.onreadystatechange should be a function definition so include () after the function keyword
XMLHttpRequest should be referenced through ajax var.
So the correct code would be:
<script type="text/javascript">
function showhint(str) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("keyword").innerHTML = ajax.responseText;
}
};
ajax.open("GET","xmlconvert.php?q="+str,true);
ajax.send();
}
</script>

javascript in php and using ajax

I'm getting really confused with php,ajax and javascript.
I'm using some ajax code I got from w3 schools to handle a form and display it below the form input. However, I can't seem to get my php and Javascript right. I'm using JavaScript in php tags where I then Get my variable in the same php tags and echo it. I then try to get that variable in ajax. I don't think I'm correctly getting the variable with ajax and inside my php. Does anyone have some advice.
Thanks
Heres my javascript in my html doc
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "hackacronymphp.php?phpAnswer=" + str, true);
xmlhttp.send();
}
}
</script>
Here's the last part of my script with my php afterward all inside one php tag
var stringe = vari.join("");
console.log(stringe);
var answer = dataarray[stringe];
console.log(answer);
</script>
$phpanswer = $_GET['answer']
echo $phpanswer ;
?>

Categories

Resources