Parse XML data on page load & insert into div using AJAX / Javascript - 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;
}​

Related

how to change ckeditor value by javascript

my textarea is:
<textarea class="content" name="content" id="content" rows="10" cols="80"></textarea>
and initializing it as:
<script>
$(document).ready(function(){
///CKeditor
CKEDITOR.replace( 'content', {
height: 320,
} );
});
</script>
now i am getting data in an array and then changing the values of different elements according to it. the array that i am getting is:
[{"id":"5","subject_Id":"1","topic_id":"1","question_type_id":"4","exam_id":"1","difficulty_id":"1","year_id":"1","essay":"","right_marks":"2","negative_marks":"3","question":"question 2","options":"Ans CC~Ans BB~Ans AA~","correct_answer":"Ans BB~"}]
[{"id":"6","subject_Id":"1","topic_id":"1","question_type_id":"4","exam_id":"1","difficulty_id":"1","year_id":"1","essay":"","right_marks":"2","negative_marks":"3","question":"question 1","options":"<img alt=\"\" src=\"\/corePhp\/examinationsystem\/assets\/ckeditor\/kcfinder\/upload\/images\/profile-icon-9(1).png\" style=\"height:512px; width:512px\" \/>~Ans BB~Ans AA~","correct_answer":"Ans BB~"}]
[{"id":"18","subject_Id":"1","topic_id":"1","question_type_id":"1","exam_id":"1","difficulty_id":"1","year_id":"2","essay":"Essay 5","right_marks":"2","negative_marks":"3","question":"Brass gets discoloured in air because of the presence of which of the following gases in air?","options":"Oxygen~Hydrogen sulphide~Carbon dioxide~Nitrogen","correct_answer":"\"Hydrogen sulphide\""}]
then in my javascript
<script type="text/javascript">
function dbDataQuestion(quesId) {
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");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
var convert=JSON.parse(xmlhttp.responseText);
//console.log(convert[0].subject_Id);
document.getElementById("selectSubject").value=convert[0].subject_Id;
document.getElementById("selectTopic").value=convert[0].topic_id;
document.getElementById("selectQuestionType").value=convert[0].question_type_id;
document.getElementById("selectExam").value=convert[0].exam_id;
document.getElementById("selectYear").value=convert[0].year_id;
document.getElementById("selectDiffLvl").value=convert[0].difficulty_id;
document.getElementById("txtRightMarks").value=convert[0].right_marks;
document.getElementById("txtNegMarks").value=convert[0].negative_marks;
console.log(convert[0].question_type_id);
console.log(convert[0].question);
CKEDITOR.on("instanceReady", function(event)
{
//CKEDITOR.instances.content.insertHtml(convert[0].question);
CKEDITOR.instances.content.focus();
CKEDITOR.instances.content.setData(convert[0].question);
});
if(convert[0].essay){
document.getElementById("txtEssayName").value=convert[0].essay;
document.getElementById("radioEssayYes").checked = true;
}
else{
document.getElementById("txtEssayName").value=convert[0].essay;
document.getElementById("radioEssayNo").checked = true;
}
}
}
xmlhttp.open("POST","process/questions/quesDetails.php?quesId="+quesId, false);
xmlhttp.send();
}
</script>
as you can see i am consoling console.log(convert[0].question); in which i am getting correct data, but when i am writing CKEDITOR.instances.content.setData(convert[0].question); its not updating ck editor's value.
actually the function "dbDataQuestion(quesId)" is being called once at the time of page load at that time its working fine the CKEditor is showing question 2 which you can see is in the first array, after that I have a button on which I am getting the next array and so on. on clicking this button array is getting displayed in the console as well as other element are changing its values but CKEditor is showing the same old value that is question 1 and not question 2 on consoling console.log(convert[0].question); I am getting "question 2" which is correct.
Note: function dbDataQuestion(quesId) is where from where i am getting above mentioned array and on xmlhttp.readyState === 4 && xmlhttp.status === 200 of the function i am changing the values of the elements which includes ck editor. its once called at the time of page load and then its being called on a button click:
<button type="button" class="btn btn-xs btn-success" onclick="fetchQuestionDetails('next')">Next</button>
I am calling all my scripts at the bottom of the page.
thanks in advance.
Update:
I noticed that instanceReady event is not getting triggered by calling the function when the button is pressed. I altered my code to check
console.log(convert[0].question);
CKEDITOR.on("instanceReady", function(event)
{
console.log(convert[0].question);
console.log("sss");
CKEDITOR.instances.content.focus();
CKEDITOR.instances.content.setData(convert[0].question);
});
only console.log(convert[0].question); is getting triggered and none of the other console statements. What am I doing wrong?
first thanks a lot #Muhammad Omer Aslam for responding, so quickly. i have not tried your answer but i ll try it and comment if it solved the problem or not but i found a way to make it work i removed instanceReady event and wrote
setTimeout(function(){
CKEDITOR.instances.content.setData(convert[0].question);
}, 1000);
and its working fine. but again thanks #Muhammad Omer Aslam
try it the following way by moving the initialization inside the ajax response section.
$(document).ready(function () {
dbDataQuestion(quesId);
});
Your function will look like this.
function dbDataQuestion(quesId) {
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");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var convert = JSON.parse(xmlhttp.responseText);
//console.log(convert[0].subject_Id);
document.getElementById("selectSubject").value = convert[0].subject_Id;
document.getElementById("selectTopic").value = convert[0].topic_id;
document.getElementById("selectQuestionType").value = convert[0].question_type_id;
document.getElementById("selectExam").value = convert[0].exam_id;
document.getElementById("selectYear").value = convert[0].year_id;
document.getElementById("selectDiffLvl").value = convert[0].difficulty_id;
document.getElementById("txtRightMarks").value = convert[0].right_marks;
document.getElementById("txtNegMarks").value = convert[0].negative_marks;
console.log(convert[0].question_type_id);
console.log(convert[0].question);
///CKeditor
CKEDITOR.replace('content', {
height: 320,
});
CKEDITOR.on("instanceReady", function (event) {
//CKEDITOR.instances.content.insertHtml(convert[0].question);
CKEDITOR.instances.content.focus();
CKEDITOR.instances.content.setData(convert[0].question);
});
if (convert[0].essay) {
document.getElementById("txtEssayName").value = convert[0].essay;
document.getElementById("radioEssayYes").checked = true;
} else {
document.getElementById("txtEssayName").value = convert[0].essay;
document.getElementById("radioEssayNo").checked = true;
}
}
}
xmlhttp.open("POST", "process/questions/quesDetails.php?quesId=" + quesId, false);
xmlhttp.send();
}

Javascript div refresh

I am trying to refresh a php script to show updated content as a database updates. I first built my php, then the code to refresh and then merge them. However, the script doesn't update. Anyone know why?
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(
function() {
setInterval(function() {
if(document.getElementById('gallery') != null){
function showLots() {
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) {
document.getElementById("gallery").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php",true);
xmlhttp.send();
}
}
}, 3000);
});
</script>
Thanks.
You did not called method showLots, First define it outside the function and than call it in setInterval
The issue with your code is that function showLots() is inside your if (document.getElementById('gallery') != null) conditional without the function actually executing.
Below is what your corrected code could could look like by moving the function showLots() definition up. showLots() is then called inside where you originally had the definition.
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function showLots() {
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) {
document.getElementById("gallery").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php",true);
xmlhttp.send();
}
$(document).ready(function () {
setInterval(function () {
if (document.getElementById('gallery') !== null) {
showLots();
}
}, 3000);
});
</script>

ajax internet explorer onchange

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

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;
}

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);
}

Categories