Load specific XML content to HTML - javascript

I'm trying to load specific content from a XML to a HTML div. I'm using a function with parameters to do this.
This my call to function:
loadDoc("news.xml","destak-article","article");
this should send a request for the xml file, get the content of «article» tag and put it on the «destak-article» div.
Here's my function body:
function loadDoc(url,id,tagname){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.open("GET",url,false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById(id).innerHTML = xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
But this doesn't seem to work.
On Chrome js console I get this error: Cannot call method 'getElementsByTagName' of null
On Firebug I get: xmlDoc.getElementsByTagName(tagname)[0] is undefined
Any help is much appreciated.

Did you verify the server response? Use some error checking in your code. For example:
if (xmlhttp.status == 200) {
document.getElementById(id).innerHTML = xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
else {
alert('error');
}

You need to register a handler function that will be called once the request is complete. You can see an example of how to do that here.
What's happening in your case is that you're trying to get the xmlDoc immediately after sending the request and the server hasn't had time to process the request and respond yet.

Related

Ajax Function Not Being Called

So What I'm trying to do is, create an alert using java script. And if the person presses OK
it will send a variable to the handler and the handler will send an email. The following code is what I have, but I'm having trouble debugging it. As of right now I have this:
THE IF STATEMENT, CLICKING OKAY:
var pressed = confirm("Click okay to email users of video upload or Cancel to keep adding videos");
if (pressed == true)
{
var variable = 44;
emailParticipants(variable);
alert ("email sent");
}
FUNCTION THAT SENDS TO HANDLER:
function emailParticipants(sessionID)
{
var ID = sessionID;
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("GET","http://www.website.ca/portal/folder/HandleEmail.php?sessID="+ID,true);
xmlhttp.send();
}
HANDLER:
$SessID = $_GET['ID'];
<?php
$toEmail = 'someone#hotmail.com';
$toName = "TEST TEST";
<script>alert ("works");</script>
.
..
....
The rest of the handler functing just sends the email. I can't catch where the mistake is.
Well, you are invoking the handler via AJAX. The alert() method is inside the page the handler returns ... but you aren't doing anything with that page. You make a request and forget about the response. The browser doesn't execute the response from an AJAX call, so the code with the alert never executes.
By the way, you ** never ** should send e-mails (or do any other change in the server but returning information) with a GET request. GET requests can be cached, or even prefetched, causing emails to be sent when not requested, or not be sent when requested. I'd change the request type to POST.
If you want your alert, you need to change your client code and add this:
xmlhttp.open("GET","http://www.website.ca/portal/folder/HandleEmail.php?sessID="+ID,true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('works!');
} else {
alert('Failed! ' + xmlhttp.statusText);
}
}
}
xmlhttp.send();
I think you are a bit lost about AJAX. You should read more

Ajax Call not updating DIV in firefox. Working fine in Chrome

I am sending chat message, and receiving them in particular div.. All read and write with ajax. Everything works fine in Chrome, but in firefox, it does not shows...
Here is my code :-
var xmlhttp = false;
function read_message() {
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatBox").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",'http://<?php echo $domain; ?>/m.php?id='+<?php echo $id; ?>,true);
xmlhttp.setRequestHeader("Content-type","text/html");
xmlhttp.send();
}
$(document).ready(function(){
setInterval("read_message()", 800);
});
$domain is define in Header page and it is Same domain, where file is running... i.e,
if my chat page is in localhost than $domain is also localhost..
I am aware of same origin policy of ajax, but is this problem due to using http://.
I cannot leave http:// part as i am using url-rewriting and there my url is something like http://localhost/chat/user/anonymous so, if i use only m.php?id=1 than it tries to fetch page from
http://localhost/chat/user/m.php which obviously doesnot exist... it exist in http://localhost/m.php
if above mentioned point is error, is there any way that we can solve it, or any other better help would be great.
Thanks
When you fire two requests, if the second request fires before the first request resolves, xmlhttp.responseText in your onreadystatechange listener would point to the responseText of the second (unresolved) request when the listener for the first request fires. This is because you only use a single global xmlhttp variable that is shared for all requests.
If you define var xmlhttp inside your read_message, instead of outside of it, then each new function call will have its own private xmlhttp variable:
function read_message() {
var xmlhttp;
//...
}

Why is my basic Ajax script not working?

I have been playing around with Javascript and now I came to Ajax. I am trying to write very simple script that would get the file contents - print the txt file contents in the div with id=test. This is the script :
function loadXMLDoc(url)
{
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("GET" , url ,false);
xmlhttp.send(null);
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
when I use it on this website :
<div id="test" name="test"> HELLo </div>
<button type="button" onclick="loadXMLDoc('test1.txt')">ClickMe1</button>
With this script HELLo is substituted by nothing - the script empties the container.
Maybe I am missing something trivial but do I need PHP installed ? I don't think so but... I am not sure what is happening in here. When I am debugging the xmlhttp is empty the whole time. Why ?
You'll need to check for readyState and the HTTP response status before replacing the text;
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test").innerHTML=xmlhttp.responseText;
}
example on http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
Please let me know if it works.
For browsers other than IE
IE's active X object seems not to care much about the ready state, other browsers may not have the text loaded quickly enough at the time you run your function (hence why you are getting the blank instead of file contents). IE's active X seems to handle this automatically and ignores the ready state, so you have to break up the code differently as below. Normally you check the status of the request to see if it's been fully read or not before accessing the responseText.
Add onreadystatechange you cannot check the status attribute since there is no HTTP requests being made on a file system request. (The status will always be 0 for request not made via HTTP) The best I can offer is this:
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
xmlhttp.open( "GET", url );
xmlhttp.send(null);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open( "GET", url );
xmlhttp.send(null);
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
}
For CHROME
If you are using CHROME you must start chrome up with the --allow-file-access-from-files switch. Otherwise, it will refuse file system ajax requests. (You will have to set this even if using a so-called "easier" library such as jQuery).
Running AJAX apps on File System In General
Not usually a good idea, a lot of caveats to this route. Typically local development is done with a web server installed to localhost on your development machine.
Today its old fashion to call ajax like xmlhttp = new XMLHttpRequest();
You have many other options for this.
http://api.jquery.com/jQuery.ajax/
http://www.w3schools.com/jquery/jquery_ref_ajax.asp
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Firstly, you have to fight with Same Origin Policy.
A simple working code for a synchronous request is following:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.status == 200 && req.readyState == 4) {
...
}
req.open('GET', url, true);
req.send(null);
Note this is working for Firefox/Opera/Chrome. If IE, use:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
You need a server to listen up to requests. Your regular file system will not be able to respond to AJAX requests.
You don't need PHP, however you'll need apache or a similar web server.
Try with jQuery. Download the last version here and write this code snippet:
function loadXMLDoc(url) {
$("#test").load(url);
}
It's much simpler and less error prone

why do i always get a 404 on this function?

I'm using this function to check if a webpage exists. To do this I am checking if it has a header. But I always get a 404, even with a blank url.. what am I doing wrong here?
var xmlhttp;
function checkURL(url){
xmlhttp=null; // initialize the request object
// All the browsers except for the old IE
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest()
xmlhttp.onreadystatechange=xmlhttpChange
xmlhttp.open("HEAD",url,true)
xmlhttp.send(null)
}
// old IE
else if (window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
if (xmlhttp)
{
xmlhttp.onreadystatechange=xmlhttpChange
xmlhttp.open("HEAD",url,true)
xmlhttp.send();
}
}
}
function xmlhttpChange()
{
// if loaded
if (xmlhttp.readyState==4)
{
// if head exists "OK"
if (xmlhttp.status==200)
{
alert('URL exists')
}
else
{
alert("Status is "+xmlhttp.status)
}
}
}
It works fine for any page that you are allowed to access.
Demo: http://jsfiddle.net/Guffa/dPMah/
You can only access pages in the same domain using the XMLHTTP object.
I assume the url variable will contain addresses to completely other sites, and is not just for checking internal paths in your application? You can't AJAX to another domain like that because of the Same Origin Policy.

AJAX Request Too Long / Bad Request

Greetings Everyone
I am using the following code to send data to update to a php file. The problem is I get a Request Too Long issue. I have used the 'POST' method I believe if thats the right way. Yes the data I am sending is quiet huge. So what can I do?
var link = 'updateFirstPost.php?post_id='+id+'&first_post='+encodeURIComponent(text);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
refreshPost(div_post, thread_id , id);
}
}
xmlhttp.open("POST",link,true);
xmlhttp.send();
The problem is I get a Request Too Long issue. I have used the 'POST' method I believe if thats the right way. So what can I do?
You are putting the data into the URL, which will always cause them to be sent as GET data. GET requests have natural length limitations on both the server's and the browser's side.
To send the data through POST, you need to put the parameters like so:
var params = 'first_post='+encodeURIComponent(text);
....
http.send(params);
(stolen from here)
If this is not for learning purposes, consider using a JS framework like jQuery. It makes stuff like this much, much easier and less code-intensive.

Categories