MakeRequest doesn't work - javascript

I do request:
And I receive XML:
<?xml version="1.0" encoding="UTF-8"?>
<search>
<location id="18171" client_id="511">
<site>3</site>
.....
After refresh browser I receive:
<?xml version="1.0" encoding="UTF-8"?>
</search>
Only If i close and open browser I receive
<?xml version="1.0" encoding="UTF-8"?>
<search>
<location id="18171" client_id="511">
<site>3</site>
Why? I don't want to close and open browser everytime
Thank you
My code:
function makeRequestXML(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = ContentsXML;
http_request.open('GET', url, true);
http_request.send(null);
}
function ContentsXML() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
number_checkbox = 0;
var xmldoc = http_request.responseXML;

This a problem with your server you are connecting to. I have no idea what it's doing, or what you expect it to be doing, but your JS is clearly hitting that server and returning data in all cases. If you are getting back bad data, that is not the fault of your JS.
It seems like the server may be sending different data based on the browser session, and relaunching the browser may reset that session.

Related

chrome 401 unauthorized javascript login

I'm currently developing a chrome extension, I need to access some http-auth protected resources (webdav). The HTTP auth is using (in the best case) a digest authentication.
The issue is : if the login/password is wrong, I can't just get a 401 status (unauthorized), Chrome pops up the regular authentication dialog. Which I don't want cause it's confusing for user and I can't save the credentials from here.
EDIT: Another use-case I faced is : I want to check if a resource is password-protected without trying to provide credentials to actualy access it.
Any ideas on how to catch the 401 without poping the Chrome's auth box ?
I try using this function:
function autoLogin(domain, user, password) {
var httpAuth;
if (window.XMLHttpRequest) {
httpAuth = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
}
else if (window.ActiveXObject) {
httpAuth = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
else {
alert("Seu browser não suporta autenticação xml. Favor autenticar no popup!");
}
var userName = domain + "\\" + user;
httpAuth.open("GET", "/_layouts/settings.aspx", false, userName, password);
httpAuth.onreadystatechange = function () {
if (httpAuth.status == 401) {
alert("wrong");
eraseCookie('AutoLoginCookieUserControl_User');
eraseCookie('AutoLoginCookieUserControl_Password');
}
else {
if ($(".pnlLogin").is(':visible')) {
$(".pnlLogin").hide();
$(".pnlUsuario").css("display", "block");
$(".avatar").css("display", "block");
var name = $().SPServices.SPGetCurrentUser({ fieldName: "Title" });
$(".loginNomeUsuario").html("Seja Bem Vindo(a) <br />" + name);
}
}
}
try {
httpAuth.send();
}
catch (err) {
console.log(err);
}
}

XMLHttpRequest error SCRIPT10

Hi all I have to connect to an external server to retrieve data.
They told me to use their script and I have to modify something because it was wrong. Now I ahve a problem when I try to lunch my request.
Return me an error into my internet explorer console
SCRIPT10: The data required for the completion of this operation are
not yet available.
This is my javascript page, the problem I think is because the query doesn't finish in time to print my result. How can I print the result when they are ready and don't return me error?
I have try to comment all my request and leave only the method "open" but the error return me every time. Why??
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
var req = null ;
function sendRequest(){
var urlStr="www.test.it";
var xmlString="";
xmlString+="<?xml version='1.0' encoding='UTF-8'?><some xml>";
createHTTPRequestObject();
var resp = getResponseText(urlStr+"?"+xmlString,null);
var xmlDoc;
xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = false;
xmlDoc.loadXML(resp);
alert(xmlDoc.xml);
}
function createHTTPRequestObject(){
req=null ;
var pXmlreq = false ;
if (window.XMLHttpRequest) {
pXmlreq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try{
pXmlreq = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
try{
pXmlreq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2) {
}
}
}
req = pXmlreq ;
}
function getResponseText(action,query,method,async,contenttype){
if(method==null){
method="POST";
}
if(async==null){
async="true";
}
if(contenttype==null){
contenttype = "application/x-www-form-urlencoded";
}
req.open(method,action, async);
req.setRequestHeader("Content-Type", contenttype);
if(query){
req.send(query);
}else{
req.send();
}
return req.responseText ;
}
</script>
</head>
<body>
<input type="button" name="Request" value="Request" onclick="sendRequest();"/>
<div id="content" />
</body>
</html>
You are trying to read the responseText before it is ready. Looks like you are treating a asynchronous call as synchronous. That would be the issue.

Status is zero in Chrome and Firefox

I have to call Rest Services using Javascript. My code is:
function CreateXMLHttpRequest() {
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("XMLHttpRequestnot supported");
}
}
function CallWebService() {
objXMLHttpRequest = CreateXMLHttpRequest();
objXMLHttpRequest.open("POST", "http://www.rest.net/services/abc.svc/json/GetXml", true);
objXMLHttpRequest.setRequestHeader("Content-Type", "application/xml;charset=UTF-8");
var packet = '<?xml version="1.0" encoding="utf-8" ?><CompanyRequest xmlns="http://schemas.datacontract.org/2004/07/abc.DomainModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><CompanyName>company</CompanyName></CompanyRequest>';
objXMLHttpRequest.onreadystatechange = function () {
if (objXMLHttpRequest.readyState == 4&&objXMLHttpRequest.status==200) {
alert(objXMLHttpRequest.responseText);
}
}
objXMLHttpRequest.send(packet);
}
The status is 200 in IE and I am able to get a response. But in Firefox and Chrome, the status is 0. How can I overcome this problem?
Thanks in advance.
You are requesting a document at http://www.rest.net and I assume you are on a different domain. In this case you are victim of the same origin policy and your calls are blocked.
It might work in IE if you have set http://www.rest.net as a trusted domain.

letting user open an xml file on client and parse it using javascript

I'm trying to let a users on my site to save and XML file one the local machine and then later to load them using the HTML file element.
Saving the file what done with iFrame.
When trying to let the user load the file i am getting exceptions all the time.
I've tried every thing i could find over the web and can't seem to find the way to do it.
I am getting all kind of exception, like cross domain or XMLHttpRequest cannot load file:///C:/fakepath/Regions.xml. Cross origin requests are only supported for HTTP.
Depending on the code i tried.
I read that HTML5 standard replace the url with "fakepath", and can't find solution for this. Is there no way to let the user load a file from his own computer to be edited? loading a specific file from server is not a problem but i want to give this freedom to the user and not decide for them what file to load, and also to let them save and load the xml on their computer and not the server
Is there a solution for this problem?
Found this codes but neither helped (and I've tried few other veriations of this):
1)
var error = "";
strFile = document.frmLoadFile.selectedFile.value;
intPos = strFile.lastIndexOf("\\");
strDirectory = strFile.substring(0, intPos);
//alert(strDirectory);
document.frmLoadFile.selectedFile.value = strDirectory;
var file = 'file:\\\\\\' + document.frmLoadFile.selectedFile.value;
try //Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(file);
}
catch (e) {
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.async = false;
xmlDoc.load(file);
}
catch (e) {
try //Google Chrome
{
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", file, false);
xmlhttp.send(null);
xmlDoc = xmlhttp.responseXML.documentElement;
}
catch (e) {
error = e.message;
}
}
}
2)
var xmlDoc;
var xmlloaded = false;
function xml_initLibrary(file) {
importXML(file);
}
function importXML(xmlfile) {
try {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlfile, false);
}
catch (Exception) {
var ie = (typeof window.ActiveXObject != 'undefined');
if (ie) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
while (xmlDoc.readyState != 4) { };
xmlDoc.load(xmlfile);
xmlloaded = true;
readXML();
}
else {
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = readXML;
xmlDoc.load(xmlfile);
xmlloaded = true;
}
}
if (!xmlloaded) {
xmlhttp.setRequestHeader('Content-Type', 'text/xml')
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
xmlloaded = true;
readXML();
}
}
function readXML() {
//console.log(xmlDoc);
}
does any one knows if there is a way to fix this? of do you need to save the files on the server?
Thank you all very much
Erez
I think you're looking for FileReader, new in HTML5. For IE < 10 you'll need to use the ActiveX FileSystemObject.
This code works for me on Chrome.
<script type="text/javascript">
function doit(e) {
var files = e.target.files;
var reader = new FileReader();
reader.onload = function() {
var parsed = new DOMParser().parseFromString(this.result, "text/xml");
console.log(parsed);
};
reader.readAsText(files[0]);
}
document.getElementById("selectfile").addEventListener("change", doit, false);​
</script>
<input type="file" id="selectfile" />
http://jsfiddle.net/xKuPV/

AJAX Permission Denied On IE?

I'm trying to make an ajax call to an external domain that is already allowing external requests by sending Access-Control-Allow-Origin:* header, but i get Permission Denied on the xmlhttp.post() line.
Here is my code:
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "http://www.domain.com", true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send();
I believe that in IE, you still can't use XMLHttpRequest for cross domain requests. For that, you need to use XDomainRequest object. Full documentation is here. I believe the reason for introducing the separate object was to allow developers to do a compatibility test before making a request that certainly would fail with older browsers.
I believe you can only use Ajax with URL's form the same domain as your calling page. It's not the external domain that disallows the request, it's your browser's security. Take a look at Same Origin Policy
This is a way to avoid cross browser scripts - otherwise imagine you have a page where you can enter your credit card info and someone injects a script that sends information you are typing to an external site. Would be a big problem to fight.
Note :Do not use "http://domain.xxx" or "http://localhost/" or "IP" for URL in Ajax.
Only use path(directory) and page name without address.
false state:
var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'http://www.example.com/dir1/dir2/page.php', true);
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);
true state:
var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST','dir1/dir2/page.php', true); // <<--- note
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);
function createAjax()
{
var ajaxHttp = null;
try
{
if(typeof ActiveXObject == 'function')
ajaxHttp = new ActiveXObject("Microsoft.XMLHTTP");
else
if(window.XMLHttpRequest)
ajaxHttp = new XMLHttpRequest();
}
catch(e)
{
alert(e.message);
return null;
}
//-------------
return ajaxHttp;
};

Categories

Resources