I have a problem: I'd like to have a double Ajax request, but I can't.
For example I have a page in PHP (rand.php) which returns a random number.
Code:
<?php
$rand = rand(0,10);
echo $rand;
?>
In an other page I want to create an Ajax request which get a random number from rand.php twice and write it in different div.
<head>
<script type="text/javascript">
http = new XMLHttpRequest;
function rando(div){
http.onreadystatechange = function(){
if (http.readyState == 4 && http.status == 200){
document.getElementById(div).innerHTML = http.responseText;
}
}
http.open("GET","rand.php",true);
http.send();
}
</script>
</head>
<body>
<div id="div1"></div><br />
<div id="div2"></div><br />
<button onclick="rando('div1');rando('div2')">Randomize!</button>
</body>
It doesn't work. Help me, please!
Yeah, as others have pointed out, your http is shared between all callers to rando. You should create a new one inside rando.
As an aside, that wont work on all browsers. You need to create a different type of http request object on early versions of Internet Explorer.
You have to initialize XMLHttpRequest every time you want to call rand.php:
<head>
<script type="text/javascript">
function rando(div)
{
var http = new XMLHttpRequest;
http.onreadystatechange = function()
{
if (http.readyState == 4 && http.status == 200) {
document.getElementById(div).innerHTML = http.responseText;
}
}
http.open("GET","rand.php",true);
http.send();
}
</script>
</head>
<body>
<div id="div1"></div><br />
<div id="div2"></div><br />
<button onclick="rando('div1');rando('div2')">Randomize!</button>
</body>
Related
As a learning exercise I'm trying to retrieve the track_artist_name from a url used by a radio sation to show the song being played.
This could be a case of "Same-Origin-Policy" but I dont have enough knowledge to tell.
Could someone please help me to workaround the conflict ? Also, I know "this.responseText" will show everything, I will try to filter it once I can retrieve the Data, but if you feel generous and want to trow me also that bone, I will be really grateful to you. Thank you : )
<html>
<body>
<div id="data">
</div>
<button type="button" onclick="loadXMLDoc()">Get Data</button>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "http://np.tritondigital.com/public/nowplaying?mountName=XERC_FM&numberToFetch=1", true);
xhttp.send();
}
</script>
</body>
</html>
I am trying to get HTTP 201 response from this code but I can't get. Please help me in solving the problems related to this code.
<html>
<body>
<center>
<h2>PAY</h2>
<div id="demo">
<button type="button" onclick="lol()">payhere</button>
</div>
<script>
function lol() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 | this.status == 201) {
document.getElementById("demo").innerHTML = alert(this.responseText);
}
};
xhttp.open("GET", "https://api.test.com/cors", true);
xhttp.withCredentials = true;
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send(JSON.stringify('{"returnUrl":"x","cancelUrl":"x","offerCredit":false,"experienceProfile":{"brandName":"test.com","noShipping":"true","addressOverride":false},"testLibraryVersion":"test/web/3.31.0","_meta":{}'));
}
</script>
</body>
</html>
Thanks
Http status in the form 2xx are really not something to be wished at client side. It is a response code that is sent by server depending on how it's coded there. 201 mainly means created but I can return 200 instead saying a Ok meaning whatever the code was supposed to do has been done. The error normally occurrs when there are missing headers or the content you sent is not correct. Please add accept header in your code like below:
xhttp.setRequestHeader("Accept", "application/json");
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 ;(
}
I have been reading up on Ajax and am following along on W3Schools.com. I am using Ajax/PHP/MySQL. So far I've gotten the request to successfully query my database based on a button selection, however it's reprinting my entire page when I click on one of the buttons.
Here is the Ajax code:
<script>
function statusShow(status) {
if(status == "") {
document.getElementById("exams").innerHTML = "";
return;
} else {
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("exams").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "rspamanager.php?st="+status, true);
xmlhttp.send();
}
}
</script>
And this is part of the PHP that is printing a table
if(isset($_GET["st"])) {
$st = mysqli_real_escape_string($connection, $_GET["st"]);
} else {
// default status
$st = "open";
}
if($connection) {
$query = "SELECT * FROM exams WHERE status = '{$st}'";
$sth = mysqli_query($connection, $query);
while ($result = mysqli_fetch_assoc($sth)) {
etc ...
This is all in the same php file "rspamanager.php".
EDIT: Button code:
<button onclick="statusShow(this.value)" value="open" class="status_open">Open</button>
<button onclick="statusShow(this.value)" value="closed" class="status_closed">Complete</button>
My test document seems to work just fine, added no-cache options, otherwise seems ok.
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<script>
function statusShow(status) {
if(status == "") {
document.getElementById("exams").innerHTML = "";
return;
} else {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "test.txt", true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.setRequestHeader("Pragma", "no-cache");
xmlhttp.setRequestHeader("Cache-Control", "must-revalidate");
xmlhttp.setRequestHeader("Cache-Control", "no-cache");
xmlhttp.setRequestHeader("Cache-Control", "no-store");
xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
xhttp.send();
}
}
</script>
</head>
<body>
<div id="exams">test</div>
<button onclick="statusShow(this.value)" value="open" class="status_open">Open</button>
<button onclick="statusShow(this.value)" value="closed" class="status_closed">Complete</button>
<div id="demo"></div>
</body>
</html>
Try changing
xmlhttp.open("GET", "rspamanager.php?st="+status, true);
to
`xmlhttp.open("GET", "rspamanager.php?st="+status+"&" + Math.random() + '=' + Math.random() * Math.random(), true);`
and see if that makes a difference.
If that works, you can leave it like that but should consider adding headers to prevent caching.
Thank you for everyone's help, it was a silly mistake. I ended up putting all of the code to generate the table in a separate file to call and it worked. Not because of the separate file, it just made me understand the request a bit better.
xmlhttp.open("GET", "ajax.php?st="+st, true);
My problem was that I had my PHP script that was being called hard-coded into the page, so it was written, and then written again when called. Copy/pasting all the hard-coded PHP script into a separate file fixed this and made it easier to understand.
Julie mentioned that the script was simply giving me a full page instead of just the section I needed which made the solution click with me.
Also, thank you Bryan for the suggestion to use no-cache options.
I have tried everything suggested in questions of similar nature but this very basic code is just not working. I just want to receive the message from the php code in the same file using XMLHttpRequest.
<!DOCTYPE html>
<head></head>
<body>
<div id="qwer" style="height:50px;width:40px"></div>
<script type="text/javascript">
function check() {
var ualias=document.getElementById('ualias').value;
var resu=document.getElementById("qwer");
var params="username="+ualias;
var hm = new XMLHttpRequest();
var url = "http://'my-domain-name'/try.php";
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
hm.send(null);
resu.innerHTML="CHECKING...";
}
}
</script>
<?php if(isset($_GET['username'])) {
$u=$_GET['username'];
echo $u;
exit();
} ?>
<input id='ualias' type='text' onblur=''>
<button type='button' onclick="check()">Go!</button>
</body>
</html>
The browser (Google Chrome) isn't showing anything for the onclick event.
It finally worked. I made the following edits.
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function check()
{
var ualias=document.getElementById('ualias').value;
var resu=document.getElementById("qwer");
var params="username="+ualias;
var hm = new XMLHttpRequest();
var url = "http://www.websamaj.in/try.php";
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200)
{
var return_data = hm.responseText;
resu.innerHTML=return_data;
}
}
hm.send(null);
resu.innerHTML="wait...";
}
</script>
<?php
if(isset($_GET['username']))
{
$u=$_GET['username'];
echo $u.",you are finally here!:)";
exit();
}
?>
<input id='ualias' type='text' onblur=''>
<button type='button' onclick="check()">Go!</button>
<div id="qwer" style="height:50px;width:100px;background-color:#CCC;"></div>
</body>
</html>
Apparently, the else condition there in onreadystatechange function was causing a problem. I would love it if anybody could tell me why exactly was that creating a problem. As far as i know, onreadystatechange event is called each time the state changes. So in my previous code, "error" should be overwritten thrice on the div and then, when the state changes to 4 and 200, the responseText should be overwritten, since i didnt use append. So, an explanation would be highly acknowledged. Thank you!
In your original code, hm.send(null) and resu.innerHTML="CHECKING" lines are actually INSIDE the onreadystatechange callback:
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
hm.send(null); // <-- wrong place!
resu.innerHTML="CHECKING...";
}
In your edited version, you moved them out of there (fixed indention):
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
}
hm.send(null);
resu.innerHTML="wait...";
The reason you didn't notice this is because in your edited version, you didn't indent your blocks correctly. Recommend always keeping your code formatted consistently, even when hacking around, so you can see the code blocks.