javascript with XMLHttpRequest not working - javascript

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.

Related

Retrieve a variable from server using alert

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.
}
}

Ajax GET Request is duplicating page

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.

Fetch result from database when link clicked

I'm using this HTML code;
if ($forum['type'] != 'c' && !$forum['linkto'] && $forum['posts'])
{
$forum['collapsed_image'] = '
<div class="expcolimage">
<a id="forum_name" fid="'.$fid.'">
<img src="images/collapse_collapsed.gif" id="ann_'.$forum['fid'].'_img" class="expander" alt="[-]" title="[-]" />
</a>
</div>';
}
else
{
$forum['collapsed_image'] = '';
}
What I want to do is to make it so when this link is clicked then an sql query should be run on a PHP page which fetches a result from database show that result in a <div> on an HTML page (or to show that result just under that link on the same page)
Due to limited knowledge in javascript I'm unable to code a javascript function which do that process, can you please provide me an example? I'll be very thankful to you.
Thank you!
PLEASE NOTE: I only want to use javascript and not jQuery
This is how you can do this:
test.php - the entire script is to be placed on this single script.
<?php
// Handle GET Request
if (isset($_GET['loadData']) && isset($_GET['id']))
{
// Dummy Response
// you should query the database here
exit("hello #". $_GET['id']);
}
?>
<script type="text/javascript">
function ajaxCall(url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function loadData(id)
{
ajaxCall('test.php?loadData&id='+ id, function(result) {
document.getElementById('result').innerHTML = result;
});
}
</script>
Click any of these links: <br>
Result: <div style="display: inline;" id="result"></div>
<br><br>
<?php
// this is your initial database query result with links
for ($i = 1; $i <= 3; $i++)
{
echo "• Hello, I am #$i. <a href='#' onclick='loadData($i);'>Click here<a> to load data.<br>";
}
?>
Demo:
The problem here is the way you're creating your html object. By doing it in one line you can't attach a listener for the click event.
I suggest to create elements in the javascript style:
var container = document.createElement("div");
container.className = "expcolimage";
var link = document.createElement("a");
link.setAttribute("fid", $fid);
var img = document.createElement("img");
img.src = "images/collapse_collapsed.gif";
img.id = "ann_" + $forum['fid'] + "_img";
img.className = "expander";
link.appendChild(img);
container.appendChild(link);
$forum['collapsed_image'] = container;
link.click(function(event){
event.preventDefault();
//AJAX code
});
Then I suggest you to look at these examples for choosing the best for you:
http://www.w3schools.com/ajax/ajax_examples.asp

Javascript function is not defined, ReferenceError

I'm just trying to execute an Ajax request but instead end up having a ReferenceError: getData is not defined on Console. And this piece of code worked fine 6 months back or so. I've already referred some previously asked questions but no good.
Here's the code:
<html>
<head>
<script language = "text/javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<form>
<input type = "button" value = "Fetch the message"
onclick = "getData('data.txt', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched message will appear here.</p>
</div>
</body>
</html>
Your browser doesn't know what language "text/javascript" is. It only knows the language "javascript" and the MIME-type "text/javascript". You're mixing the two up.
You could either change it to language="javascript" or type="text/javascript".
<script type="text/javascript">
language is an outdated attribute anyway; type is more modern.

How can I have a double Ajax request?

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>

Categories

Resources