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.
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 have two simple pages.
test.php:
<div id="demo"></div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "sse.php", true);
xhttp.send();
}
var myVar = setInterval("loadDoc()", 2000);
</script>
sse.php
<?php
echo time();
?>
Problem is - in my private PC - it works perfect.
every 2 seconds, sse.php is pulling, and demo-div changes accordingly.
BUT, in my Bluehost website, same script - doesn't work.
it pulls one time (after two seconds) and that's it - no more.
Funny thing is, if i refresh the sse.php manually (in another tab)
the demo div content does change!
I tried to figure out what's the issue, but i'm out of ideas.
Any ideas?
Thank you.
After further research - adding those lines in the top of my sse.php file and refresh this page, solved my problem. Thanks.
<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
echo time();
?>
I had a similar problem which I described here:
AJAX function request stops previous load when called again - no jQuery please
Go get that code I wrote and check if works for you.
EDIT:
A call would be:
ajaxGetData('http://whateverurl.com', 'containerObjectId');
And the supporting functions:
function ajaxGetData(url, objId)
{
var request;
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e)
{
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e) {}
}
}
if (!document.getElementById(objId))
{
return false;
}
var obj = document.getElementById(objId); /* <= fix: added var */
ajaxLoadingIndicator(obj);
/* YOU MAY NOT NEED TO ADD/USE EVENT HANDLERS */
request.addEventListener("progress", function(event){ajaxCallBack(event, obj)}, false);
request.addEventListener("load", function(event){ajaxCallBack(event, obj)}, false);
request.addEventListener("error", function(event){ajaxCallBack(event, obj)}, false);
request.addEventListener("abort", function(event){ajaxCallBack(event, obj)}, false);
request.onreadystatechange = function()
{
if(request.readyState === 4)
{
if(request.status === 200)
{
obj.innerHTML = request.responseText;
}
else
{
obj.innerHTML = '<div id="'+id+'">Error loading data.</div>';
}
}
};
/* in my case i'm using asynch AJAX request (true) */
request.open('GET', url, true);
request.send(null);
}
/* YOU CAN GO AND SHOW FANCY LOADERS HERE */
function ajaxLoadingIndicator(obj)
{
idBase = obj.id.split("_");
id = idBase[0]+"_ajax_loading";
obj.innerHTML = '<div id="'+id+'">Loading</div>';
}
/* IF YOU DONT WANT EVENT HANDLERS, YOU DON'T NEED THE FOLLOWING FUNC */
function ajaxCallBack(e)
{
// Handle each event
switch(e.type)
{
case 'error':
{
idBase = obj.id.split("_");
id = idBase[0]+"_ajax_error";
obj.innerHTML = '<div id="'+id+'">Server unavailable. Error loading data.</div>';
} break;
}
}
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.
I am trying to write a streamlined version of a XMLHttpRequest demo script shown here:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
I'm only going to use this on iPad, so I don't have to check for older versions of IE, and so on. On button click, I want to check if the connection exists. Here's my entire html page, including JavaScript snippet:
<html>
<head>
<script>
var myURL = "http://www.google.com";
function testConnection(url) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("Connected!");
} else {
alert("Not connected!");
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="testConnection(myURL)">Test Connection</button>
</body>
</html>
For some weird reason, even though I'm online, when I click the button, I get repeated "Not connected" alerts, and only after a while I get the "Connected" alert, followed by no alerts.
Looks like I messed up, but I can't see where. What should I change to make it work?
If you can use xhr2, you can learn stuff from this tutorial and rewrite your code to something like this:
function testConnection(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() { alert("Connected!"); }
xmlhttp.onerror = function() { alert("Not Connected"); }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
If you send request to another domain, you may get error even if it exists, if the target server has Same-Domain-Policy restriction (default). If the target server is on another domain, it must send header
Access-Control-Allow-Origin: *
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>