For some reason the following code works in Internet Explorer but not in Chrome or Firefox.
in this browsers I receive the:
"Not able to retrieve sliders data."
alert.
I would love for some help with this one.
Thanks.
Here is my JavaScript code:
<script>
if (navigator.appName == "Microsoft Internet Explorer")
{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
request = new XMLHttpRequest();
}
if (request == null)
alert ("Your browser doesn't support XMLHttpRequest");
function getSelectedText(elementId)
{
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].value;
}
function sendRequest()
{
debugger;
var type = getSelectedText('dropdown');
//alert("The chosen type: "+type);
var url = 'https://tomcat-emildesign.rhcloud.com/coupons/Client/serveranswer.jsp?type=' + type;
request.open("GET", url, true);
request.onreadystatechange= processRequest;
request.send(null);
}
function processRequest()
{
if (request.readyState == 4)
{
if (request.status == 200)
{
parseMessage();
}
else
{
alert ( "Not able to retrieve sliders data." );
}
}
}
function parseMessage()
{
// Assign the XML file to a var variable.
var doc = request.responseXML;
var pending, hires, rejected;
if(navigator.appName == "Microsoft Internet Explorer")
{
pending = doc.documentElement.getElementsByTagName('pending').item(0).text;
hires = doc.documentElement.getElementsByTagName('hires').item(0).text;
rejected = doc.documentElement.getElementsByTagName('rejected').item(0).text;
}
else
{
pending = doc.documentElement.getElementsByTagName('pending')[0].textContent;
hires = doc.documentElement.getElementsByTagName('hires')[0].textContent;
rejected = doc.documentElement.getElementsByTagName('rejected')[0].textContent;
}
alert("values:" + pending + "," + hires + "," + rejected);
}
I would replace your first if-else block with this:
// Mozilla/Safari/Non-IE
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
Your better off testing for support of a function versus testing for the browser.
I don't see anything wrong with your code. The issue might be that you are doing a cross-domain request that is trusted in Internet Explorer but fails in other browsers.
To confirm this, you can check if the returned request.status is equal to 0.
More info on the same origin policy on Wikipedia.
Related
I am using an AJAX call within a javascript function to populate a SELECT input. This script does not work the first time but works as I intend it to each subsequent time that it is called. The relevant code follows:
function getXMLHttp()
{
var xmlHttp;
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
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;
}
function populateEntries(menu, userName, entryRow)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200) && (xmlHttp.responseText == ""))
{
window.alert("There are no records to view!"); }
else if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
{
response = xmlHttp.responseText;
}
}
xmlHttp.open("GET", "getUsers.php", true)
xmlHttp.send(null);
ADDITIONAL UNRELATED CODE FOLLOWS ....
}
I've checked to see if the "response" is being passed from the AJAX call during the first function call and it is but it is not being passed out of the function for further use in the code that follows except on subsequent function calls. Can anyone tell me why this is happening? Your help will be very much appreciated. Before you tell me that this can be done with jquery, please understand that I need to do it with javascript.
Script:
function ajaxHandler() {
var xmlhttp;
try { // Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
} catch (e) { // Internet Explorer Browsers
try {
alert("paososdao");
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { // Something went wrong
alert("Your browser broke!");
return false;
}
}
}
xmlhttp.onreadystatechange = useHttpResponse();
xmlhttp.open("GET","prova.php",true);
xmlhttp.send(null);
function useHttpResponse(){
if (xmlhttp.readyState < 4) // while waiting response from server
document.getElementById('test').innerHTML = "Loading...";
else if (xmlhttp.readyState === 4) {
if (xmlhttp.status == 200 && xmlhttp.status < 300)
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
}
}
I'm testing it using xampp and I always get readyState = 0 and no response from prova.php, but if I open the developer console on Chrome I can see that the GET request status is 200. What's the problem.
Try that:
xmlhttp.onreadystatechange = useHttpResponse;
You're calling the useHttpResponse before you need it.
I have this code to form get XMLHttpRequest:
var makeRequest = function () {
var xmlhttp = getXmlHttp();
var params = 'name=' + encodeURIComponent('123') + '&surname=' + encodeURIComponent('surname')
xmlhttp.open("GET", 'site.html?' + params, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(null)
}
And I have this cross-browser function:
getXmlHttp = function () {
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') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
makeRequest()
All code is in the local file. No server side.
But Firefox says in console this:
'not well-formed'
So what's wrong?
UPD: I have added this xmlhttp.overrideMimeType("text/html");
It doesn'throw an error now but i still can't see it in a web inspector in a firefox
But i can see it in chrome.
It might help if you specified the MIME type.
xmlhttp.overrideMimeType("text/html");
or maybe site.html really is incorrectly formed - check opening tags, closing tags, etc...
I've looked at tons of demos and AJAX and JavaScript tutorials, but I can't seem to get this thing to work right. Here's what I've got...
function createRequestObject() {
var ro = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
ro = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
ro = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { }
}
}
return ro;
}
function ajaxrequest(){
var http = createRequestObject();
if(http) {
var name = "Strassburg";
var message = "Strike three you're out";
http.open('post', '/server/shout.php');
// needed in order for most servers to see POST data
http.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if(http.readyState == 4){
if(http.responseText.indexOf(':' != -1)) {
var data = http.responseText.split(':')
alert(data)
}
}
};
http.send('name=' + name + '&message=' + message);
}
}
Right now I'm doing it with static text (name and message instead of using the user entered fields), but I just get an empty alert. If the readyState is set to 4 this means that the ajax call was successful I believe? the server/shout.php was given to me, I dont understand php very well, but if a snippit of that is needed I can put it here as well.
its this line
http.responseText.indexOf(':' != -1)
( ":" != -1 ) = true, so indexOf is looking for true in the responseText
try this
http.responseText.indexOf(':') !== -1
readyState == 4 means that request was completed, to check if it was OK check http.status == 200
if (http.readyState == 4) {
if(http.status == 200) {
alert(http.responseText);
}
}
P.S. that should be a comment, but i don't have enough rating to comment your post
I try to make Cross Domain POST requests and get back JSON encoded responses,
everything works fine except in IE 7, 8, 9.
I have try those solutions but i get this error:
Object doesn't support property or method 'setRequestHeader'
Function createXMLHTTPObject() - attempt 1
function createXMLHTTPObject() {
var xmlhttp = false;
var is_IE = window.XDomainRequest ? true : false;
if (is_IE) {
xmlhttp = new window.XDomainRequest();
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlhttp;
}
Function createXMLHTTPObject() - attempt 2
var XMLHttpFactories = [
function() { return new XMLHttpRequest() },
function() { return new ActiveXObject("Msxml2.XMLHTTP") },
function() { return new ActiveXObject("Msxml3.XMLHTTP") },
function() { return new ActiveXObject("Microsoft.XMLHTTP") }
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0; i<XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch(e) {
continue;
}
break;
}
return xmlhttp;
}
Function send()
Here it returns the error, at: req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
function send(postData, callback) {
var url = 'http://domain.com/ajax-processing.php'; //url overlap
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method, url, true);
req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
if (postData) {
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
req.onreadystatechange = function() {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
console.log('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
Here i call the send function
var insert = 'id=1&type=insert';
CLib.send(insert, function(data) {
console.log(data);
});
Is it possible to make Cross Domain requests in IE?
How i can leave behind this part, without using any other library like jQuery?
Thanks a lot #Esailija who inform me that i can't make set request headers with the XDomainRequest.
So i tried other methods and solutions also and i finally came back with a simpler method:
changed the POST requests to GET and everything working fine after some small changes.