I am using the XMLHttpRequest object for my AJAX calls which has been working fine across browsers with a callback handler I have created to return JSON based on the request type and arguments etc.
But I am now integrating an external RESTful API to return a JSON string and for some reason it only works for me in IE (tested in IE 8). Using fiddler 2 I have determined that the API is returning the correct data.
I get the XMLHttpRequest.readyState of 4 but XMLHttpRequest.status only returns 0 for Chrome, Safari and FF. I read that sometimes when using a local server (test server) you always get a status of zero so I bypassed my check for status but still got a blank string for XMLHttpRequest.responseText.
function ajaxRequest(requestType,url) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
switch (requestType)
{
case 5:
//Home postcode search
showAddresses("home", xmlhttp.responseText);
break;
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
You should upgrade to jQuery as it will handle this request for nearly all browsers. But if you really want to know how to use XMLHttpRequest across all browsers, here's some code that seems to do the trick: https://github.com/ilinsky/xmlhttprequest/blob/master/XMLHttpRequest.js
Or, just pick apart jQuery's implementation.
http://api.jquery.com/category/ajax/
Hope this helps.
My issue was that I was using an external API and xmlHttpRequest only allows you to makes calls on the same server. I moved my data call into my server code and got the response from my callback handling page instead of going straight out to the API.
Related
I'm a beginner in Javascript , and I want to understand what the method XMLHttpRequest does.
This is the code that I was reading, and I was wondering if someone could explain what it is doing:
var xhttp;
xhttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();
Hi I am not really good in explanations, but I will try to explain this in details as I see and understand this.
The XMLHttpRequest is an object. It is used for exchanging of data with a server. So with its use you can send some data to the script on the server(request) and get some data back from it(response). That response data can be displayed instantly on the page without page reloading. So this process call AJAX.
I would read your provided code as
//define a variable
var xhttp;
/*assign a XMLHttpRequest object to this variable
check if the global object window has a XMLHttpRequest object already
if not and user have a newer browser, create one (new XMLHttpRequest - for IE7+, Firefox, Chrome, Opera, Safari browsers) or user have an older browser (ActiveXObject("Microsoft.XMLHTTP") - for IE6, IE5 browsers)
xhttp.open method specifies the type of request(method GET, Script on server, asynchronous)
xhttp.send method sends the request to a server*/
xhttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();
But you have to check the readyState property of the XMLHttpRequest object as well
xmlhttp.onreadystatechange = function() {
//4: request finished and response is ready
//200: "OK"
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//display of returned data from the server
//it is available in this property - xmlhttp.responseText
}
}
The whole peace of code should look like:
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//display of returned data from the server
//jquery example
$('div').html(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "script.php", true);
xmlhttp.send();
Hopefully this helped, good luck!
It's a reference to an AJAX request.
See more at the MDN site.
In a nutshell, it is sending a GET request to script.php.
An XMLHttpRequest is a JavaScript object made for making AJAX request. I am not fully sure that code is correct. Usually you make an instance of the XMLHttpRequest object. Then you check the window ready state to make the request. Finally you make the request. This is an example of that:
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
I hope that helps!
Happy coding!
I want to post data using XMLHttpRequest in a form and provide the same functionality under various environments. The following well-known code creates the request for me.
function createRequest() {
var result = null;
if (window.ActiveXObject) {
// MSIE
result = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
// FireFox, Safari, etc.
result = new XMLHttpRequest();
if (typeof xmlhttp.overrideMimeType != 'undefined') {
result.overrideMimeType('text/xml'); // Or anything else
}
}
else {
alert("What a bad browser!")
// No known mechanism -- consider aborting the application
}
return result;
}
This works fine in the system web-browser and in the default web/browser of iNotes client. But when run in a normal form in iNotes client, no suitable object is found to send the request.
My question is whether iNotes client provides some alternative for sending such requests.
A negative answer would also be appreciated since it would help me make decisions!
I'm using javascript to pass a dynamic url to iframe src. but sometimes the url does not exist, how could i detect the non-exist url beforehand, so that i can hide the iframe that with 404 error.
Due to my low reputation I couldn't comment on Derek 朕會功夫's answer.
I've tried that code as it is and it didn't work well. There are three issues on Derek 朕會功夫's code.
The first is that the time to async send the request and change its property 'status' is slower than to execute the next expression - if(request.status === "404"). So the request.status will eventually, due to internet band, remain on status 0 (zero), and it won't achieve the code right below if. To fix that is easy: change 'true' to 'false' on method open of the ajax request. This will cause a brief (or not so) block on your code (due to synchronous call), but will change the status of the request before reaching the test on if.
The second is that the status is an integer. Using '===' javascript comparison operator you're trying to compare if the left side object is identical to one on the right side. To make this work there are two ways:
Remove the quotes that surrounds 404, making it an integer;
Use the javascript's operator '==' so you will be testing if the two objects are similar.
The third is that the object XMLHttpRequest only works on newer browsers (Firefox, Chrome and IE7+). If you want that snippet to work on all browsers you have to do in the way W3Schools suggests: w3schools ajax
The code that really worked for me was:
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
if (request.status === 404) {
alert("The page you are trying to reach is not available.");
}
Use a XHR and see if it responds you a 404 or not.
var request = new XMLHttpRequest();
request.open('GET', 'http://www.mozilla.org', true);
request.onreadystatechange = function(){
if (request.readyState === 4){
if (request.status === 404) {
alert("Oh no, it does not exist!");
}
}
};
request.send();
But notice that it will only work on the same origin. For another host, you will have to use a server-side language to do that, which you will have to figure it out by yourself.
I found this worked in my scenario.
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
$.get("urlToCheck.com").done(function () {
alert("success");
}).fail(function () {
alert("failed.");
});
I created this method, it is ideal because it aborts the connection without downloading it in its entirety, ideal for checking if videos or large images exist, decreasing the response time and the need to download the entire file
// if-url-exist.js v1
function ifUrlExist(url, callback) {
let request = new XMLHttpRequest;
request.open('GET', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Accept', '*/*');
request.onprogress = function(event) {
let status = event.target.status;
let statusFirstNumber = (status).toString()[0];
switch (statusFirstNumber) {
case '2':
request.abort();
return callback(true);
default:
request.abort();
return callback(false);
};
};
request.send('');
};
Example of use:
ifUrlExist(url, function(exists) {
console.log(exists);
});
You could test the url via AJAX and read the status code - that is if the URL is in the same domain.
If it's a remote domain, you could have a server script on your own domain check out a remote URL.
Using async/await, this worked for me for opening a new tab; I needed to detect a 404 for the same reason as the OP:
openHelp : async function(iPossiblyBogusURL) {
const defaultURL = `http://guaranteedToWork.xyz`;
const response = await fetch(iPossiblyBogusURL);
if (response.status == 200) {
window.open(iPossiblyBogusURL, `_blank`);
} else if (response.status === 404) {
window.open(defaultURL, `_blank`);
}
},
You can try and do a simple GET on the page, if you get a 200 back it means the page exists. Try this (using jQuery), the function is the success callback function on a successful page load. Note this will only work on sites within your domain to prevent XSS. Other domains will have to be handled server side
$.get(
yourURL,
function(data, textStatus, jqXHR) {
//load the iframe here...
}
);
There is no need to make a separate HTTP request to check beforehand.
You could switch the logic around: only display the iframe if it has been loaded successfully. For this purpose, you can attach an onload event listener to the iframe.
See this related question for details: Capture iframe load complete event
In my extension, I create Access Level as "All" as well as I add whitelists as http://*/* too for every domain.
And I have following code in my JS file (which run as end script):
var feedbackmsg = "message goes here";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://mysitename.com/feedback.php', true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("html=" + feedbackmsg);
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.getAllResponseHeaders());
if (xmlhttp.status == 200) {
alert("send");
} else {
alert("error");
}
}
}
Whenever I run it, I am getting no header respond in alert box as well as error alert message. How can I resolve the problem?
Whether or not it's an extension, XMLHttpRequest (if injected into a page) isn't allowed to access anything outside the page's current domain, I think. The console just says that the request was cancelled. At least, that was the case for me when I tested it just now. (I didn't have any urls in the whitelist or blacklist when I tested, but the Access option was set to "all".)
You can try going to the same domain as the one you want to "call" with the XHR object in your code, and see if it succeeds then. If it does, you'll know it's because the domain of the page and the XHR request must match.
However, it appears you can do cross-site ajax request from the extension's global page (oddly enough). At least it seemed to work for me just now. That's actually a little scary (I'd prefer it to be more difficult to call up a random server from an extension) but it worked.
Don't know if that helps you out, though.
I am quite new in this area.
I need to find out how to make a request to my solr server using Ajax
How can I give a url(my solr server's url) in request
Any body know how to deal with this?
How can i make a request to the below mentioned url
http://mysite:8080/solr/select/?q=%2A%3A%2A&version=2.2&start=0&rows=100&indent=on
See here: Corrected the Code Snippet as below
function getProductIds() {
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) console.dir(xmlhttp);
else alert('no response');
var ajaxURL = "http://localhost:8080/solr/select/?q=*:*&version=2.2&start=0&rows=100&indent=on";
xmlhttp.open("GET", ajaxURL, true);
xmlhttp.send();
}
This is my code, it always showing "no response"
Thanks.
You will have to prepare the URL before sending in the request first get the URl using javascript and then encode it to ajax format like below
var URL = location.href;
var ajaxURL = encodeURIComponent(URL);
xmlhttp.open("GET",ajaxURL,true);
after reading your question clearly it seemed it is a static URL hence you can do below
var URL = "http://localhost:8080/blah blah blah";
xmlhttp.open("GET",URL,true);
Are you sure it is Get request. because get requests are most of the time cached. also log the response object into Firebug console and inspect the object to know more. Since you get no response that means the server did not send you anything for the request you made.
I'm just now working on XMLHttpRequests to solr as well and I was stuck with what seems like an identical problem. I too am quite new at this. However, the problem for me was that of same origin policy. Firefox seems to give very little feedback when this problem occurs. Chrome at least give you a error message (most of the time?).
In Chrome you can get around this, but only for development purposes, by starting it with the '--disable-web-security' command line option.
I'm yet to find a good workaround for this problem for Solr. In general you avoid the restriction by only using requests with relative paths, but that doesn't seem possible when doing a request to another port.
Ways to circumvent the policy (I haven't had time to study this too much yet)
$.ajax({
url: "url path",
context: document.body
}).done(function(data) {
alert(data);
});
This one also will work.