What more is needed for Ajax than this function - javascript

I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying?
function loadPage(pagePath, displayElement)
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById(displayElement).innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", pagePath, true);
xmlHttp.send(null);
}

I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't insert potentially insecure javascript or something into your page.
Another thing a more robust framework will give you is the ability to do more than just use innerHTML to replace items in the DOM. Your function here can only be used to replace one element with the response from the ajax call. There's a lot more you can do with Ajax.

I would remove this line.
alert("Your browser does not support AJAX!")
Shouting at the user in a language he probably doesn't understand is worse than failure. :-)

I've never been a fan of nested try/catch blocks, so I'd do it something like:
var xmlHttp;
if (window.XMLHttpRequest) {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (xmlHttp) {
// No errors, do whatever you need.
}
I think that'll work. But as has been mentioned before - why reinvent the wheel, use a library. Even better - find out how they do it.

jQuery is probably one of the lightest popular libraries out there.

The same thing in prototype:
function loadPage(pagePath, displayElement) {
new Ajax.Updater(displayElement, pagePath);
}
Ajax.Updater in Prototype API

If you really want to see what you are missing, read the jQuery or Prototype source code for their ajax routines. If there are bug numbers in the comments, look those up as well.

Related

javascript get html file from online link

i want to call a html online link using xmlhttprequest with javascript, here is my code
but when the code arrive to xmlhttp.open it stopped and does not continue the execution
function loadXMLDoc(size,downloadfromurl) {
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) {
var temp = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://app.arsel.qa/mobileappspeedtest/samples/256.htm?n=" + Math.random(), false);
xmlhttp.send(null);
}
What you are doing is an actual AJAX request to that page.
Cross domain AJAX requests are not allowed by default for security reasons.
However, there are several ways of performing cross domain requests, and you could take a look at how jQuery does it, so you don't have to reinvent the wheel all over again using plain JavaScript. This article should be helpful.
Anyway, if you actually want to crawl that page, there are tons of open source libraries for server side scripting languages like Java, PHP, Node.js, etc that are very useful in gathering the content, parsing the HTML and so on, depending on your needs.
You can use JSONP for overcoming cross domain barrier.
$.ajax({
type:'GET',
dataType:'jsonp',
jsonp: "jsonp",
url:"http://yoururl.com?callback=callbackFunction"
});
function callbackFunction(data){
//you can process the data here
console.log(date)
}

ajax with php data flicker update

So I'm working on this site that needs to retrieve updated results from a mysql database which I did through a php script that echos the output in html.
I just started getting into ajax and would appreciate some help as to why this flickers the entire page when the update is being done to the specific div.
<script type="text/javascript">
function Ajax(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("No AJAX!?");
return false;
}
}
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById('ReloadThis').innerHTML=xmlHttp.responseText;
setTimeout('Ajax()',10000);
}
}
xmlHttp.open("GET","http://xxxxxx.com/updatePlayerList.php",true);
xmlHttp.send(null);
}
window.onload=function(){
setTimeout('Ajax()',10000);
}
</script>
<div id="ReloadThis"></div>
Thanks in advance
The flicker is caused because you write the entire div each time. Why don't you just append or prepend the data to the div instead....
The advantage is low data exchange and controlled output.
Also no need for writing setTimeout after every calls, better use setInterval which will update the div on each interval.
You can append using
$("#ReloadThis").append(strHtml); // strHtml is the html in string format to be appended
and prepend using
$("#ReloadThis").prepend(strHtml); // strHtml is the html in string format to be prepended

Fill div with a php script via Ajax call?

I'm wondering what is the simplest way to fill a div by grabbing a PHP script (and send data like POST or GET) to process what data to return.
But without the use of a library... All I ever find is prototype and jquery examples.
Has any one done this without a library?
var xmlhttp;
function showUser()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="yourpage.php";
url=url+"?q="+str;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("yourdiv_id").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
I'd suggest you look at this code.
You will see how to handle perfectly XHR objects, and it also gives you some sugar syntax.
Btw, a less-than-one-hundred-lines "library" should be fine, since it basically does what you want it to, and no more.

javascript: Problem with dynamically adding xsl-stylesheet to XML Data

I'm trying to write my first Firefox-Extension. The extension is supposed to display FOAF-Files in a nice way using XSLT. Right now I just want to add the XSL Stylesheet to the rdf file when I press a button. The function is called but the presentation of the rdf-file does not change.
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send("");
return xhttp.responseXML;
}
function displayMyResult()
{
alert("test")
xml=loadXMLDoc("http://www.example.com/me.rdf");
xsl=loadXMLDoc("http://www.example.com/test.xsl");
if (window.ActiveXObject)
{
ex=xml.transformNode(xsl);
content.document.location.replace(ex)
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor=new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml,document);
content.document.location.replace(ex)
}
}
The first function loadXMLDoc is copied from another post here, and should probably work. The Probem is in the displayMyResult Method. The test alert confirms, that the function is called but the me.rdf file is not displayed any different.
I believe that the line content.document.location.replace(ex) is wrong but have not found anything on the web that would explain to me what to use instead.
Can anybody tell me how to load the XLST stylesheet to present the RDF File?
Why does your code intended for a Mozilla extension do checks for IE objects like "ActiveXObject"?
Anyway, your code does not make much sense, your Mozilla branch never assigns to the variable named ex, yet you then call replace(ex).
Some more meaningful code would be
var resultFragment = xsltProcessor.transformToFragment(xml, content.document);
content.document.replaceChild(resultFragment, content.document.documentElement);
But I am not sure that will work in general, in particular if content.document is of a different type than the result document of the XSLT (i.e. one being an HTML document, the other being an SVG document).

Running Ajax in IE, FF, and Safari

I'm trying to create an ajax connection to a weather xml feed and then parse returned data. I don't have any issues making a connection via IE, but for some reason I don't have any luck in FF or Safari. Basically what I'm doing is running an html file that contains the following code.
<html>
<script type="text/javascript" language="javascript">
function makeRequest(zip) {
var url = 'http://rdona.accu-weather.com/widget/rdona/weather-data.asp?location=' + zip;
//var httpRequest;
var httpRequest = false;
if (window.XMLHttpRequest) {
document.write("xmlhttprequest");
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
// See note below about this line
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open('GET', url, true);
httpRequest.send('');
}
function alertContents(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
makeRequest(84405);
</script>
</html>
Any help and or suggestions would be greatly appreciated.
I'm afraid you will run into some issues because of same origin policy, meaning that you cant do XMLHTTPRequests to another domain.
Not even jQuery (which you really should check out anyways) can help you with that.
I strongly suggest you use a framework to do this sort of thing. Frameworks will do all of the browser compatibility stuff for you.
On the other hand, if you are interested in how to do this as an academic exercise... still get a framework! See how the framework does it and you will immediately learn all of the pitfalls.
Mootools is my framework of choice.
In order to perform a basic AJAX request in Mootools you would do the following:
window.addEvent('domReady', function() {
new Request({
'url': "The url where you want to send the request
'data': "Some data to send. It can be an object."
}).send();
});
Full documentation for the Request class can be found here.
If you want to see how Mootools implements cross-browser AJAX, you can find the source of the Request class here.
You'll find the source for Browser.Request particularly useful.
For cross browser stuff, I recommend you use a library like JQuery because it will quietly smooth over IE vs Firefox vs Safari etc issues. Also to make the code format properly, use the 101010 button in the toolbar.

Categories

Resources