I am working with javascript cross domain ajax request. my code is working fine on chrome and other devices like android browser and android native app using phonegap.
But i was facing issue with Firefox..
Firefox does not support my PUT and DELETE requests.
Is there any solution for firefox to make put and delete request to my server.
firefox does support my post and get request. both request working fine.
here is my working code.
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;
}
For send Put request..
var xhr = createXMLHTTPObject();
xhr.open("PUT", url,true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4)
{
if(xhr.status==200){
request.success(xhr.responseText);
}else if(xhr.status!=200){
request.error(xhr.responseText)
}
}
}
xhr.send(body);
The following is working just fine on Firefox 22.0 (& 23.0 too):
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;
}
var xhr = createXMLHTTPObject();
xhr.open("PUT", "/echo/html/", true);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
alert("Request completed, with the following status code: " + xhr.status);
}
xhr.send("");
Here is a jsFiddle: http://jsfiddle.net/qXQtD/
To better understand your situation, please answer the following:
What is the data you are trying to send?
What are your complete response headers (especially the "Access-Control-Allow-Origin" header)?
Related
There is a way for combine these two technologies so that they work together when we are alredy in the div "result" ?
Let's see the problem.. We have the first code that do the ajax request
var http_request = false;
function makeRequest(url,getvar,funzione) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
//http_request.overrideMimeType('text/xml');
// See note below about this line
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Errore :( Non riesco a creare unna connessione XMLHTTP');
return false;
}
http_request.onreadystatechange = funzione;
http_request.open('POST', url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.send(getvar);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
document.getElementById("result").innerHTML = http_request.responseText;
} else {
alert('C\'è stato un problema alla connessione.');
}
}else{
document.getElementById("result").innerHTML ="loading";
}
}
And another function that edit the andress bar..
jQuery(document).ready(function() {
$('a.clickurl').click(function(event) {
var currentPage = document.location.pathname.substring(document.location.pathname.lastIndexOf('/') + 1);
if ($(this).attr('href') != currentPage){
if (history && history.pushState) {
history.pushState(null, document.title, $(this).attr('href'));
$.get($(this).attr('href'), {ajax:'1'}, function(data, text, xhr) {
pageSlider(data, text, xhr);
});
event.preventDefault();
}
}
});
after the first istance we got result on the div.. and up to here everything is working correctly, but how let the function work also in the links inside the "result" div?
setting a href="#" the ajaxrequest work correctly and just reflash the "result" div.. but if i set an different address loads the entire page..
ps. i already tried return false;
Problem is the fact that you are not binidng events to the dynamic content. You need to either rebind or use event delegation.
$(document).on("click", 'a.clickurl', function(event) {
or even better if all the links are only in the result div
$("#result").on("click", 'a.clickurl', function(event) {
I need to load and read an XML file using JavaScript.
The following code works fine in Firefox, IE and Opera:
function loadXMLDoc(dname) {
var xmlDoc
// Internet Explorer
try {
xmlDoc = new ActiveXObject('Microsoft.XMLDOM')
}
catch (e) {
// Firefox, Opera, etc.
try {
xmlDoc = document.implementation.createDocument('', '', null)
}
catch (e) {
alert(e.message)
}
}
try {
xmlDoc.async = false
xmlDoc.load(dname)
return xmlDoc
}
catch (e) {
alert(e.message)
}
return null
}
But executing this code in Chrome gives me this error:
Object# has no method "load"
Legacy Code
document.implementation.createDocument does not work on Chrome and Safari.
Use XMLHttpRequest instead when possible:
function loadXMLSync(url) {
try {
// Prefer XMLHttpRequest when available
var xhr = new XMLHttpRequest()
xhr.open('GET', url, false)
xhr.setRequestHeader('Content-Type', 'text/xml')
xhr.send()
return xhr.responseXML
}
catch (e) {
// XMLHttpRequest not available, fallback on ActiveXObject
try {
var activex = new ActiveXObject('Microsoft.XMLDOM')
activex.async = false
activex.load(url)
return activex
}
catch (e) {
// Neither XMLHttpRequest or ActiveXObject are available
return undefined
}
}
}
Modern Browsers
If you're targeting modern browsers (> IE6), just use XMLHttpRequest:
function loadXMLSync(url) {
var xhr = new XMLHttpRequest()
xhr.open('GET', url, false)
xhr.setRequestHeader('Content-Type', 'text/xml')
xhr.send()
return xhr.responseXML
}
On MDN, there is guidance to use XMLHttpRequest. But it isn't clear from DOMImplementation.createDocument until you drill into the return type and see that XMLDocument is not supported in Google Chrome. The example on W3Schools uses XMLHttpRequest.
follow this to print,load,append xml data.Here xml is stored as string inside javascript.This method works in chrome,firefox hopes it will work in others too
txt="<papers>"+"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<papers>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
x=xmlDoc.getElementsByTagName("paper");
for (var i = 0; i < x.length; i++) {
var athor =x[i].childNodes[0].firstChild.nodeValue;
var title = x[i].childNodes[1].firstChild.nodeValue;
var path = x[i].childNodes[2].firstChild.nodeValue;
var tack =x[i].childNodes[3].firstChild.nodeValue;
//do something with these values...
//each iteration gives one paper details
var xml=document.getElementById("element_id");//<div id="element_id"></div>
var li = document.createElement("br");// create a new <br>
newlink = document.createElement('A'); // creating an <a> element
newlink.innerHTML = athor;// adding <a>athor value here</a>
newlink.setAttribute('href', path);//
newlink.appendChild(li);// athor<br>
document.getElementById("element_id").appendChild(newlink);
//finaly it becomes <div id="element_id">athor<br></div>
}
i posted this answer here
Add
var xhr = new XMLHttpRequest();
xhr.open("GET", "/example/xdom/books.xml", false);
xhr.send(null);
xmlDoc = xhr.responseXML.documentElement;
return xmlDoc;
in catch statement. Like below:
function loadXMLDoc(dname) {
var xmlDoc
// Internet Explorer
try {
xmlDoc = new ActiveXObject('Microsoft.XMLDOM')
}
catch (e) {
// Firefox, Opera, etc.
try {
xmlDoc = document.implementation.createDocument('', '', null)
}
catch (e) {
alert(e.message)
}
}
try {
xmlDoc.async = false
xmlDoc.load(dname)
return xmlDoc
}
catch (e) {
//alert(e.message)
// For Chrome
var xhr = new XMLHttpRequest();
xhr.open("GET", "/example/xdom/books.xml", false);
xhr.send(null);
xmlDoc = xhr.responseXML.documentElement;
return xmlDoc;
}
return null
}
home.html
front page test
test.php
<SCRIPT language="JavaScript" SRC="ajax.js"></SCRIPT>
<button type="button" onclick="callAJAX('home.html','displaydiv')">Click Me!</button>
<div id="displaydiv"></div>
ajax.js
function callAJAX(url, pageElement, callMessage) {
document.getElementById(pageElement).innerHTML = callMessage;
try {
req = new XMLHttpRequest(); /* e.g. Firefox */
} catch(e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
/* some versions IE */
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
/* some versions IE */
} catch (E) {
req = false;
}
}
}
req.onreadystatechange = function() {responseAJAX(pageElement);};
req.open("GET",url,true);
req.send(null);
}
function responseAJAX(pageElement) {
console.log(req.readyState);
var output = '';
if (req.readyState == 4) {
if (req.status == 200) {
output = req.responseText;
document.getElementById(pageElement).innerHTML = output;
}
}
}
Above code is mainly from here:
Questions:
according to this site, onreadystatechange stores a function (or the name of a function) to be called automatically each time the readyState property changes so when will readyState property change? after req.send(null);?
for this line: console.log(req.readyState); in chrome console, it shows: 1 2 3 4, it does not output 0, is that because 0: request not initialized?
readyState changes in a few places, check out Mozilla's documentation for more information. req.readyState = 0 means that req.open() has not been called yet.
Also, depending on what browsers you are trying to support with this code, you can look into using some of the features from XHR2, including a req.onload() function that would change your code to:
function callAJAX(url, pageElement, callMessage) {
var elem = document.getElementById(pageElement);
elem.innerHTML = callMessage;
var req = new XMLHttpRequest();
req.onload = function() {
elem.innerHTML = req.responseText;
};
req.open("GET",url,true);
req.send(null);
}
I´ve implemented a dynatree on a web application, dynatree is generated from server with a JSON object.
Dynatree works perfectly on Firefox, Safari, Chrome and Opera (last versions), but when I open on IE9, I just capable of loading the tree after refresh the page, or start the debug mode. I can´t find any mistake on console, script....
Any suggestion? someone with the same problem?
Code:
function hacerPeticion(url, callback){
var request;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function(){
if (request.readyState == 4 && request.status == 200){
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
Using the function:
hacerPeticion('/ServiciosWeb/Zonas.jsp', function(data){
var data = JSON.parse(data.responseText);
var arbol = data;
eval('var obj='+arbol);
console.log(obj);
$(function(){
$("#tree3").dynatree({
checkbox: true,
selectMode: 3,
children: obj,
onSelect: function(select, node) {
if(!select){
if(node.data.key=="zonas"){
control=false;
cargaMapaCYL(map, control);
}
if(node.data.key=="ast"){
control=false;
cargaMapaAst(map, control);
}
/*Nodos seleccionados*/
if(select){
if(node.data.key=="zonas"){
control=true;
cargaMapaCYL(map, control);
}
if(node.data.key=="ast"){
control=true;
cargaMapaAst(map, control);
}
}
onDblClick: function(node, event){
node.toggleSelect();
},
onKeydown: function(node, event) {
if( event.which == 32 ) {
node.toggleSelect();
return false;
}
}
});
Thanks in advance.
So....., the problem is in this line:
console.log(obj);
When I have retired this line everything works fine.
function processAjaxStateChangeForRowAdd() {
alert(0);
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
processForRowAdd(req.responseText);
} else {
alert("Problem: " + req.statusText);
}
}
}
This code is working fine for IE, Safari and Firefox, but if I remove the alert, then the code will not work in Firefox, though it still works in IE and Safari.
Can anybody give me suggestion why it not working in Firefox without alert?
EDIT: Code that adds a row:
if (window.XMLHttpRequest && browserVersion.indexOf("Microsoft") == -1 ) {
// code for Firefox, Chrome, Opera, Safari
req = new XMLHttpRequest("");
if (req) {
ajaxProcessed = false;
req.onreadystatechange = processAjaxStateChangeForRowAdd;
req.open("POST", url, true);
req.send();
// alert("1");
}
}
The alert is blocking. What this means is that your script is temporarily suspended (even if it's for a few milliseconds). During this time, your AJAX request completes and your req object is being set. You can add a delay (using setTimeout) to your callback to verify this.
I would suggest you post more of your script so that we can help you set up your callback properly. Alternatively, use a library such as jQuery to set up AJAX calls in a cross-browser manner easily.
EDIT: You need to either declare req as a global variable, or use an anonymous function. The following code demonstrates the first method (using a global variable):
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
if (req) {
req.onreadystatechange = processAjaxStateChangeForRowAdd;
req.open("POST", url, true);
req.send();
}
}
function processAjaxStateChangeForRowAdd() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
processForRowAdd(req.responseText);
} else {
alert("Problem: " + req.statusText);
}
}
}
function getHttp()
{
var xmlhttp;
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
if(typeof XMLHttpRequest != 'undefiend')
{
xmlhttp = new XMLHttpRequest();
}
}
}
return xmlhttp;
}
can you try this:
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText;
} else
alert("status: " + request.status);
}
You should also check for the readyState , the following code might help
req.onreadystatechange=function()
{
if (req.readyState==4 && req.status==200)
{
processForRowAdd(req.responseText)
}
}
Read this for the different values of readyState