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;
}
}
Related
I am calling a php file that queries my database and returns a result. I have verified that the php file accurately returns the data as needed, but my calling page is not updated from the JavaScript.
What do I need to alter in my syntax below so that the returned value is returned on page?
<script type="text/javascript">
function boostion()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("data").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
EDIT
I have also opened Developer Options in Chrome and checked the Console and there are no errors or issues displayed, everything is a success!
Edit 2
I tried to use the JQuery approach below and used this syntax - but I get the error
Uncaught TypeError: $(...).load is not a function
Syntax:
<script src="https://code.jquery.com/jquery-3.1.1.slim.js"
integrity="sha256-5i/mQ300M779N2OVDrl16lbohwXNUdzL/R2aVUXyXWA="
crossorigin="anonymous" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
document.getElementById("data").innerHTML = data;
});
});
</script>
Edit 3
This is my php syntax that runs the sql syntax and echo result that I want to have returned from the javascript
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'host';
$option['user'] = 'user';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance( $option );
$result = $db->getQuery(true);
$result->select($db->quoteName(array('trackandfieldresults')));
$result->from($db->quoteName('[TrackData]'));
$db->setQuery($result);
$row = $db->loadRowList();
echo $row['0']
?>
Use xhr.send();
If it is a GET request, you have to apply the query string in in xhr.open and you dont have to set Content-type:application/x-www-form-urlencoded
first, the scripts should be inside the HTML before the ending body tag. then you open another file and write your code in it. JQUERY does not have script tag. Sp you are creating an external javascript file for the script. No script tag needed. Now use this format.
$(window).on('load', function(e){
e.preventDefault();
var dat = //the content you are trying to load
$.get('middleware.php', dat, function(data){
$('#selector').html(data)
});
})
I have a faster approach using JQuery.
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
//Do whatever you want here
});
});
This should do the Job. Your approach is old and kind of complicated to debug
Try this
function boostion(){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.send();
xhr.onreadystatechange = function(){
console.log(xhr);
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("data").innerHTML = xhr.responseText;
}
}
}
<div id="data"></div>
<button onclick="boostion();">Load</button>
Here is my code in javascript
<script type="text/javascript">
startingListener();
function startingListener() {
setInterval(function(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.send();
var result = xhr.response;
console.log(result);
}
}, 100);
}
</script>
And my server on Java
public static void main (String... args) throws IOException, Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(32081);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true);
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
System.out.println("begin");
outToClient.println("fu");
System.out.println("Received: done");
}
}
I just want to receive answer string in JS and work with it further.
So when I run server and run JS, they connected and I received in IDE send() from JS
After that I saw in console of Java that begin and done received, but in browser console I didn't see any answer and script just handled. What do I do wrong?
Thank you for your help
Your client code is missing a state change handler and using setInterval with 100 ms it is very heavy on the server. Here is a better JS. Your JAVA issue is another problem. Downvoters: Do comment
function listener() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
}
}
listener();
If you want to call listener repeatedly, you can do
function listener() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
if (xhr.responseText != "done") {
console.log("server still busy");
setTimeout(listener,1000); // repeat the call
}
else {
console.log("finally done");
}
}
}
}
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 a form that is supposed to display a feedback message from the server once it is submitted in <div id="resposta"></div>
I can't use JQuery on my page because it is also using Mootools and it's really a mess to avoid the conflicts with those two (I tried all sorts of things I don't to bother you with). Therefore, I must use pure JavaScript here.
Once the form is submitted (after validation) it calls the function getResposta below:
function getXmlHttp() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
};
function getResposta(){
var resposta = document.getElementById("resposta");
var request = getXmlHttp();
request.open("POST", "thanks.php", true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if (request.readyState != 4) return;
if (request.status == 200) {
resposta.innerHTML = '<p>' + request.responseText + '</p>';
} else {
alert("Erro: "+request.statusText);
}
};
}
}
thanks.php:
<?php
echo "thank you";
?>
It seems that thanks.php isn't being called, although the form is correctly filled in and sent to the server.
I've tried typing in the absolute path to the file but it didn't work. So, what is wrong with this code?
Thanks for any help!
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;
}
}
}