<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlDoc=xmlhttp.responseXML;
}
}
xmlhttp.open("GET","cd_catalog.xml",true);
xmlhttp.send();
}
</script>
</head>
<body>
<script>
loadXMLDoc();
alert(xmlDoc)//dont work
if(xmlDoc){console.log("true")}
else(console.log("false"))
</script>
<div id="myDiv"></div>
</body>
</html>
If i try to access xmlDoc from within the body then the code does not work??Also i tried to know whether xmlDoc exist using if statement within the body like:
if(xmlDoc){console.log("true")}
else(console.log("false"))
but this also fails ,i m new to xmlDom so what mistake have i made above ?thanks
xmlhttp.open("GET","xmlhttp_info.txt",false);
sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:
execute other scripts while waiting for server response &
deal with the response when the response ready
So this is the reason why ur alert within the body doesn't work since js will continue to execute code.
using async=false JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.
Remember that async=false is not recommended, but for a few small requests this can be ok.
Related
I have been troubled on how to load the same div into the same page for days.
Been looking for answer in stackoverflow but not found one yet.
Simplified, this is my code so far,
<script>
function add_fields() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "add_more.php", false);
xmlhttp.send();
document.getElementById("add_more1").innerHTML = xmlhttp.responseText;
}
</script>
<html>
<body>
<input type="button" onclick="add_fields()" value="ADD"/>
<div id="add_more1"></div>
</body>
</html>
The problem is that when i clicked the button, it will only load add_more.php once. I want it to load everytime the button is clicked. How to do that?
Please help.
function add_fields() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //really no need for this anymore these days.
}
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) //success
{
document.getElementById("add_more1").innerHTML=this.responseText;
}
}
xmlhttp.open("POST","add_more.php",true); //set the sync to true, modern browsers will block a synchronous request.
xmlhttp.send();
}
This updated versions contains a readystate event that will fill your div every time the Ajax call is completed.
You were using a XMLHttpRequest with the asynchronous option set to false. This could block the user experience and modern browsers (like Firefox) will block this.
if you would like to add more content to the div, use
document.getElementById("add_more1").innerHTML += this.responseText;
+= adds content to the element instead of replacing it. It's a shorthand for:
document.getElementById("add_more1").innerHTML = document.getElementById("add_more1").innerHTML + this.responseText;
SIDENOTE: You are using a POST (in this case a GET would be better, since you're retrieving information only). If you want to send post data to the server you need to put the querystring (without the ?) as an argument in the send method.
To continue with this read up on asynchronous coding:
Easy to understand definition of "asynchronous event"? (very simple explanation).
How does Asynchronous Javascript Execution happen? and when not to use return statement? (more comprehensive).
I'm trying to modify this http://www.w3schools.com/php/php_ajax_database.asp
I'm just using the HTML part of that ^. My php file only have
<?php
echo rand();
?>
And it works fine! It updates every time I switch something on the drop-down list.
But, I want it to run every second, but it won't work. This is what my HTML looks like:
<html>
<head>
<script>
function showUser() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/test.php?q="+str,true);
xmlhttp.send();
}
setInterval(showUser, 1000);
</script>
</head>
<body>
<div id="txtHint"><b>this will be updated</b></div>
</body>
</html>
The SetInterval won't run it. The php file is still only echo rand();.
It worked at some point but I screwed something up I believe. Thanks in advance.
setInterval() is likely running just fine, but showUser() is ending with an error since str is not defined. Check your JavaScript console for errors.
Either remove the reference to str, or define it somewhere.
try this:
setInterval(function(){showUser()}, 1000);
Replace
setInterval(showUser, 1000);
with
window.onload = function() {
setInterval(showUser, 1000);
}
I want to fetch the content of a file in server without extension using AJAX. Simple demonstration of code is as follows:
<html>
<head>
<script>
function read_my_file(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById ("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","MYFILE",true);// MYFILE HAS NO EXTENSION
xmlhttp.send();
}
</script>
</head>
<body>
<h2>THIS FETCHES DATA FROM SERVER IF WORKS!!!!!!</h2>
<button type="button" onclick="read_my_file()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
As the file MYFILE has no extension, I think it is interpreted as folder name and I get 404 error. How can I fix this?
If chris's answer does not work you could also try and specify what mime-type your page should have using:
xmlHttp.overrideMimeType("application/xml");
or
xmlHttp.setRequestHeader("Accept", "text/html");
and simply replace "application/xml" or "text/html" with the type you need.
If you want to load a file directly, it must be located within the web server's document root. That is, if the document root is /var/www/example.com/public, then you can access files like this:
/var/www/example.com/public/json/myfile.json
xmlhttp.open("GET","json/myfile.json",true);
xmlhttp.open("GET","http://www.example.com/json/myfile.json",true);
It can't, however, be accessed if the file is located at /var/files/json/myfile.json, since that lies outside the document root! You'd have to use a server-side language (such as PHP) to read the file.
I am new to javascript and AJAX, and have spent the last 8 hours on this one problem, and its beating me. I know its simple, just can't find what I am doing wrong. I have an image on my site with a with an on-click=SendCommand() . This is the js code that I have
function SendCommand(){
alert("BingoBango!");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
};
I get the alert message, and I get no errors using firebug or in chrome javascript console. However that page is not executed. I can however copy and paste that exact url into the browser and it executes successfully.
Any help would be GREATLY appreciated, its kickin my butt.
The page it is calling is calling a python script as well as updating a mysql record. Is there something i can do in my request to ask it to not use the browser cache and actually hit my server?
You should not use a GET request for things that execute actions on the server. Use POST instead, which should not be cached.
If that doesn't help, adapt your HTTP cache headers or, as a last resort, append random strings to the url.
This is how I would do it
JS
function SendCommand()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
}
HTML
<button type="button" onclick="SendCommand()">My button</button>
<div id="myDiv"></div>
The reason I am asking this is because in one of my pages I link a javascript script and then when I try to run a function in the javascript file, it doesn't work.
This is weird because when I copy the exact same code from the script file and put it between the tags, the function then works fine.
Here is how I linked it:
<script src="../scripts/login.js" type="text/javascript"></script>
Here is how it is referenced:
<td><button type="button" onclick="login()">log in </button></td>
Here is the javascript file in case you want to see it:
function login()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
username = encodeURICompenent(document.getElementById("username").value);
password = encodeURICompenent(document.getElementById("password").value);
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
If you attach an external JavaScript file to your document and it contains code that were not found inside any method written on function declaration syntax. those code would execute right after the browser parses the JavaScript file.
Ex.
function CallMe() {
console.log("I'm going to execute once callMe method is invoke");
}
console.log("I'm going to execute once browser parses the javascript file");
The login method on your case wont execute unless there is an event that triggers/invokes the click event of your button.