I'm new in Javascript and i'm trying to make an http request to fetch some data and display the results in html. I'm fetching the results and update the html code, but then the html code inside body reloads and shows the default values. My code is,
<head>
<script>
function httpGetAsync() {
var results = new Array(3);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
xhr.onreadystatechange = processRequest;
function processRequest() {
if (xhr.readyState == 4 && xhr.status == 200) {
// populate here results array
// i change the value with the following line
document.getElementById("title_1").innerText = "fetched_value";
}
}
}
</script>
</head>
<body>
<div class="search_btn">
<form id="search_form" method="get" onSubmit="return httpGetAsync()">
<input type="text" class="search" placeholder="Search" id="search">
<input type="submit" value="search" class="search_button">
</form>
</div>
<div id="one">
<p id="title_1">default</p>
</div>
</body>
The 'title_1' changes its text to 'fetched_value' but it then reloads and becomes 'default' again. What am i doing wrong?
It's because your onSubmit does not receive false. Simply add return false to httpGetAsync end
function httpGetAsync() {
var results = new Array(3);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.addEventListener(
"readystatechange",
function processRequest() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("title_1").innerText = "fetched_value";
}
},
false);
xhr.onreadystatechange = processRequest;
return false;
}
You need to prevent the default action on submit, which is to use the "action" attribute on the form element to reload the page (if it's not present the current page is reloaded).
function httpGetAsync(event) {
event.preventDefault();
...
}
Related
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);
}
I'm new to Javascript, can I use XMLHttpRequest() after I hit submit from form but the result should be the same as onclick event. I have a function named get and by using XMLHttpRequest() I can add a new object within the div sample, it works if it's a button. The only difference is that I want to add new object to the div sample without redirecting to http://127.0.0.1:5000/get?query=apple after I submit the form, form and function get() should be working together in this case. And also I don't want to see the http://127.0.0.1:5000/get?query=apple in the browser's url field after I submit the form. I need some help, I push myself to use pure js as possible and not to rely on jquery.
<div id="sample"></div>
<div onclick="get('apple');">CLICK APPLE</div>
<form action="/get" method="GET">
<input name="query">
<input type="submit">
</form>
<script>
function get(query) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("sample").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "get?query=" + query, true);
xhttp.send();
};
</script>
This is how you can interrupt submit event, and do whatever you want.
<div id="sample"></div>
<div onclick="get('apple');">CLICK APPLE</div>
<form id="form">
<input name="query">
<input type="submit" value="Submit">
</form>
<script>
document.querySelector('#form').addEventListener('submit', function(e){
e.preventDefault();
var query = e.target.elements['query'].value;
get(query);
});
function get(query) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("sample").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "get?query=" + query, true);
xhttp.send();
};
</script>
function get(query) {
console.log("Called Function");
query = document.getElementById('query').value;
console.log(query);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("sample").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "get?query=" + query, true);
xhttp.send();
};
<div id="sample"></div>
<div onclick="get('apple');">CLICK APPLE</div>
<form id="myForm" action="/get" method="POST">
<input type="text" name="query" id="query">
<input type="button" onclick="get()" value="Submit form">
</form>
You have user Form type method="GET" which changed to method="POST" and added onclick="get()" to call the function from javaScript
How do you insert the correct "xhr" value into the HTML5 button?
I am not sure how this whole XMLHttpRequest works. I believe it takes: xml data, text, numbers or null from the HTML5 button input and prints it out in text input in this case but can it store a value in it to call on it later. That is the question!
<script type="text/javascript">
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text"){
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
window.document.myform.xhr1.value = data;
return data;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200); {
window.document.myform.readBodyxhr.value = readBody(xhr);
}
else {
alert(xhr.status);
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);
}
</script>
...HTML5
<input type="button" name="XMLHttpRequest" value="XMLHttpRequest" onclick="readBody(xhr)" />
<input type="text" name="xhr1" value="" size="4"/></td>
<input type="text" name="readBodyxhr" value="" size="4"/></td>
Move call to .open() and .send() outside of onreadystatechange handler.
Substituted onload and onerror for onreadystatechange. ; following if condition is a syntax error. Note also, XMLHttpRequest with true passed at third parameter at .open() sets load handler to return results asynchronously.
<script type="text/javascript">
var url = "https://gist.githubusercontent.com/guest271314/6a76aa9d2921350c9d53/raw/1864137bfd2eb62705bd0e71175048a28b3253e6/abc.txt";
function readBody() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
window.document.myform
.readBodyxhr.value = xhr.responseText;
}
xhr.onerror = function() {
alert(xhr.status);
}
xhr.open("GET", url, true);
xhr.send(null);
}
</script>
...HTML5
<form name="myform">
<input type="button" name="XMLHttpRequest" value="XMLHttpRequest" onclick="readBody()" />
<input type="text" name="xhr1" value="" size="4" />
<input type="text" name="readBodyxhr" value="" size="4" />
</form>
We can call php directly from form action in html:
<form name='x' action = "filename.php">
in this case, php will receive all inputs in the form even we don't pass them.
Can we call js function from form action in html?
<form name='x' action = "javascript:jsFunction();">
Then, call the php from the js function?
jsFunction()
{ var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
}
Hint
I cannot use onsubmit because it log me out from the platform. in other words, it reload the platform from the beginning of the login page.
I am working on integration and I don't have a clear idea about the platform.
Edit 1:
Now, in the HTML file:
<form enctype='multipart/form-data' id = "myform">
<input type='submit' value='Basic search' onclick = "i2b2.BLAST.jsFunction();">
JS file:
i2b2.BLAST.jsFunction = function ()
{
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(event)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", blastresult.php, true);
xhttp.send();
event.preventDefault();
});
}
it reloads the platform from the beginning of the login page!
Edit2:
I put some alert to see if the button call the javascript.
i2b2.BLAST.jsFunction = function ()
{
alert('hi');
this.yuiTabs = new YAHOO.widget.TabView("BLAST-TABS", {activeIndex:1});//this two lines navigate to second tab
this.yuiTabs.set('activeIndex', 1);
alert('hi');
myForm.addEventListener('submit', function()
{
alert('hi');
preventDefault();
The button call the js and display first 'hi' then navigate to second tab then reload the page. It stop at the second 'hi'.
Any help is highly appreciated.
Thanks.
Yes you can, First give your FORM an id
<form id="myForm"></form>
then in javascript try this:
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(e)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
e.preventDefault();
});
Instead of:
<form name='x' action = "javascript:jsFunction();">
Use:
<form name='x' onsubmit="jsFunction();">
You can POST via AJAX as you have shown in your code:
function jsFunction(event) {
// prevent default event from taking place (submitting form to file)
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
}
Though you will need to serialize your data and pass it to xhttp.send(), it will need to be form url encoded like: key1=value1&key2=value2. You are probably better off using jQuery in the manner #mmm suggests.
I want to retrieve all elements from an ajax call, then insert them into another element without:
using jquery (I just want to use pure JavaScript)
creating a new element to contain the ajax response
Here's what I have tried:
index.php
<!DOCTYPE HTML>
<head>
<script type="text/javascript">
function loadPage() {
var ajax = new XMLHttpRequest();
ajax.open('GET', 'test.php', true);
ajax.onreadystatechange = function (){
if(ajax.readyState === 4 && ajax.status === 200){
document.getElementById('output').appendChild( ajax.responseText ) ;
}
};
ajax.send();
}
loadPage();
</script>
</head>
<body>
<div id="output">
<h1>Default</h1>
</div>
</body>
</html>
test.php
<h1>
its work
</h1>
<div>
<h2>
its work2
</h2>
</div>
I already googled it, but the answer was always to use jQuery.
Node.appendChild requires a Node object as an argument. What you're getting from test.php is a string. Try using innerHTML instead
document.getElementById('output').innerHTML = ajax.responseText;
As of XHR level 2, you can simply attach an onload handler to XHR instead of checking the readyState and status properties.
ajax.onload = function() {
document.getElementById('output').innerHTML += this.responseText;
}
have you looked at this
http://w3schools.com/ajax/ajax_examples.asp
http://w3schools.com/ajax/tryit.asp?filename=tryajax_first
I think the most of the examples that you find use jquery because jquery makes it cross browser
try this one
function loadPage(){
var strURL="test.php";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('output').value=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}