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/
Related
I am trying working off of https://wiki.apache.org/solr/SolJSON tutorial. I have put my url for solr in the code, copied from solr admin query result to make sure the query should return something.
I try typing in "title:Asian" into text box (that field/search term combo returned results in the admin console query) but when the button is hit, textbox just clears and nothing in output spot.
I used the dev tools from [F12] key of browser to check console and see there was no errors given there, such as for syntax, so not due to that.
Perhaps I am understanding how the url for query works or should be here? If I leave out local host part as shown I just get error for not specifying local full path.
Does anyone see anything wrong here, or have any ideas/tips of what more to do to try and solve the issue?
[ If I must do/add anything else to make good/better post here, please do explain so I can fix :) ]
<html>
<head>
<title>Solr Ajax Example</title>
<meta charset="UTF-8">
<script language="Javascript">
// derived from http://www.degraeve.com/reference/simple-ajax-example.php
function xmlhttpPost(strURL)
{
var xmlHttpReq = false;
var self = this;
if (window.XMLHttpRequest) { // Mozilla/Safari
self.xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
};
var params = getstandardargs().concat(getquerystring());
var strData = params.join('&');
self.xmlHttpReq.send(strData);
//document.getElementById("raw").innerHTML = strData;
return false;
}
function getstandardargs() {
var params = [
'wt=json'
, 'indent=on'
, 'hl=true'
];
return params;
}
function getquerystring() {
var form = document.forms['f1'];
var query = form.query.value;
qstr = 'q=' + escape(query);
return qstr;
}
// this function does all the work of parsing the solr response and updating the page.
function updatepage(str)
{
document.getElementById("raw").innerHTML = str;
var rsp = eval("("+str+")"); // use eval to parse Solr's JSON response
var html = "<br>numFound=" + rsp.response.numFound;
var first = rsp.response.docs[0];
html += "<br>product name=" + first.name;
var hl = rsp.highlighting[first.id];
if (hl.name != null) { html += "<br>name highlighted: " + hl.name[0]; }
if (hl.features != null) { html += "<br>features highligted: " + hl.features[0]; }
document.getElementById("result").innerHTML = html;
}
</script>
</head>
<body>
<form name="f1" onsubmit='xmlhttpPost("http://localhost:8983/solr/myCore/select?")'>
<p>query: <input name="query" type="text">
<input value="Go" type="submit"></p>
<div id="result"></div>
<p/><pre>Raw JSON String/output: <div id="raw"></div></pre>
</form>
</body>
</html>
Hello,
i searching around the internet, and can't find a full "tutorial", how to write a code, that's if no internet connection automatically shows a error message. I started with the Visual Studio to create a Windows 10 App with Javascript. I searched around, and found some examples with jQuery or AJAX on stackoverflow, but seem's not working for my application. Can someone share a code, that i can put in my application?
I creating a app for my Website, with some addition features, and it's need's internet connection.
Thanks
you can use the NetworkConnectivityLevel, NetworkInformation.getInternetConnectionProfile and getNetworkConnectivityLevel to do this, and show the information with a MessageDialog in the default.js like this:
var connections = Windows.Networking.Connectivity.NetworkInformation.getInternetConnectionProfile();
if (connections != null) {
var networkConnectivityLevel = connections.getNetworkConnectivityLevel();
if (networkConnectivityLevel == Windows.Networking.Connectivity.NetworkConnectivityLevel.internetAccess) {
var msg = new Windows.UI.Popups.MessageDialog("Internet access OK.");
} else if (networkConnectivityLevel == Windows.Networking.Connectivity.NetworkConnectivityLevel.constrainedInternetAccess) {
var msg = new Windows.UI.Popups.MessageDialog("Limited internet access.");
} else if (networkConnectivityLevel == Windows.Networking.Connectivity.NetworkConnectivityLevel.localAccess) {
var msg = new Windows.UI.Popups.MessageDialog("Local network access only.");
} else if (networkConnectivityLevel == Windows.Networking.Connectivity.NetworkConnectivityLevel.none) {
var msg = new Windows.UI.Popups.MessageDialog("No internet access.");
}
msg.showAsync();
} else {
var msg = new Windows.UI.Popups.MessageDialog("No internet access.");
msg.showAsync();
}
$.get('/').fail(function(){
//request failed for some reason. probably internet down
console.log("your internet is down");
});
You can use some HTTP test service as follows:
<html>
<body>
<div id="status" style="width:100px;height:40px;"></div>
<script>
function GetConnectionStatusToElement(element) {
var request = new XMLHttpRequest();
request.open("GET", "https://httpbin.org/", true);
request.onload = function () {
element.innerHTML = "Connected";
};
request.onerror = function () {
element.innerHTML = "Not Connected";
};
request.send();
}
GetConnectionStatusToElement(document.getElementById("status"));
</script>
</body>
<html>
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.
I'd like to make a popup preview of a textarea, using a PHP function inside the popup.
Let's say you type "Hello world" in the textarea, then you click "preview" and you get your text converted to "Hey you" by a PHP function in a popup (of course the function is not that simple, that's the reason why I can't adapt this in pure javascript).
Is it possible to do so ?
I know it could easily send the form to an intermediate page, but I must keep the form in background... that's why I need a quick preview on fly.
I did the following:
function PreviewMe() {
var newWin = window.open("", "_blank");
newWin.document.write("<html><body>"+document.getElementById('myText').value+"</body></html>");
newWin.document.close();
}
and
<textarea id="myText" ... />
<input type="submit" ... onclick="PreviewMe();">
Obviously it works without reformatting anything, so how to reformat this result in the popup please ?
Would it be possible (and mayber a better option) to use XMLHttpRequest ?
Thx !
Yes , you should use an XHR request to send data to a script which will return you data to be manipulated on the client side.
Thanks, it was by far easier in the end.
In case it might help others, here is what I've done.
Js function became :
function PreviewMe() {
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("XMLHTTPRequest not supported...");
return;
}
xhr.open("POST", "page.php", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById('show').innerHTML = xhr.responseText;
}
};
xhr.send("var="+document.getElementById('myText').value+"");
return;
}
Of course page.php includes my PHP function, show is the id of the div where the result is printed.
Does anyone know of a tutorial on how to read data from a server side file with JS? I cant seem to find any topics on this when I google it. I tried to use but it does not seem to work. I just want to read some data from a file to display on the page. Is this even possible?
var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
To achieve this, you would have to retrieve the file from the server using a method called AJAX.
I'd look into JavaScript libraries such as Mootools and jQuery. They make AJAX very simple use.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
<script type="text/javascript">
//This event is called when the DOM is fully loaded
window.addEvent("domready",function(){
//Creating a new AJAX request that will request 'test.csv' from the current directory
var csvRequest = new Request({
url:"test.csv",
onSuccess:function(response){
//The response text is available in the 'response' variable
//Set the value of the textarea with the id 'csvResponse' to the response
$("csvResponse").value = response;
}
}).send(); //Don't forget to send our request!
});
</script>
</head>
<body>
<textarea rows="5" cols="25" id="csvResponse"></textarea>
</body>
</html>
If you upload that to the directory that test.csv resides in on your webserver and load the page, you should see the contents of test.csv appear in the textarea defined.
You need to use AJAX. With jQuery library the code can look like this:
$.ajax({ url: "test.csv", success: function(file_content) {
console.log(file_content);
}
});
or if you don't want to use libraries use raw XMLHTTPRequest object (but you I has different names on different browsers
function xhr(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
} catch(e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
req = xhr();
req.open("GET", "test.cvs");
req.onreadystatechange = function() {
console.log(req.responseText);
};
req.send(null);
UPDATE 2017 there is new fetch api, you can use it like this:
fetch('test.csv').then(function(response) {
if (response.status !== 200) {
throw response.status;
}
return response.text();
}).then(function(file_content) {
console.log(file_content);
}).catch(function(status) {
console.log('Error ' + status);
});
the support is pretty good if you need to support browser that don't support fetch API you can use polyfill that github created