i'm trying to load a XML document that is not in the web application folder but on level up through a GET request. the loadXMLDoc works fine for FF and chrome but the XDR doesn't for IE.
i'm calling the method like this:
xmlDoc = loadXMLDoc("../XML/stops_group1.xml");
I'm lead to believe the problem lies in going up one level in the root directory, because it works fine for same directory folders
function loadXMLDoc(url) {
if (typeof XDomainRequest != 'undefined') {
var xdr = new XDomainRequest();
xdr.contentType = "text/plain";
xdr.timeout = 5000;
if (xdr) {
xdr.onerror = function () {
alert('XDR onerror');
alert("Got: " + xdr.responseText);
};
xdr.ontimeout = function () {
alert('XDR ontimeout');
alert("Got: " + xdr.responseText);
};
xdr.onprogress = function () {
alert("XDR onprogress");
alert("Got: " + xdr.responseText);
};
xdr.onload = function () {
alert('onload' + xdr.responseText);
callback(xdr.responseText);
};
// 2. Open connection with server using GET method
xdr.open("get", url);
// 3. Send string data to server
xdr.send("");
} else {
alert('failed to create xdr');
}
return xdr.responseXML;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.send("");
return xhr.responseXML;
}
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
I already tried adding the Access-Control-Allow-Origin in the web.config file
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
but still get the alert message for onError with responseText empty...
Any clues?
Thanks for the replies... actually my problem was other... seems that IE can't handle the UTF-16 encoding present in the xml file... changed to utf-8 and evertything is well now
Related
I have written some JavaScript to send a request to a php file which can query or post to a database. I have tried using GET and POST.
function action(theAction) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "queryDB.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function () {
// The variable xmlhttp not available here. But since this function is a member of xmlhttp, this=xmlhttp
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
document.getElementById("result").innerHTML =
document.getElementById("result").innerHTML + " " + this.responseText;
}
}
xmlhttp.send("p1=post&p2=" + theAction);
}
function showActivity () {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function () {
document.getElementById("result").innerHTML = this.responseText;
}
xmlhttp.open("GET", "queryDB.php?p1=list");
xmlhttp.send();
}
Both methods work fine but they both can be imitated by simply writing the URL of my php file followed by suitable parameters into a browser address bar. So for the GET example I could write in
https://patience5games.com/php/queryDB.php?p1=list
and I get a little report in the browser window.
This means that it is quite easy for hackers to post fake data to my database. How can I prevent that?
I want to send a message in not such an obvious way. One bodge solution using the POST method would be to have xmlhttp.setRequestHeader("Content-Type", "my message"); which I could decode at the other end. I think. But surely there must be a better way than that?
I'm switching requests from content script to background script and the code is identical but somehow the XMLHttpRequest doesn't keep me logged in.
My goal is to log in a user and change his password - which requires 2 POST requests. The second one fails.
Background script:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
// FIRST REQUEST
var loginRequest = new XMLHttpRequest();
loginRequest.open("POST", "https://.../login.php", true);
loginRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
loginRequest.send("user credentials...");
loginRequest.onload = function() {
// SECOND REQUEST
var changeRequest = new XMLHttpRequest();
changeRequest.open("POST", "https://.../changePassword", true);
changeRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
changeRequest.send("old pass... new pass...");
changeRequest.onload = function() {
// ISSUE: changeRequest.responseURL is back at the login page? WHY?
if (changeRequest.responseText.includes("Password successfully changed!")) {
sendResponse({passwordChanged: true});
} else {
sendResponse({passwordChanged: false});
}
}
}
return true;
});
PLEASE NOTE: This code works perfectly fine in the content script!
loginRequest.anonymous = true;
has solved the problem due to unnecessary cookies when sending from background script.
My extension tried to log me in on a certain website when a login button is present. I now want to add a check if the login failed, so the script doesnt loop and instead I can handle it in some other way. My problem is that the check never actually happens.
I want to check by looking for an auth cookie that is set in the responseheader, but it doesn't work, because nothing in the function() actually executes.
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://loginpage.com/login?login=1&password=2", true);
xhr.send();
xhr.onreadystatechange = function() {
if(this.readyState == this.HEADERS_RECEIVED) {
var cookies = xhr.getResponseHeader("Set-Cookie")
if(cookies.includes("auth=")) {
everythingworks();
} else {
wrongcredentials();
}
}
};
<script type="text/javascript">
$(document).ready(function () {
function validemail(isemail) {
var emailReg = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return emailReg.test(isemail);
}
$("#<%=txtEmail.ClientID %>").blur(function () {
if ($("#<%=txtEmail.ClientID %>").siblings().size() > 0) {
$("div").remove(".tooltips");
}
});
$("#btnSubmit").click(function () {
var name = $("#<%=txtName.ClientID %>").val();
var email = $("#<%=txtEmail.ClientID %>").val();
var message = $("#<%=txtMessage.ClientID %>").val();
if (name != '' && email != '' && message != '') {
if (validemail(email)) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://abcname.azurewebsites.net/Contact.aspx/InsertData",
data: "{'customername':'" + name + "','customeremail':'" + email + "','customermessage':'" + message + "'}",
dataType: "json",
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$("#<%=txtName.ClientID %>").val('');
$("#<%=txtEmail.ClientID %>").val('');
$("#<%=txtMessage.ClientID %>").val('');
alert('Details submitted successfully');
}
},
error: function (result) {
alert("An error occur while submitting details.");
}
});
}
else {
$("#<%=txtEmail.ClientID %>").focus();
$("<div class='tooltips'><span>Invalid Email Address</span></div>").insertAfter("#<%=txtEmail.ClientID %>");
}
}
else {
alert('Please fill all the fields');
}
});
});
</script>
Above code perfectly working on local host but it doesn't on server side. If there would any error on the .cs file then it will show alert box, but it even doesn't showing alert box that "An error occur while submitting details"
url: "http://abcname.azurewebsites.net/Contact.aspx/InsertData",
Based on the URL, I suspected that you were using WebMethod to handle AJAX request in WebForms application. Since there were .aspx suffix in your URL, please make sure you have commented out the following code which default exist in RouteConfig.cs.
//settings.AutoRedirectMode = RedirectMode.Permanent;
but it even doesn't showing alert box that "An error occur while submitting details"
var obj = data.d;
The reason for this may be that the response is came back but it doesn’t contain a property named d or its value doesn’t equals ‘true’. I suggest use a tool to view the detail response message. Fiddler is common tool which could help you do it.
In addition, did you send the AJAX request from different domain as 'http://abcname.azurewebsites.net'? For example, the code which you posted is in the website named 'http://defname.azurewebsites.net'. If it is true, you need to configure CORS in abcname web app. Steps below are for your reference.
In Azure portal, open web app abcname.
On menus bar, click CORS.
Input the domain name in the ‘Allowed Regions’ textboxes.
Click [Save] button to save all your operations.
I am searching for a way to get the control on the elements inside a document. The problem is, the document is attached to an iFrame.
Here's an example:
.goto('https://wirecard-sandbox-engine.thesolution.com/engine/hpp/')
.use(iframe.withFrameName('wc', function (nightmare) {
nightmare
.type('#account_number', accountNumber)
.screenshot(resultfolder + '\\06-Card-Number.png')
.type('#card_security_code', testData.securityCode)
.selectIndex('#expiration_month_list', 1)
.selectIndex('#expiration_year_list', 4)
.click('span[id="hpp-form-submit"]')
}))
What I am trying to do above is:
Getting the iFrame with the Url.
Using this to get the control on every element in iFrame.
I encountered a similar issue. For one reason or another (Windows? Outdated?) the package nightmare-iframe was not working for me.
So I did this using pure DOM, which would transcribe for you:
var info = {
"account": account_number,
"security": testData.security_code;
};
nightmare.wait( () => {
/* Return true when the iframe is loaded */
var iframe = document.querySelector("iframe[name='wc']");
if (!iframe) {
return false;
}
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
return iframeDocument.querySelector("#account_number") != null;
}).evaluate( (info) => {
var iframe = document.querySelector("iframe[name='wc']");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
iframeDocument.querySelector("#account_number").value = info.account;
iframeDocument.querySelector("#card_security_code").value = info.security;
//also use DOM to set proper date
...
iframeDocument.querySelector("span#hpp-form-submit").click();
}, info).then( () => {
console.log("submit done!");
}).catch((error) => {
console.error("Error in iframe magic", error);
});
This only works of course if the iframe is in the same domain as the main page and same-origin is allowed for the iframe. My use case was logging into paypal from a merchant's page.
For iframes with different origin, nightmare-iframe would be the package to use but then an error is needed to see what's the problem.