Ajax call with javascript fails with internet explorer - javascript

OK here is my code which i am using to call a remote site for a list of data objects which i want to display on another site.
This works fine with Chrome and Firefox but throws error in IE "Permission denied"
I also added the request for Access-Control-Allow-Origin and headers but the issue persist in IE....
I can't use jQuery because the site on which I'll put this might not have jQuery. Does it have to something with cross domain request?
<script id= "sc1" type="text/javascript">
function ajaxRequest() {
var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
if (window.ActiveXObject) {
for (var i = 0; i < activexmodes.length; i++) {
try {
return new ActiveXObject(activexmodes[i])
} catch (e) {
}
}
} else if (window.XMLHttpRequest) return new XMLHttpRequest()
else return false;
}
var contentDiv = document.createElement("div");
contentDiv.id = 'contentJobsoid';
document.getElementById('sc1').parentNode.appendChild(contentDiv);
(function(){
var mygetrequest = new ajaxRequest()
if (mygetrequest.overrideMimeType) mygetrequest.overrideMimeType('text/html')
mygetrequest.onreadystatechange = function () {
if (mygetrequest.readyState == 4) {
if (mygetrequest.status == 200 || window.location.href.indexOf("http") == -1) {
var data = mygetrequest.responseText;
document.getElementById("contentJobsoid").innerHTML = data;
} else {
console.log("An error has occured making the request");
}
}
}
mygetrequest.open("GET", "http://www.demo.com/demo/dee0c7fe-867d-408d-a00f-d9bed4b169a7", true);
mygetrequest.send(null);
return false;
}());
</script> -->

I just passed the data from the server in form of string in the script src tag and it solved my problem very easily

Related

Ajax POST never gets sent?

I'm having an issue with my ajax POST for some reason the POST is never made! can't for the life of me work it out?
yeah so I used the network debug tool in firefox to check the POST request but the POST request never gets made..
The function is definitely getting called too as I have added an alert alert("start") to the beginning of the function which does run.
AJAX
<script>
function updateContentNow(pid2, status2) {
var mypostrequest = new ajaxRequest();
mypostrequest.onreadystatechange = function() {
if (mypostrequest.readyState == 4) {
if (mypostrequest.status == 200 || window.location.href.indexOf("http") == -1) {
document.getElementById("livestats").innerHTML = mypostrequest.responseText;
} else {
alert("An error has occured making the request");
}
}
}
var parameters = "cid=clientid&pid=6&statusinfo=approve";
mypostrequest.open("POST", "http://mydomain.com.au/content-approval/ajax.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
</script>
UPDATED WORKING: thanks peps..
<script>
function updateContentNow(pid2,status2)
{
var mypostrequest=new XMLHttpRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("livestats").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var parameters="cid=<?=$clientID?>&pid="+pid2+"&statusinfo="+status2;
mypostrequest.open("POST", "http://mydomain.com.au/content-approval/ajax.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
</script>
Are you using some external Ajax classes, at least ajaxRequest() object doesn't exist in plain JavaScript. Try to substitute this line
var mypostrequest = new ajaxRequest();
by that:
var mypostrequest=new XMLHttpRequest();
Then even calling your method with
updateContentNow("","");
at least makes the POST request as you easily can see with Firebug.

Does this Ajax method work in many browsers and operating systems?

I'm using Ajax in Javascript to get values ​​on other pages.
function loadXMLDoc(){
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","ajax_info.txt",true);
xmlhttp.send();
}
But I'm afraid it does not work in certain browsers or even operating systems. Is it safe to use? Or is it better to use jQuery Ajax?
(detail: I do not want to use jQuery!)
First off up-vote for trying to do this with real JavaScript!
Secondly you probably are unaware but you're treating code as text, not as code. Don't use innerHTML and don't use responseText. You need to use a proper DOM method such as appendChild and insertBefore though with AJAX you need to specifically use importNode and responseXML. The XML you load from the server must be served as application/xml, the mime text/xml is invalid.
The code on my site works with older browsers (e.g. IE5/6 if you're that insane at this point). I've been meaning to clean this up. Also it's reusable so you won't need to keep creating new AJAX functions except ajax_post() which if you visit my site and look at the index.js file you're welcome to mess with that.
Super-Bonus: The ajax_sequel() function can be used to execute whatever you want after the AJAX request has completed in full. I've left the alerts in place for you to mess with the code.
Example execution...
ajax_load_page('?ajax=1&url=mail/sent/','inside','sidebar','sequel-string',id_focus);
The first parameter is the AJAX URL, keep in mind you must have a single element that contains everything for the request and no whitespace before or after it. It must also have an XML namespace...
<div xmlns="http://www.w3.org/1999/xhtml">AJAX stuffs</div>
The second parameter accepts the strings after, before, inside, replace relative to the id of the third parameter.
The fourth parameter I use for the ajax_sequel() function I already mentioned.
The last (fifth) parameter is the ID I want the browser to give focus to (if any).
Strict code is difficult but when you do it the right way things just work so much easier.
Any functions missing can be found in the index.js file of my site, linked from my profile. Here is the main part of what you're looking for...
function ajax_id_duplication_prevention(xml)
{//alert(typeof xml+'\n\n'+xml.childNodes[0].childNodes.length);
var re = true;
if (option.id_fade && option.id_fade!='' && document.getElementById(option.id_fade))
{
element_del(option.id_fade);
option.id_fade = '';
}
if (typeof document.createTreeWalker=='function')
{
var idz = [];
try
{
var walker = document.createTreeWalker(xml,NodeFilter.SHOW_ELEMENT,null,false);
while (walker.nextNode())
{
if (walker.currentNode.id==undefined && walker.currentNode.nodeName=='parsererror') {alert('Error: a parser error was detected.\n\nThis may or may not afflict the content being loaded.\n\nIf the content does not load correctly reload the entire page.');}
else if (walker.currentNode.id==undefined) {alert('walker.currentNode.nodeName = '+walker.currentNode.nodeName+'\n\n'+document.serializeToString(xml));}
else if (walker.currentNode.id!='')
{
var n = document.getElementById(walker.currentNode.id);
if (n)
{
var l = document.getElementById('liquid');
for (var i=0; i<l.childNodes.length; i++)
{
var c = l.childNodes[i];
if (n.compareDocumentPosition(c)==10)
{
element_del(c);
//Do AJAX report to DB table: id error log
break;
}
}
//alert('Error: can not import XML.\n\nAn element with the id \''+walker.currentNode.id+'\' already exists in the target application.');
//re = false;
break;
}
else if (in_array(walker.currentNode.id,idz))
{
alert('Error: can not import XML, the id \''+walker.currentNode.id+'\' was detected twice in the layer being imported.\n\nDuplicated ID\'s break expected functionality and are illegal.\n\nWhile the XML content was not imported it is still possible that the related request was successful.');
re = false;
break;
}
else {idz.push(walker.currentNode.id);}
}
}
}
catch (err) {}//IE9
}
return re;
}
function ajax_load_page(url,id_container_pos,id_container,sequel,id_focus)
{//alert(url+'\n'+id_container_pos+'\n'+id_container+'\n'+sequel+'\n'+id_focus);
if (document.getElementById(id_container) || id_container)
{
if (window.XMLHttpRequest) {var xmlhttp = new XMLHttpRequest();}
else if (window.ActiveXObject) {try {xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');} catch (e) {try {xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');} catch (e) {}}}
else {alert('Error: Your browser does not seem to support AJAX.');}
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState=='4')
{
if (xmlhttp.status=='200' || xmlhttp.status=='401' || xmlhttp.status=='403' || xmlhttp.status=='404' || xmlhttp.status=='501') {ajax_load_page_import(url,xmlhttp,id_container_pos,id_container,sequel,id_focus);}
else if (xmlhttp.status=='404') {alert('HTTP 404: The content was not found.');}
else if (xmlhttp.status=='429') {alert('HTTP 429: You are requesting pages too quickly.');}
else if (xmlhttp.status=='500')
{
if (xmlhttp.getResponseHeader('AJAX-HTTP')==null) {alert('HTTP 500: The server encountered an error.');}
else
{
var http = xmlhttp.getResponseHeader('AJAX-HTTP');
if (http==429) {alert('HTTP 429: You are requesting pages too quickly.');}
else {alert('HTTP '+http);}
}
}
else if (xmlhttp.status=='204' || xmlhttp.status=='0' || xmlhttp.status=='1223' || xmlhttp.status==undefined) {if (id_container=='chat_messages') {ajax_sequel(sequel,id_container);}}
else if (xmlhttp.status!='204' && xmlhttp.status!='0' && xmlhttp.status!='1223') {alert('HTTP '+xmlhttp.status+'\n\nIf you keep encountering this error please contact the webmaster.');}//Opera 204='0' & IE 204='1223'
}
}
}
else {alert('Error: '+id_container+' id does not exist!');}
}
function ajax_load_page_import(url,xmlhttp,id_container_pos,id_container,sequel,id_focus)
{//alert('url = '+url+'\n\nxmlhttp = '+xmlhttp+'\n'+id_container_pos+'\n'+id_container+'\n'+sequel+'\n'+id_focus);
if (!document.getElementById('Body') && xmlhttp.responseXML) {var xmlDoc=xmlhttp.responseXML;}
else {var xmlDoc=xmlhttp.responseText;}
if (!document.ELEMENT_NODE)
{
document.ELEMENT_NODE = 1;
document.ATTRIBUTE_NODE = 2;
document.TEXT_NODE = 3;
document.CDATA_SECTION_NODE = 4;
document.ENTITY_REFERENCE_NODE = 5;
document.ENTITY_NODE = 6;
document.PROCESSING_INSTRUCTION_NODE = 7;
document.COMMENT_NODE = 8;
document.DOCUMENT_NODE = 9;
document.DOCUMENT_TYPE_NODE = 10;
document.DOCUMENT_FRAGMENT_NODE = 11;
document.NOTATION_NODE = 12;
}
document._importNode = function(node,allChildren)
{
switch (node.nodeType)
{
case document.ELEMENT_NODE:
var newNode = document.createElement(node.nodeName);
if (node.attributes && node.attributes.length > 0) {for (var i = 0, il = node.attributes.length; i < il;) {newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));}}
if (allChildren && node.childNodes && node.childNodes.length > 0) {for (var i = 0, il = node.childNodes.length; i < il;) {newNode.appendChild(document._importNode(node.childNodes[i++], allChildren));}}
return newNode;
break;
case document.TEXT_NODE:
case document.CDATA_SECTION_NODE:
case document.COMMENT_NODE:
return document.createTextNode(node.nodeValue);
break;
}
return true;
}
if (xmlhttp.responseXML)
{
if (ajax_id_duplication_prevention(xmlhttp.responseXML))
{
if (xmlhttp.responseXML.childNodes.length==0) {alert('Error: no elements were found in the AJAX request!\n\n'+url);}
else if (xmlhttp.responseXML.childNodes.length>1) {alert('Error: parse error, AJAX requests can only have a single parent-most element.\n\n'+url+'\n\n'+xmlhttp.responseText);}
else
{
if (document.getElementById(id_container)) {var id_container_obj = document.getElementById(id_container);}
else {var id_container_obj = id_container;}
var id_ajax = xmlhttp.responseXML.childNodes[0].getAttribute('id');
if (id_container=='prompts_ajax') {ajax_layer_init('prompts_ajax',id_ajax);}
if (document.importNode && xmlhttp.responseXML && document.getElementById('body').style.khtmlMarginBottomCollapse==undefined && browser!='MSIE')
{
if (id_container_pos=='after') {id_container_obj.insertBefore(xmlDoc.getElementsByTagName('div')[0],id_container_obj.nextSibling);}
else if (id_container_pos=='before')
{
id_container_obj.parentNode.insertBefore(document.importNode(xmlDoc.getElementsByTagName('div')[0],true),id_container_obj);
}
else if (id_container_pos=='inside') {id_container_obj.appendChild(document.importNode(xmlDoc.getElementsByTagName('div')[0],true));}
else if (id_container_pos=='replace') {var r = id_container_obj.parentNode; r.removeChild(r.getElementsByTagName('div')[0]); r.appendChild(document.importNode(xmlDoc.getElementsByTagName('div')[0],true));}
else {alert('Error: unknown position to import data to: '+id_container_pos);}
}
else if (!document.getElementById('Body') && xmlhttp.responseXML)//IE8+
{
if (typeof xmlDoc.getElementsByTagName('div')[0]=='object')
{
if (id_container_pos=='after') {id_container_obj.parentNode.appendChild(document._importNode(xmlDoc.getElementsByTagName('div')[0],true));}
else if (id_container_pos=='before') {id_container_obj.parentNode.insertBefore(document._importNode(xmlDoc.getElementsByTagName('div')[0],true),id_container_obj);}
else if (id_container_pos=='inside') {id_container_obj.appendChild(document._importNode(xmlDoc.getElementsByTagName('div')[0],true));}
else if (id_container_pos=='replace') {var r = id_container_obj.parentNode; r.removeChild(r.getElementsByTagName('div')[0]); r.appendChild(document._importNode(xmlDoc.getElementsByTagName('div')[0],true));}
else {alert('Error: unknown position to import data to: '+id_container_pos);}
//if (document.getElementById(id_focus)) {document.getElementById(id_focus).focus();}
}
}
else if (document.getElementById('Body') && xmlhttp.responseXML)// IE 5.0~7
{
if (document.getElementById('body').currentStyle.scrollbarBaseColor)
{
//IE 5.5/6/7
var id_imported = xmlhttp.responseXML.childNodes[0].getAttribute('id');
if (!document.getElementById(id_imported))
{
if (id_container_pos=='after') {id_container_obj.parentNode.appendChild(document._importNode(xmlhttp.responseXML.childNodes[0],true));}
else if (id_container_pos=='before') {id_container_obj.parentNode.insertBefore(document._importNode(xmlhttp.responseXML.childNodes[0],true),id_container_obj);}
else if (id_container_pos=='inside') {id_container_obj.appendChild(document._importNode(xmlhttp.responseXML.childNodes[0],true));}
else if (id_container_pos=='replace') {var r = id_container_obj.parentNode.id; id_container_obj.parentNode.removeChild(id_container_obj.parentNode.getElementsByTagName('div')[0]); if (document.getElementById(r)) {document.getElementById(r).appendChild(document._importNode(xmlhttp.responseXML.childNodes[0],true));}}
else {alert('Error: unknown position to import data to: \''+id_container_pos+'\'');}
}
}
var id_ajax = xmlhttp.responseXML.childNodes[0].getAttribute('id');
}
else if (!id_container_obj) {alert('Error: can not add content to the DOM; the id \''+id_container+'\' does not exist or has not been imported to the DOM yet.');}
else {alert('Error: Ajax function did not trigger correctly, try checking content\'s mime?\n\n'+xmlhttp+'\n'+id_container_pos+'\n'+id_container+'\n'+sequel+'\n'+id_focus);}
ajax_sequel(sequel,id_container,id_ajax,id_focus);
}
}
}
else if (xmlhttp.getResponseHeader('Content-Type')=='text/html')
{
if (!option.th || option.th==2)
{
ajax_load_page(url,id_container_pos,id_container,sequel,id_focus);
option.th = 1;
}
else if (confirm('Error: unable to load AJAX content.\n\nType: '+xmlhttp.getResponseHeader('Content-Type')+'\n\nInitiating second attempt at request...\n\n'+xmlhttp.responseText))
{
ajax_load_page(url,id_container_pos,id_container,sequel,id_focus);
}
}
else
{
alert('Error: unable to load AJAX content.\n\nType: '+xmlhttp.getResponseHeader('Content-Type')+'\n\nresponseText = '+xmlhttp.responseText);
}
}
function ajax_sequel(sequel,id_container,id_ajax,id_focus)
{alert('ajax_sequel()\n\nsequel = '+sequel+'\nid_container = '+id_container+'\nid_ajax = '+id_ajax);
}

window.location not firing after ajax event

I'm not sure if this is related to an ajax call or not. I'm very new to Ajax, and so I suspect it is the cause.
I run the following javascript:
function GetXmlHttpObject() {
"use strict";
var objXMLHttp = null;
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
objXMLHttp = new window.ActiveXObject("Microsoft.XMLHTTP");
}
return objXMLHttp;
}
function delete_director(i) {
"use strict";
var r, url;
r = window.confirm("Are you sure you want to disable this director");
url = "ajax.php?task=director&event=delete&UserId=" + i;
if (r === true) {
mdata = new GetXmlHttpObject();
if (mdata === null) {
alert("Browser does not support HTTP Request");
return;
}
mdata.open("GET", url, true);
mdata.send(null);
}
}
And that calls into the following php function:
function deletedirector()
{
$UserId=mysql_real_escape_string($_GET['UserId']);
$query = "update tbl_users set IsDisabled='1' where UserId=".$UserId;
$result = mysql_query($query) OR die('Cannot perform query!');
if ($result) {
error_log("a");
?><script type="text/javascript">window.location='index.php?task=director&success=Director Successfully Deleted.'</script><?
} else {
error_log("b");
?><script type="text/javascript">window.location='index.php?task=director&error=Director Deletion Failed.'</script><?
}
}
The db shows that the director was deleted, and "a" prints in the error log, but the window.location never fires.
The user experience is that the browser prompts for confirmation, and after that - nothing. A javascript console shows now error.
Any ideas?
You already return new object (of XMLHttpRequest API) with function, so you don't need new here
...
if (r === true) {
mdata = GetXmlHttpObject();
...
and try to use onreadystatechange like this
mdata.onreadystatechange = function(){
if (mdata.readyState === 4) {
alert("some text");
} else {
alert(mdata.status);
}
};

call server side methode and javascript code at the same time

I am developing the web application for Mobile where I want to open SMS editor from javascript.
below is my aspx code
<a class="redBtn fltrt" href="#" id="lnkBuy" runat="server" onclick="return makePayment()" onserverclick="lnkBuy_Click" rev='12' rel='21'>Buy</a>
and the onClick method
function makePayment()
{
try
{
var res=confirm('Are you sure to continue?');
if(res == true)
{
window.location='sms:+334343434343';
return true;
}
else
{
return false;
}
}
catch(Error)
{
}
}
here is I want to open the SMS editor and call to my code behind code
protected void lnkBuy_Click(object sender, EventArgs e)
{
//code goes here
}
By using this and I am able to open the SMS editor but not be able to redirect to my code behind code.Can any body suggest me any way to do this both action in same time or any other convenient way.
thanks in advance
Maybe you can do it the other way, doing the server call first, and then sending a redirect to the client to "sms:+334343434343" ?
Or alternatively, instead of using the ASP.NET callback mechanism, send an AJAX call to the server before the window.location change.
It depends on what you need to do server side.
I use the XMLHTTPRequest to send the call to my processing page and write another function to redirect to native SMS editor call.
Below is my code
function makeoldPayment(courseId,basketId)
{
try
{
var res=confirm('Are you sure to continue?');
if(res == true)
{
var mobNo = document.getElementById('hidMNo').value;
var lerid = document.getElementById('hidLId').value;
var sendDataToServerReq = getXMLHttpRequest();
var newURL = window.location.protocol + "//" + window.location.host + "/Learners/SaveToDB.aspx?cid=1&mbid=123456&bid=43&lid=3;
//alert(newURL)
sendDataToServerReq.open("POST", newURL, false);
sendDataToServerReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8;");
gosms();
sendDataToServerReq.send("mobno="+mobNo+"&lerid="+lerid+"&basketid="+basketId+"&recordid="+courseId);
location.reload();
return false;
}
else
{
return false;
}
}
catch(Error)
{
}
}
function gosms()
{
try
{
window.location='sms:+334343434343';
}
catch(Error)
{
}
}
function getXMLHttpRequest()
{
var httpRequest = null;
// Create the appropriate HttpRequest object for the browser.
if (window.XMLHttpRequest != null){
httpRequest = new window.XMLHttpRequest();
}else if (window.ActiveXObject != null){
// Must be IE, find the right ActiveXObject.
var success = false;
for (var i = 0; i < XMLHTTPREQUEST_MS_PROGIDS.length && !success; i++)
{
try{
httpRequest = new ActiveXObject(XMLHTTPREQUEST_MS_PROGIDS[i]);
success = true;
}
catch (ex)
{}
}
}
if (httpRequest == null){
//alert("Error in HttpRequest():\n\nCannot create an XMLHttpRequest object.");
}
return httpRequest;
}
hop this will help some one :)

how to disable submit button with ajax based on ajax response

I am trying to use something like this in my code but having no luck...
function captcha(data) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
document.getElementById("cap_error").innerHTML = httpxml.responseText;
var result = httpxml.responseText;
if (result == 'Error..try again') {
document.getElementById("regSubmit").disabled = true;
}
}
}
var url = "includes/captcha.php";
url = url + "?datacap=" + data;
url = url + "&sid=" + Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET", url, true);
httpxml.send(null);
}
Edit:
My submit button is:
<input type="submit" value="Submit" id="regSubmit" name="Submit"/>
When ajax function returns 'Error..try again' regSubmit button should be disabled. But this function is not working for my right now.
if (result == 'Error..try again')
{
document.getElementById("regSubmit").disabled = true;
}
This is what we have in our app:
document.getElementById('buttonId').disabled=true;
And it works.
Two things:
1 - Make should you clear your browser cache after you change your javascript.
2 - Put an alert before you disable your button to make sure you are getting into your 'if' statement.

Categories