ajax internet explorer onchange - javascript

My ajax script for loading the second select box, works in firefox and chrome, but internt explorers cant handle it. I call the onChange function from my select box and give the value from the select box to the function.
Code:
function getXMLHTTP()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function getType(categoryName)
{
var strURL="includes/get.php?c="+categoryName+"&sid="+Math.random();
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200)
{document.getElementById('type').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
My second question is, is it possible to send the text between the options tag instead of the value in the options tag?

For your 1st question, I assume your if (req) returns false. Which IE version are you using? Try to add debug codes in getXMLHTTP() function to start diagnosing the codes. Try this solution provided by Microsoft: http://msdn.microsoft.com/en-us/library/ms537505(v=vs.85).aspx
I try not to repeat other's answer. Here is the answer for obtaining text in selected option tag : Getting the text from a drop-down box

Related

What causes error in IE7?

I am using this JS code to reach a list of cities. It works in fireworks, chrome .e.t.c. But in ie7 it does not. the line document.getElementById(oDiv).innerHTML=xmlhttp.responseText; causes the error.
When I change "responseText" to "readyState", "statusText", "readyState" the scripts works. Only "responseText" causes problem.
What is the problem here?
function showAjax(oDiv, countrycode, dowhat) {
if (oDiv == "") {
document.getElementById(oDiv).innerHTML = "";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open('POST', 'ajax.php?dowhat=' + dowhat + '&countrycode=' + countrycode, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(oDiv).innerHTML = xmlhttp.responseText;
//document.getElementById(oDiv).innerHTML=xmlhttp.readyState;
}
}
xmlhttp.send();
}
Click
<div id=citytd></div>
IE7 (and before, and IE8 in "compatibility" mode) has issues with getElementById, where it considers some things IDs that it shouldn't. I suspect you have a global variable, or another element with name="citytd", and IE is pick that up instead (even though, again, it shouldn't). More: ...by any other name, would smell as sweet

XML Parsing not working in IE

I am trying to parse a XML file, it works perfectly in FF but dont in IE. Pls help debug this. The code is as follows.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("StepName");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getAttribute("name"));
document.write("</td><td>");
document.write(x[i].getElementsByTagName("StepStatus")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("StepDescription")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
Your code, improved and annotated:
abstract things like XmlHttp requests into dedicated functions for reusability
always use the var keyword for declaring variables; forgetting this is a source of nasty bugs
use meaningful variable names wherever possible; single-letter names are suitable for loop counters but not for a lot else
never do synchronous HTTP requests, use callbacks instead
functions that do sanity checks first and return early tend to be less deeply nested
do not build HTML with document.write(), use the DOM instead
function getXml(url, onsuccess) {
var xmlhttp;
if (window.XMLHttpRequest) { // IE10+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // IE5 - IE9
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState != 4) return;
if (xmlhttp.statusCode !== 200 || !xmlhttp.responseXML) return;
if (typeof onsuccess !== "function") return;
onsuccess.call(xmlhttp, xmlhttp.responseXML);
};
xmlhttp.send();
}
Now we can use it as follows:
getXml("books.xml", function (xmlDoc) {
var table = e("table", document.body), // see helper function e below
steps = xmlDoc.getElementsByTagName("StepName"),
i, step, tr;
for (i = 0; i < steps.length; i++) {
step = steps[i];
tr = e("tr", table);
e("td", tr, step.getAttribute("name"));
e("td", tr, step.getElementsByTagName("StepStatus")[0].childNodes[0].nodeValue);
e("td", tr, step.getElementsByTagName("StepDescription")[0].childNodes[0].nodeValue);
}
});
// helper function to build HTML elements with the DOM
function e(name, parentNode, text) {
var elem = document.createElement(name),
textProp = elem.hasOwnProperty("textContent") ? "textContent" : "innerText";
if (text) elem[textProp] = text;
if (parentNode && parentNode.appendChild) parentNode.appendChild(e);
return elem;
}
I suspect that your problem lies here:
step.getElementsByTagName("StepStatus")[0].childNodes[0].nodeValue
Maybe you are making assumptions about the document structure that are incorrect. But unless you post your XML, this is hard to say.
i had similar problem and following code works for all browser ...the trick is use separate code XML for IE browsers or that are version of less than 10 .
so every time Ajax is call a method parseXml is called with input parameter XML Dom or text, depending on browser .... and if current browser is IE, it upload XML doc, process it according to Microsoft standards and return XML and rest of processes in Ajax carries on as expected!!
note : browser.msie is not supported in jQuery 1.9 but you can add jquery-migrate-1.2.1.min.js in order to make it compatible or use userAgent and find which is current browser
$.ajax({
type: 'GET',
url: 'XML_file.xml',
dataType: ($.browser.msie) ? "text" : "xml",
success: function (xml) {
var processedXML = parseXml(xml);
$(processedXML).find('my record').each(function () { //code }
});
function parseXml(xml) {
if ($.browser.msie) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "XML_file.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
xml = xmlDoc;
}
return xml;
}

Parse XML data on page load & insert into div using AJAX / Javascript

I am working on a page that uses javascript / AJAX to parse xml from a file. I need to be able to parse a url on the loading of a page and insert it into a div. I have the script written but I need help getting 2 things:
1) having it parse an XML file and load that data into a div on page load
2) the option to click a link and load that data into the same div instead of what was there when the page loaded.
I am using an external script to do this & embeded a link to it in my page
HTML example to request data:
<div id="rightcolumn">
<button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button>
</div>
How do I change that to load #1 when the page loads & #2 when a link is clicked?
For the script, do I need anything special at the top to make sure it loads properly? jQuery has $(document).ready(function() {//GUTS}, do I need something similar with AJAX?
My Script
function loadXMLDoc(url){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var anno= xmlhttp.responseXML.documentElement.getElementsByTagName("anno");
// Parser Guts
}
document.getElementById('rightcolumn').innerHTML=txt;
}
}
xmlhttp.open("GET","url",true);
xmlhttp.send();
Usage
<!-- when the user clicks -->
<button onclick="ajax('#ELEMENT','cd_catalog.xml')">Get CD info</button>
// when the page loads
window.onload = function () {
ajax('#ELEMENT', 'cd_catalog.xml');
};
or you can place a script tag at the bottom of the page, or use the dom ready event
Code
function getXmlHttpObject() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (!xmlHttp) {
alert("Your browser does not support AJAX!");
}
return xmlHttp;
}
function ajax(el, url, onSuccess, onError) {
if (typeof el == "string")
el = document.getElementById(el);
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function() {
if (this.readyState === 4) {
// onSuccess
if (this.status === 200 ) {
if (el)
el.innerHTML = this.responseText;
if (typeof onSuccess == 'function')
onSuccess(this.responseText);
}
// onError
else if(typeof onError == 'function') {
onError();
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}​

AJAX: How to use TWO xmlHttpRequest in parallel in ONE function?

How should I do this?
function(id,id2){
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
First Request:
xmlhttp.open("GET", "http://example.com/ajax.php?id="+id, true);
xmlhttp.send();
Second Request:
xmlhttp.open("GET", "http://example.com/ajax2.php?id2="+id2, true);
xmlhttp.send();
}
Because in this way doesn't works.
I want to make it in plain javascript, so please do not post answers with jQuery or any library etc.
Thanks
It should work if you create a new xmlhttp object. Currently you are attempting to reuse the same object, which is already performing a query so it will not work.
if you are looking for classic javascript style you can use as the following. But use jQuery as it's simple and comprehensive. The one thing to be noted is that the "xmlhr" should be in method (callAjax) scope.
function callAjax(url) {
var xmlhr;
if (window.XMLHttpRequest) {
xmlhr = new XMLHttpRequest();
} else {
xmlhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhr.onreadystatechange = function () {
if (xmlhr.readyState == 4 && xmlhr.status == 200) {
alert(xmlhr.responseText);
}
}
xmlhr.open("GET", url, true);
xmlhr.send();
}
function myFunction(id1, id2) {
callAjax("http://example.com/ajax2.php?id2=" + id1);
callAjax("http://example.com/ajax2.php?id2=" + id2);
}

How to create a xmlhttp request?

var url="display.php?vote="+grade;
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}
This piece of code fails to send out the request. How to create a xmlHttp correctly?
<script type="text/javascript">
function ajaxFunction()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
}
</script>
this piece of code is available in link text you can learn basics here like i did. hope this helps.
Here is a "80%" solution.
function GetXHR()
{
try
{
if (window.XmlHTTPRequest)
xmlHttp = new XmlHTTPRequest()
else
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP.3.0")
}
catch(e) { }
}
var xmlHttp = GetXHR()
if (xmlHttp)
{
// Proceed with xmlHttp usage.
}
Edit
Note I tend to avoid the old ProgID "Microsoft.XMLHTTP" in favour of the one I have used because this later ProgID has a more predictable behaviour and is ever so slightly more secure. However if you want wider compatiblity with really old Windows machines (I'm talking out-of-support stuff) then you could use the older one in your specific case.
var xmlHttp=new(window.ActiveXObject?ActiveXObject:XMLHttpRequest)('Microsoft.XMLHTTP');

Categories