Javascript - XMLHttpRequest failing in Internet Explorer - javascript

* SOLVED * Answer is in separate post below
This code runs fine in FireFox but it will not run in Internet Explorer 8. It gives me the error of "access denied. Is there something I am missing?
function loadXMLDoc(dname){
if (window.XMLHttpRequest){
var xhttp=new XMLHttpRequest();
}
else{
var xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname,false);
xhttp.send();
return xhttp.responseXML;
}
var xmlDoc=loadXMLDoc("notSchema.xml");
var x=xmlDoc.getElementsByTagName('ROOT_NODE_ID');
It specifically doesn't like the .open() and the .send()
Edited...
var x;
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(http){
xmlDoc = http;
alert(http);
x=http.getElementsByTagName("ROOT_NODE_ID");
},
error: function(html){
alert('failure: ' + html);
}
});
}
loadXMLDoc("notSchema.xml");
for (var i=0;i<x.length;i++)
{
if(x[i].childNodes[0] == undefined) {
treeArray[count]="null";
count++;
}else{
//return ROOT_NODE_ID
treeArray[count]=x[i].childNodes[0].nodeValue;
count++;
}
}
Edited the Code once again. What I'm trying to do is load the XML, parse for the tag "ROOT_NODE_ID" and then get that value and store it into an array
When I run that code in firefox, it returns 51, which is the number of ROOT_NODE_ID tags and fills the tree that I am making.
When I run the same exact code in IE8, it does not even alert.
I'm Stumped.

I figured it out. Like I said before, if you run the code above in Firefox, it returns the 'object' and if you run it in IE8, it returns the contents of the object. I solved this problem by loading the content of the object again in IE8, thus turning the content of the object back into an object that will be ready to be parsed. If that makes any sense.
Just to clarify to people that are just visiting this thread. When I called 'alert(http);' in firefox, it would return '[object XMLDocument]', but in IE8 it would return the actual contents of '[object XMLDocument]'.
var treeArray=new Array();
var count = 0;
var x;
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(http){
var xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
//Loading the contents of the object 'http' a second time, which turns it into an object again.
xmlDocument.loadXML(http);
x = xmlDocument.getElementsByTagName("ROOT_NODE_ID");
alert(x.length);
},
error: function(html){
alert('failure: ' + html);
}
});
}
loadXMLDoc("notSchema.xml");
for (var i=0;i<x.length;i++)
{
if(x[i].childNodes[0] == undefined) {
treeArray[count]="null";
count++;
}else{
//return ROOT_NODE_ID
treeArray[count]=x[i].childNodes[0].nodeValue;
count++;
}
}

Zack,
You can use jquery to do the ajax call - jquery will do everything properly behind the curtains.
In your case here:
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(html){
var x=xmlDoc.getElementsByTagName('ROOT_NODE_ID');
},
error: function(html){
alert('failure: ' + html);
}
});
}

Related

Abort all remaining AJAX requests

I am running an AJAX request when the user types in an input field and then displaying the result on the page. When the user presses the backspace to delete all of what they've inputted, I use .empty to remove the result from the page.
However, if you press the backspaces really quickly, the result is removed from the page, but then because the last AJAX query hasn't last executed, the result from that query appears!!!
I have looked at Abort Ajax requests using jQuery but that didn't help, and have tried adding return: false; after $("#results").empty(); to no avail.
If there are any remaining AJAX calls when if(this.value.length < 1) { is true, I would like to abort them all inside that function.
$("input#enter").keyup(function() {
if(this.value.length < 1) {
$("#display").empty();
}else{
$.ajax({
type: "POST",
url: "getdata.php",
data: "title=" + this.value,
success: function(data) {
$("#display").empty();
$("#display").html(data);
}
});
}
});
You can use $.active to check if $.ajax() call is active before calling next $.ajax()
$("input#enter").keyup(function() {
if(this.value.length < 1) {
$("#display").empty();
}else{
if (!$.active) {
$.ajax({
type: "POST",
url: "getdata.php",
data: "title=" + this.value,
success: function(data) {
$("#display").empty();
$("#display").html(data);
}
});
}
}
});
You can also include attaching .ajaxComplete() to document to call next $.ajax() call when current call completes
function request(value) {
return $.ajax({
type: "POST",
url: "getdata.php",
data: "title=" + value,
success: function(data) {
$("#display").empty();
$("#display").html(data);
}
});
}
$("input#enter").keyup(function() {
if(this.value.length < 1) {
$("#display").empty();
}else{
if (!$.active) {
request(this.value)
} else {
$(document).one("ajaxComplete", function() {
request(this.value)
})
}
}
});
One approach to abort requests is to use XMLHttpRequest(), push requests to an array, then call .abort() on each element of the array
function request(data) {
let fd = new FormData();
fd.append("html", data);
fd.append("delay", Math.floor(Math.random() * 10));
let xhr = new XMLHttpRequest();
xhr.open("POST", "/echo/html/", true);
xhr.onload = function() {
console.log(xhr.responseText);
}
xhr.onabort = function() {
console.log("request " + requests.indexOf(xhr) + " aborted")
}
xhr.send(fd);
return xhr
}
function abortAllRequests() {
requests.forEach(function(xhr, index) {
xhr.abort()
})
}
var requests = [];
requests.push(request(123), request(456));
abortAllRequests();
jsfiddle https://jsfiddle.net/onguym5y/
You talk about aborting ajax requests. It would be sufficient to wait until the request returns and then simply do nothing. Yes, if you were doing a lot of large requests it might improve performance if you cancelled them. But that means using jqXhr objects, and personally I prefer to stick to jQuery where possible.
You could have a variable telling you how up-to-date the #display is. It would store the time of sending of the last ajax request that was used to update it. If you get a response from an earlier request, ignore it.
var lastUpdateTime = 0;
$("input#enter").keyup(function() {
var now = new Date().getTime();
if(this.value.length < 1) {
$("#display").empty();
lastUpdateTime = now;
}else{
$.ajax({
type: "POST",
url: "getdata.php",
data: "title=" + this.value,
success: function(data) {
if (now < lastUpdateTime) {
return;
}
$("#display").empty();
$("#display").html(data);
lastUpdateTime = now;
}
});
}
});

$.ajax & $.post working in Chrome

I've tried both $.ajax & $.post and both are not working in Safari or Firefox. Oddly enough, they are working in Chrome. The 'savemarkup.php' call works fine but the 'sendemail.php' is throwing an error (which comes back to my console as an object). The 'sendemail.php' utilizes PhpMailer to send an email based on selections made in the program.
function generatePDF () {
$("#saving").css("display","none");
var email = generateEmail();
var markup = document.documentElement.innerHTML;
$.post (
'savemarkup.php', {
markup: markup,
email: email
},
function (data,status) {
if (status === 'success') {
$("#saving").fadeIn("fast");
//$.post('sendemail.php');
$.ajax({
url: 'sendemail.php',
type: 'POST',
success: function(res) {
console.log( res );
},
error: function (xhr) {
console.log( xhr );
}
});
var saveDelay = 1000;
if (i > 3) {
saveDelay = 333 * i;
}
$("#saving-image").attr("src","http://quote.hekmancontract.com/images/please-wait-pdf.gif");
window.location = 'savepdf.php';
$("#saving").delay(saveDelay).fadeOut("fast");
$("#saving-image").attr("src","http://quote.hekmancontract.com/images/please-wait-saving.gif");
}
});
}
I can't copy and paste the error log very easily so I've included a snapshot.

JQuery display XSLT into my html page

Can someone help me with this please?
basically I am trying to display the result of my transformed XSLT into an existing page, the transformation seem to be working, but it's not displaying the results when I run my html page. I have tried to run the XSL independently and it's seem to display correctly on his own, so that will leave me with jQuery.
Thank you
This is my code:
$(document).ready(function(){
displayResult();
});
function loadXMLDoc(filename)
{
var deferred = $.Deferred();
var promise = deferred.promise();
$.ajax({
url: filename,
type: 'get',
dataType: 'xml',
success: function(data) {
console.log("resolved");
deferred.resolve(data);
}, error :function(v1, v2)
});
return promise;
}
function displayResult(){
var xmlPromise = loadXMLDoc("my.xml");
var xslPromise = loadXMLDoc("my.xsl");
$.when(xmlPromise, xslPromise).done(function(xml, xsl){
if (document.implementation && document.implementation.createDocument)
{
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
var resultDocument = xsltProcessor.transformToFragment(xml, document);
$('#example').append(resultDocument);
} else if (window.ActiveXObject)
{
/* IE */
var ex = xml.transformNode(xsl);
$('#example').innerHTML = ex;
}
});
}

Set the function itself to the url in AJAX?

I am new to AJAX. Recently, I read a block of code that set url to the function itself. In this case, it is get Path. Normally, we will set url to other pages to get data or something. I do not know what it means to set url to the calling function itself. Could you help answer my question?
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
$.ajax({
type: "POST",
url: "getPath",
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
function getPath() <-- function
url: "getPath", <-- string
They are not related. Only thing in common is the developer had the same name. The page will post to some location called getPath on the server.
It doesn't mean anything other than the fact that the url the POST request is being sent to happens to be "getPath". The function is probably named according to the route name on the server side, but renaming that function (and updating every place it is called accordingly) would have no effect, and you would have to leave the url: "getPath" as is. Changing that part would likely break something.
That getPath would be a relative url, so the request goes to something like: http://example.com/path/to/parent/of/current/page/getPath
suppose your HTML input URL
<input type="url" id="web_url" value=""></input>
Then you can get your URL
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
var url = $('#web_url').val(); // getting input URL by User
$.ajax({
type: "POST",
url:url ,
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>

jQuery AJAX works on mobile safari, but not a UIWebView?

I have a basic jQuery ajax function to log the user in via a UIWebView. However, for some reason it returns blank when it's in a UIWebView. It works fine in mobile safari, and chrome and firefox on my computer.
Here's my code:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});
The theRetrievedData just returns blank on the alert.
Please help!
PS: The app is called "Dudles" in the app store (it's free) if you want to try to login. You will get a blank message from the alert.
Can you post your PHP code as well?
I refactored the code you wrote into how I would write it just to see if I could spot any bugs, and nothing seemed glaringly incorrect. Here is what I have so far:
$(document.body).on('click', '#login_button', function () {
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: $(this).closest('form').serialize(),
success: function (response) {
var delimiter = "?!?success?!?";
var isSuccessful = response.indexOf(delimiter) !== -1;
if (!isSuccessful) {
// handle error
return;
}
$('#content').fadeOut(500, function () {
location = response.split(delimiter)[1];
});
}
});
});
try to send ajax request with async:true, like this:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
async:true,
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});

Categories

Resources