function loaded() {
var xmldoc,
currenttime = new Date().getTime(),
req,
address = 'http://webservices.foo.com/eSignalQuotes/eSignalQuotes.asmx/GetDelayedQuotes?',
symbols = 'symbols=' + '+c,s,ct,zw,kw,adm+',
cusip = '&cusip=',
fields = '&fields=' + 'desc,month,year,recent,netchg,-decimal',
type = '&type=' + 'future,stock,index',
dispfullname = '&dispfullname=' + 'true',
datefmt = '&datefmt=',
timefmt = '&timefmt=',
timestamp = '&' + Math.floor(currenttime/3600000),
query = address + symbols + cusip + fields + type + dispfullname + datefmt + timefmt + timestamp;
;
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.addEventListener('error', function(e) {alert('Error');}, false);
req.addEventListener('load', function(e) {xmldoc = req.responseText;}, false);
req.open('GET', query, true);
req.send();
}
That's what my code looks like, and it always throws an error in Safari and Firefox. The crazy thing is if I remove the event listeners, and change the response type to responseText, Internet Explorer gives me output. I tried overrideMimetype, but that didn't seem to help. If I check the response in Firefox or Safari, I get null. I'm at a loss, and any help would be appreciated.
I should mention that I'd prefer to avoid any 3rd party libraries for this.
Update:
The error occurs during the progress event, and if I check .lengthComputable I get false
Update 2:
Safari sheds more light on the issue:
XMLHttpRequest cannot load Origin is not allowed by Access-Control-Allow-Origin.
I can't be 100% sure, but it seems to me that the issue involved cross-site communication. What I ended up doing was having a PHP script download the file then I used javascript to get it locally.
<?php
$mark = $_GET['mark'];
$xmldoc = new DOMDocument();
$xmldoc -> preserveWhiteSpace = false;
$xmldoc -> formatOutput = true;
$xmldoc -> load($mark);
unlink('fenced.xml');
echo $xmldoc -> save('fenced.xml');
?>
Javascript:
localreq.open('GET', 'fenced.xml', true);
localreq.addEventListener('load', function(e) {xmldoc = localreq.responseXML;}, false);
localreq.send();
Related
I'm trying to insert a new user into mysql. I have tried to use jQuery, but it doesn't seem to be working. I tried to use pure javascript, but it's the same. It has no response after I click on the button. What's wrong?
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var shop = document.getElementById("shop");
var http = new XMLHttpRequest();
http.open("POST", "http://xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
http.send(params);
http.onload = function() {
alert(http.responseText);
};
}
There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php, so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var http = new XMLHttpRequest();
// removed the http:// protocol, assuming you're going for a local AJAX call
http.open("POST", "xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// get values of the form fields, don't submit the full element
// also added the plus (+) character before the final pw1
var params = "ac=" + acR.value + "&pw1=" + pw1.value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests
Try to use a JQuery post.
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
alert( "Data inserted: " + data );
});
Backend handles this post and then implement the insert action for example in NodeJs(express)
app.post("/xyz", function(req, res, next) {
var obj = {};
obj[acR] = body.ac;
obj[pw1] = body.pw1;
mysql.insert(obj);
});
I'm using some JavaScript to send an Ajax request to an Arduino webserver and change the HTML on a webpage.
In Safari this has been working great, but when I try to load it in Firefox and Google Chrome the document elements never update. In the debugger consoles I can see the requests and responses coming back so I'm guessing that there is an issue with parsing the response to an array?
Here is the code:
function GetSwitchState()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseText != null) {
var response = this.responseText;
var comma = ",";
var inputArray = response.split(comma);
var green = inputArray[0];
var red = inputArray[1];
var fault = inputArray[2];
var counter = inputArray[3];
document.getElementById('green').innerHTML = green;
document.getElementById("red").innerHTML = red;
document.getElementById("status").innerHTML = fault;
document.getElementById("cars").innerHTML = counter;
}
}
}
}
request.open("GET", "url" + nocache, true);
request.send(null);
setTimeout('GetSwitchState()', 1000);
}
The response from the Arduino webserver is four comma-separated values.
Okay it looks like the issue was actually getting past the
{
if (this.readyState == 4) {
if (this.status == 200) {
arguments. When I changed it to:
{
if(response.readState == 4) {
I was able to move past that statement in firefox. To get the status to 200 instead of 0 I needed to modify the response header on the arduino side to include:
Access-Control-Allow-Origin: *
To allow Cross Origin Domain Requests in FireFox. Once I made these changes the code works great, I guess I was barking up the wrong tree with my array assumption.
Thanks for the help!
What I did today was pretty much the same!
When I ran an Ajax request to a PHP file and wanted to return an array I needed to specify the return-datatype as "json". In my PHP file I then returned my values like this:
return json_encode(array(
'success' => false,
'error' => $_POST['password_hashed']
));
I was acctually using jQuery to run the request. That looks like this:
$.ajax({
type: 'POST',
url: 'script.php',
data: 'password_hashed=' + hex_sha512(str_password) + '&email=' + str_email, //Clientside password hashing
cache: false,
dataType: 'json',
success: function(value){
//Ajax successfully ran
alert(value.success + '_' + value.error); //=false_[hash]
},
error: function(){
//Ajax error occured -> Display error message in specified element
alert('error with request');
}
});
I just started with Ajax two days ago, and this may not help a lot, but it is worth trying.
Below code is from the html5uploader and it works well on all browsers except IE 10.
I have tried my best to include a function where IE is detected and the dropped file read but was unable to get this working in IE.
How do i modify code in the function below to include Internet Explorer 10?
Full Javascript code here.
Link to uploader here.
// Firefox 3.6, Chrome 6, WebKit
if(window.FileReader) {
// Once the process of reading file
this.loadEnd = function() {
bin = reader.result;
xhr = new XMLHttpRequest();
xhr.open('POST', targetPHP+'?up=true', true);
var boundary = 'xxxxxxxxx';
var body = '--' + boundary + "\r\n";
body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n";
body += "Content-Type: application/octet-stream\r\n\r\n";
body += bin + "\r\n";
body += '--' + boundary + '--';
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
// Firefox 3.6 provides a feature sendAsBinary ()
if(xhr.sendAsBinary != null) {
xhr.sendAsBinary(body);
// Chrome 7 sends data but you must use the base64_decode on the PHP side
} else {
xhr.open('POST', targetPHP+'?up=true&base64=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(window.btoa(bin));
}
if (show) {
var newFile = document.createElement('div');
newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
document.getElementById(show).appendChild(newFile);
}
if (status) {
document.getElementById(status).innerHTML = 'Loaded : 100%<br/>Next file ...';
}
}
perhaps this can help other people, even if the problem is resolved for you:
1) be sure you force your browser to IE10 : <meta http-equiv="X-UA-Compatible" content="IE=edge">
2) don't use reader.readAsBinaryString(file); but reader.readAsDataURL(file); for IE
3) send the XHR object with xhr.send and do not use btoa (just do xhr.send((bin));)
4) Generally, in order your code to be comptatible with all browser, use if (navigator.appName === "Microsoft Internet Explorer") { ... } and open your XHR object with a different target for each browser (like this: xhr.open('POST', targetPHP+'?up=true&browser=IE', true); ), because if will be handled differently by PHP.
Everything is explained here : How can i change the XmlHttpRequest or FileAPI used in html5uploader to support IE
From System.Shell.itemFromFileDrop I get System.Shell.Item object item. I've tried this:
var oStream = new ActiveXObject("ADODB.Stream");
oStream.Type = 1;
oStream.Open();
oStream.LoadFromFile(item.path);
content = oStream.Read();
var thisObj = this;
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myUrl.com//");
xhr.send(content); //NOT WORKING
oStream.Close();
oStream = null;
but I really don't know what to pass in the xhr.send function.
The serverside PHP code is as simple as it could be:
if (file_exists($_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]);
header("{$_SERVER['SERVER_PROTOCOL']} 200 OK");
header('Content-Type: text/plain');
echo "http://myUrl.com/" .$_FILES["file"]["name"];
}
any ideas what am I doing wrong ? Or any ideas about how to upload files from windows gadget at all?
I am learning this stuff so my code might not be pretty... but would appreciate some help :)
I have not written the following code but got it from somewhere else off the web:
function text_xml()
{
realXmlUrl="http://jumac.com/del_me_fruits.xml";
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/xml');
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML;
}
function response_xml()
{
if (self.http_request.readyState == 4)
{
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(http_request.responseText);
}
}
function getFruits(xml) {
var fruits = xml.getElementsByTagName("fruits")[0];
if (fruits) {
var fruitsNodes = fruits.childNodes;
if (fruitsNodes) {
for (var i = 0; i < fruitsNodes.length; i++) {
var name = fruitsNodes[i].getAttribute("name");
var colour = fruitsNodes[i].getAttribute("colour");
alert("Fruit " + name + " is coloured " + colour);
}
}
}
}
And the error I am getting is:
Error: xml.getElementsByTagName is not a function
What am I doing wrong?
responseText is a string, not an XML. Are you looking for responseXML?
Update
If your script is loaded from a different domain than the XML document you're loading (http://jumac.com/del_me_fruits.xml), then XMLHttpRequest will act differently depedning on the browser.
On IE 8, it will pop up a warning window complaining that "The page is accessing information that is not under its control. This poses a security risk. Do you want to continue?" if you click yes, then it will work correctly (i.e., the XML will load and the alerts for the fruits will be displayed).
On Chrome 12, however, it doesn't pop anything and it will say that "XMLHttpRequest cannot load http://jumac.com/del_me_fruits.xml. Origin http://localhost:54671 is not allowed by Access-Control-Allow-Origin." Because of this error, the responseXML property of the request object will be null and you'll see the error you have.
There are other questions regarding cross-domain XMLHttpRequest where you may find how to solve your issues, such as Cross-site XMLHttpRequest and http://code.google.com/chrome/extensions/xhr.html.
<body>
<script type="text/javascript">
function text_xml() {
realXmlUrl = "http://jumac.com/del_me_fruits.xml";
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML; // this doesn't have anything
}
function response_xml() {
if (self.http_request.readyState == 4) {
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(http_request.responseXML);
}
}
function getFruits(xml) {
var fruits = xml.getElementsByTagName("fruits")[0];
if (fruits) {
var fruitsNodes = fruits.childNodes;
if (fruitsNodes) {
for (var i = 0; i < fruitsNodes.length; i++) {
var name = fruitsNodes[i].getAttribute("name");
var colour = fruitsNodes[i].getAttribute("colour");
alert("Fruit " + name + " is coloured " + colour);
}
}
}
}
</script>
<input type="button" value="Click me" onclick="text_xml();" />
<p><div id="ex"></div></p>
</body>
I usually love using a dictionary when working with any kind of transferring data across servers.
MkNxGn.pro provides a sleek way to make XML HTTP requests via MkNxGn Proquest.
Load Proquest, This can be separate from the code<script src="https://mknxgn.pro/scripts/Proquest_Proquest-v1.0.js"></script>
<script>
Proquest("POST",
URL_HERE,
DATA,<br>
HEADERS,
RType,
Ignore JSON errors,
Callback);
</script>
That way you could easily write:
<script>
Proquest("GET", "http://jumac.com/del_me_fruits.xml", Skip, {'Content-type': 'text/xml'}, 'response', false, function(resp) {
resp.overrideMimeType('text/xml'); //Looks like you want it to be XML if its not.
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(resp.responseXML);
});
</script>
ignoring jason's edit to rewrite it better.
Consider using a javascript libary like jquery.
jquery ajax is pretty much self explaining and you don't have to mess with brower compatibility. http://jquery.com/