Posting Geolocation data to PHP using AJAX - javascript

I've looked through a few similar threads - but can't see exactly where I am going wrong.
I'm savng the lat & lng of a user on an app I'm creating, using AJAX & PHP. I know the AJAX & PHP works as it saves everything (even dummy lat & lng values) to my database table.
I've been playing with the variables for a couple of hours now, and the best results I have had so far is a '0' value inserted in the database.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
getCurrentLocation();
}
function onError(message) {
navigator.notification.alert(message, "", "Error");
}
function getCurrentLocation() {
navigator.geolocation.getCurrentPosition(locationSuccess, onError);
}
function locationSuccess(position) {
lat = document.getElementById("latSpan");
lon = document.getElementById("latSpan");
latitude = position.coords.latitude;
longitude = position.coords.longitude;
}
//recording function
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
xmlhttp.open("POST","http://www.lauracrane.co.uk/app/rec/location.php",true); //
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("latitude=" + latitude + "&longitude=" + longitude);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}}'
I was wondering if someone can see why it's not passing the value of lat & lng to the AJAX function.
Any help would be appreciated. :)
Laura

Maybe we can't see all the code but it looks like latitude and longitude are function scoped to locationSuccess. So when you try to access them in ajaxFunction they will get the default values.
Also, you don't need to do all that getXMLObject fun. On webkit browsers like in Android, iOS and BlackBerry you just need to do:
var xmlhttp = new XMLHttpRequest();
And finally since you are probably running this off of the file:// protocol you will have to look for a status code of 0 which is analogous to 200 in this case.
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200 || xmlhttp.status == 0) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
}
// etc.
}

Why not just use a jQuery ajax call? Your code is marked up for IE6... Since this in tagged in phonegap I would assume you have access to using newer methods of doing things.
I would suggest using jQuery ajax..
function ajaxFunction() {
$.ajax({
url:'http://www.lauracrane.co.uk/app/rec/location.php',
type:'POST',
data:'lat='+lat+'&long='+long,
success:function(d){
console.log(d);
},
error(w,t,f){
console.log(w+' '+t+' '+f);
}
});
}

Related

'undefined' error even after JSON.parse

<!DOCTYPE html>
<html>
<head>
<title>Imagery Gallery</title>
</head>
<body>
<h2>Location List</h2>
<!-- image gallery will be displayed in the results <div> -->
<div id="results"></div>
<!-- JavaScript codes -->
<script src="HTTPRequest.js"></script>
<script>
//Send request to the server to get the JSON dataset showing the list of locations
//The URL to request is "http://geopingyin.com/gis/Locations.php"
//The request function sendHttpRequest(sURL) is defined in the HTTPRequest.js file
sendHttpRequest("http://geopingyin.com/gis/Locations.php");
//When the JSON dataset (JSONData, a text string) is successfully returned to the browser,
//The function handleResponseData(JSONData) will be automatically called.
//Complete the following function to process the JSON dataset.
function handleResponseData(JSONData) {
var obj = JSON.parse(JSONData);
for (i in obj) {
i += obj[i] + "<br>";
document.getElementById("results").innerHTML = i.Locations;
}
}
//place your codes here for the imagery gallery
</script>
</body>
</html>
This code is giving me an 'undefined' answer whenever I run it. After lots of research it seems like most people have issues with 'undefined' because they are using strings and not objects. However in my code I used a JSON.parse in order to create an object off of the original string, and it still comes up as undefined. I wish to use JSON.parse in order to change my array into objects and then loop through and display each one, yet I can not seem to figure out how to go about this. Any help would be greatly appreciated!
Also here is my HTTPRequest.js code just in case
var xmlHttp = createHttpRequestObj(); //Http request object
//Create HTTP request object
function createHttpRequestObj() {
var xmlHttpObj;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
try {
xmlHttpObj = new XMLHttpRequest();
} catch (e) {
xmlHttpObj = false;
}
} else {
// code for IE6, IE5
try {
xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttpObj = false;
}
}
if (!xmlHttpObj)
alert("Cannot create the Http request object");
else {
return xmlHttpObj;
}
}
//Send HTTP request with the URL
//Function handleServerResponse() will be used to interpret the response
function sendHttpRequest(sURL) {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
xmlHttp.open("GET", sURL, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send();
} else {
setTimeout(function() {
sendHttpRequest(sURL);
}, 1000);
}
}
//Handel HTTP response
function handleServerResponse() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseText;
//Handle the xmlResponse
handleResponseData(xmlResponse);
}
}
}
THANK YOU!
undefined results when you try to access data that doesn't exist. This can result from trying to read an object key from what is actually a string; but can equally happen when reading a nonexistent key from a real object (which is one part of what was going wrong in your code.)
The issues are within your handleResponseData function; I've commented it below to describe what's going wrong:
function handleResponseData(JSONData) {
var obj = JSON.parse(JSONData); // so far so good
/* obj only contains one key, "Locations", so `obj` isn't
what you want to be iterating over; instead you want to iterate
within obj.Locations: */
for (i in obj) {
/* Two problems in this next line: first, it's trying to
concatenate objects onto a string (which will result in
the string "[object Object]"); second, it's trying to
concatenating them onto the iterator, which would
interfere with the loop: */
i += obj[i] + "<br>";
/* This line should not be inside the loop, and it shouldn't be
trying to read the Locations key from child objects, because
that key was on the parent: */
document.getElementById("results").innerHTML = i.Locations;
}
}
Below is a corrected version (I've assumed the .Name key from each object within the Locations array is what you want):
var xmlHttp = createHttpRequestObj();
function createHttpRequestObj() {
// Code for handling obsolete browsers omitted for brevity
return new XMLHttpRequest();
}
function sendHttpRequest(sURL) {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
xmlHttp.open("GET", sURL, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send();
} else {
setTimeout(function() {
sendHttpRequest(sURL);
}, 1000);
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseText;
handleResponseData(xmlResponse);
}
}
}
sendHttpRequest("https://geopingyin.com/gis/Locations.php");
function handleResponseData(JSONData) {
var obj = JSON.parse(JSONData);
var output = "";
for (i in obj.Locations) {
output += obj.Locations[i].Name + "<br>";
}
document.getElementById("results").innerHTML = output
}
<h2>Location List</h2>
<div id="results"></div>

How can I access to the serverside php from javascript?

I set some variables in serverside through PHP
$LGD_AMOUNT = ""; //Amount is for the price that customer purchases
$LGD_BUYER = "";//Buyer collect name of the customer
And I store these in $payReqMap
$payReqMap['LGD_AMOUNT'] = $LGD_AMOUNT;
$payReqMap['LGD_BUYER'] = $LGD_BUYER;
what I want to do is before I send these to the server side, in <script> part, I want to give them values. Is there any method that I can call these stored variables in <script> part?
This is a start point to use Ajax using pure Javascript;
function getxmlhttp (){
//Create a boolean variable to check for a valid Microsoft active x instance.
var xmlhttp = false;
//Check if we are using internet explorer.
try {
//If the javascript version is greater than 5.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
//If not, then use the older active x object.
try {
//If we are using internet explorer.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
//Else we must be using a non-internet explorer browser.
xmlhttp = false;
}
}
// If not using IE, create a
// JavaScript instance of the object.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}//Function getxmlhttp()
//Function to process an XMLHttpRequest.
function processajax (serverPage, obj, getOrPost, str){
//Get an XMLHttpRequest object for use.
xmlhttp = getxmlhttp ();
if (getOrPost == "get"){
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
else {
xmlhttp.open("POST", serverPage, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(str);
}
}

Ajax response works after two clicks?

I just wrote a basic user-login system where the html page uses javascript to send the ajax request to a servlet which accesses through database.
Here's the js code
var res;
function getXMLObject()
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
res=xmlhttp.responseText;
}
else {
return false;
alert("Error during AJAX call. Please try again");
}
}
function ajaxFunction() {
var veid=document.getElementById("eid").value;
var vpwd=document.getElementById("pwd").value;
//window.alert('here inside ajaxFunction'+vconf+' '+vseid);
if(xmlhttp) {
xmlhttp.open("GET","check_login?eid="+ veid +"&pwd="+ vpwd,true); //this is the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function def()
{
//window.alert('hi');
ajaxFunction();
//alert('res:'+res);
if(res=='y')
{
return true;
}
else
{
document.getElementById("uhidden").style.color="#CC0000";
document.getElementById("uhidden").innerHTML="Invalid E-Mail ID or Password"
return false;
}
}
But the code works only after two clicks :(
Any help guys?
Your def function calls ajaxFunction and then straight away checks the res variable. However ajaxFunction just sends the AJAX request; it does not wait for the AJAX response to arrive. Your code is checking the res variable before it is being set from the AJAX response.
This is why it works on the second click - not because the res variable is being set by the second click's AJAX response, but because it is still set from the first click's AJAX response.
The solution is to re-arrange your code a bit. Move the code to display the invalid login message to where the AJAX response is received. In other words, replace the res=xmlhttp.responseText; line with some code to check if xmlhttp.responseText is not y and display the invalid login message.
I guess you call def()
Your Request ist asynchron(because you set the 3rd argument of open() to true ), but in def() you immediately after sending the request work with the the result:
ajaxFunction();
//alert('res:'+res);
if(res=='y')
At this time the request usually is not finished, the result not available yet
Put all code that has to work with the server-response into handleServerResponse()

IE8 is breaking my AJAX... FF is fine

Feeling very proud of myself after creating a form with an AJAX submit, I test it in IE8 and get "Message: 'quantity' is undefined". I've read that it could be something to do with the fact that earlier versions of IE used ActiveX for AJAX requests, but I'm very new to JS and have no real understanding of the problem, let alone the ability to implement a fix.
Here's my code:
var time_variable;
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
From your last comment on your question, I suspect you are not defining 'quantity' anywhere and assuming that it will reference the form field. Try this:
if(xmlhttp) {
var txtname = document.getElementById("txtname");
var quantity = document.getElementById("quantity");
var price = document.getElementById("price");
var store = document.getElementById("store");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
If quantity is a form field you need to get it using getElementById before using it just like you did with txtname:
var quantity = document.getElementById("quantity");
You cant use it directly from the form.

AJAX responseXML errors

I've been having some weird issues when it comes to make an AJAX request and handling the response.
I am making an ajax call for an xml file. however when i get the response the xhr.responseText property works fine in firefox but not in IE.
Another thing is that I am trying to access the xhr.responseXML as XMLDocument, but it tells me in firefox it tells me that xhr.responseXML is undefined in ie it doesnt even show me the undefined error or displays the output.
This is the code I am using to make the request:
var ajaxReq = function(url, callback) {
//initialize the xhr object and settings
var xhr = window.ActiveXObject ?
new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(),
//set the successful connection function
httpSuccess = function(xhr) {
try {
// IE error sometimes returns 1223 when it should be 204
// so treat it as success, see XMLHTTPRequest #1450
// this code is taken from the jQuery library with some modification.
return !xhr.status && xhr.status == 0 ||
(xhr.status >= 200 && xhr.status < 300) ||
xhr.status == 304 || xhr.status == 1223;
} catch (e) { }
return false;
};
//making sure the request is created
if (!xhr) {
return 404; // Not Found
}
//setting the function that is going to be called after the request is made
xhr.onreadystatechange = function() {
if (!httpSuccess(xhr)) {
return 503; //Service Unavailable
}
if (xhr.responseXML != null && xhr.responseText != null &&
xhr.responseXML != undefined && xhr.responseText != undefined) {
callback(xhr);
}
};
//open request call
xhr.open('GET', url, true);
//setup the headers
try {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "text/xml, application/xml, text/plain");
} catch ( ex ) {
window.alert('error' + ex.toString());
}
//send the request
try {
xhr.send('');
} catch (e) {
return 400; //bad request
}
return xhr;
};
and this is how i am calling the function to test for results:
window.onload = function() {
ajaxReq('ConferenceRoomSchedules.xml', function(xhr) {
//in firefox this line works fine,
//but in ie it doesnt not even showing an error
window.document.getElementById('schedule').innerHTML = xhr.responseText;
//firefox says ''xhr.responseXML is undefined'.
//and ie doesn't even show error or even alerts it.
window.alert(xhr.reponseXML.documentElement.nodeName);
});
}
This is also my first attempt to work with AJAX so there might be something that I am not looking at right.
I've been searching crazy for any indications of why or how to fix it, but no luck there.
any ideas would be great.
EDIT:
I know this would be better with a framework, but the boss doesn't want to add a framework for just an ajax functionality ('just' is not a fair word for ajax :P). So I am doing it with pure javascript.
The XML file is well-formed, I see it well in the web browser, but for completion this is the testing file I am using:
<?xml version="1.0" encoding="utf-8"?>
<rooms>
<room id="Blue_Room">
<administrator>somebody#department</administrator>
<schedule>
<event>
<requester>
<name>Johnny Bravo</name>
<email>jbravo#department</email>
</requester>
<date>2009/09/03</date>
<start_time>11:00:00 GMT-0600</start_time>
<end_time>12:00:00 GMT-0600</end_time>
</event>
</schedule>
</room>
<room id="Red_Room">
<administrator>somebody#department</administrator>
<schedule>
</schedule>
</room>
<room id="Yellow_Room">
<administrator>somebody#department</administrator>
<schedule>
</schedule>
</room>
</rooms>
EDIT 2:
Well the good news is that I convinced my boss to use jQuery, the bad news is that AJAX still perplexes me. I'll read more about it just for curiousity. Thanks for the tips and I gave the answer credit to Heat Miser because he was the closest working tip.
I was having the same problem a few years ago, then I gave up on responseXML and began always using responseText. This parsing function has always worked for me:
function parseXml(xmlText){
try{
var text = xmlText;
//text = replaceAll(text,"<","<");
//text = replaceAll(text,">",">");
//text = replaceAll(text,""","\"");
//alert(text);
//var myWin = window.open('','win','resize=yes,scrollbars=yes');
//myWin.document.getElementsByTagName('body')[0].innerHTML = text;
if (typeof DOMParser != "undefined") {
// Mozilla, Firefox, and related browsers
var parser=new DOMParser();
var doc=parser.parseFromString(text,"text/xml");
//alert(text);
return doc;
}else if (typeof ActiveXObject != "undefined") {
// Internet Explorer.
var doc = new ActiveXObject("Microsoft.XMLDOM"); // Create an empty document
doc.loadXML(text); // Parse text into it
return doc; // Return it
}else{
// As a last resort, try loading the document from a data: URL
// This is supposed to work in Safari. Thanks to Manos Batsis and
// his Sarissa library (sarissa.sourceforge.net) for this technique.
var url = "data:text/xml;charset=utf-8," + encodeURIComponent(text);
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
return request.responseXML;
}
}catch(err){
alert("There was a problem parsing the xml:\n" + err.message);
}
}
With this XMLHttpRequest Object:
// The XMLHttpRequest class object
debug = false;
function Request (url,oFunction,type) {
this.funct = "";
// this.req = "";
this.url = url;
this.oFunction = oFunction;
this.type = type;
this.doXmlhttp = doXmlhttp;
this.loadXMLDoc = loadXMLDoc;
}
function doXmlhttp() {
//var funct = "";
if (this.type == 'text') {
this.funct = this.oFunction + '(req.responseText)';
} else {
this.funct = this.oFunction + '(req.responseXML)';
}
this.loadXMLDoc();
return false;
}
function loadXMLDoc() {
//alert(url);
var functionA = this.funct;
var req;
req = false;
function processReqChange() {
// alert('reqChange is being called');
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
eval(functionA);
if(debug){
var debugWin = window.open('','aWindow','width=600,height=600,scrollbars=yes');
debugWin.document.body.innerHTML = req.responseText;
}
} else {
alert("There was a problem retrieving the data:\n" +
req.statusText + '\nstatus: ' + req.status);
if(debug){
var debugWin = window.open('','aWindow','width=600,height=600,scrollbars=yes');
debugWin.document.body.innerHTML = req.responseText;
}
}
}
}
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = processReqChange;
if(this.url.length > 2000){
var urlSpl = this.url.split('?');
req.open("POST",urlSpl[0],true);
req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
req.send(urlSpl[1]);
} else {
req.open("GET", this.url, true);
req.send("");
}
}
}
function browserSniffer(){
if(navigator.userAgent.toLowerCase().indexOf("msie") != -1){
if(navigator.userAgent.toLowerCase().indexOf("6")){
return 8;
}else{
return 1;
}
}
if(navigator.userAgent.toLowerCase().indexOf("firefox") != -1){
return 2;
}
if(navigator.userAgent.toLowerCase().indexOf("opera") != -1){
return 3;
}
if(navigator.userAgent.toLowerCase().indexOf("safari") != -1){
return 4;
}
return 5;
}
Granted, this is very old code, but it is still working for me on a site I built a few years ago. I agree with everyone else though I typically use a framework nowadays so I don't have to use this code or anything like it anymore.
You can ignore some of the particulars with the split, etc... in the Request onreadystate function. It was supposed to convert the request to a post if it was longer than a certain length, but I just decided it was always better to do a post.
This problem occurs mostly when content type is mis-detected by the browser or it's not sent correctly.
Its easier to just override it:
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.overrideMimeType("text/xml");
request.send(null);
return request.responseXML;
Not sure why... This problem occurs only with Safari and Chrome (WebKit browsers, the server sends the headers correctly).
Are you calling the URL relative to the current document? Since IE would be using the ActiveXObject, it might need an absolute path, for example:
http://some.url/ConferenceRoomSchedules.xml
As for the XML, are you sure it's well-formed? Does it load in an XML editor, for instance?
What I can suggest you is to take a look at frameworks that hide and manage these cross-browser issues for you (in a reliable way). A good point here is jQuery. Doing these things yourself can become quite difficult and complex.
This may be what you need.
//Edit:
This is how the w3school shows it:
function ajaxFunction()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
}
To avoid your cross browser problems (and save yourself coding a lot of items that a strong community has already developed, tested, and reviewed), you should select a javascript library. JQuery and Dojo are great choices.
I believe that your web server need to serve correct response headers with 'ConferenceRoomSchedules.xml' e.g. Content-Type: text/xml or any other xml type.
The answer provided by Aron in https://stackoverflow.com/a/2081466/657416 is from my point of view the simplest (and the best) one. Here is my working code:
ajax = ajaxRequest();
ajax.overrideMimeType("text/xml");
ajax.open("GET", myurl;

Categories

Resources