How do I process an XML string with Jquery? - javascript

I am really struggling with a Jquery script I can't get to work.
I have an XML string and I want to return the name 'Miki' from it, however its just not working and i can't figure it out. Can someone help me?
function LoadParseXML() {
var xml
xml = '<?xml version="1.0" encoding="utf-8"?><CATALOG><VAR><PREVIOUSPAT>Miki</PREVIOUSPAT></VAR></CATALOG>';
loadXMLDoc(xml, 'PREVIOUSPAT');
}
function loadXMLDoc(url, Node) {
var xmlhttp;
var txt, x, xx, i;
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) {
x = xmlhttp.responseXML.documentElement.getElementsByTagName("VAR");
for (i = 0; i < x.length; i++) {
xx = x[i].getElementsByTagName(Node);
txt = xx[0].firstChild.nodeValue;
alert(txt);
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}

try this jQuery code to loop PREVIOUSPAT occurrences
var xml = '<?xml version="1.0" encoding="utf-8"?><CATALOG><VAR><PREVIOUSPAT>Miki</PREVIOUSPAT></VAR></CATALOG>';
xmlDoc = $.parseXML( xml );
$xml = $( xmlDoc );
$xml.find('CATALOG > VAR > PREVIOUSPAT').each(function(){
alert( $(this).text() );
})

Related

XMLHttpRequest readyState stuck at 1 and never reach 4

This is my code. i don't know what's wrong with my code but the readyState always return 1 and the status always return 0. can anyone please help me?
function Registered() {
console.log("masuk function");
var xmlhttp;
var randomNum = Math.floor((Math.random() * 100) + 1);
const proxyurl = "https://cors-anywhere.herokuapp.com/";
var url = "http://127.0.0.1:8080/webchatBack/webchat/getQueueCount?t="+randomNum;
var xmlDoc;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
console.log("masuk xml");
xmlhttp = new XMLHttpRequest();
} else if(window.ActiveXObject){// code for IE6, IE5
console.log("masuk active");
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
console.log("masuk function lagi");
console.log(xmlhttp.readyState);
console.log(xmlhttp.status);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log("masuk if");
xmlDoc = xmlhttp.responseXML;
var result = xmlDoc.getElementsByTagName("Result");
result = result[0].childNodes[0].nodeValue;
console.log(result);
document.getElementById("agentLoginData").innerHTML = result;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=\"utf-8\"");
xmlhttp.send('');
}

Dynamic Object Access from form to Ajax

Here is my JavaScript with Ajax code:
Actually i am using this for dynamically adding option in any number of select in which this function is called.
function loadabc(vm) {
var xmlhttp;
//alert(vm);
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//alert("called");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var jsonObj = JSON.parse(xmlhttp.responseText);
for(i = 0; i < jsonObj.length; i++) {
var createOption = document.createElement("option");
//alert("Jeason has Passed Data");
createOption.value = jsonObj[i].aId;
createOption.text = jsonObj[i].aName;
//alert("id" + createOption.value);
//alert("Name" + createOption.text);
document.impForm.vm.options.add(createOption);
//alert("Added");
}
}
}
xmlhttp.open("get", "${pageContext.request.contextPath}/Admin_Search_con?flag=loaddetail", true);
xmlhttp.send();
}
I am using ondblclick="loadabc(this)" for calling it. I want to access this vm object for creating options in select. How can I do so?
The solution is to use the param vm instead of referencing it as document.impForm.vm:
function loadabc(vm) {
var xmlhttp;
//alert(vm);
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//alert("called");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var jsonObj = JSON.parse(xmlhttp.responseText);
for(i = 0; i < jsonObj.length; i++) {
var createOption = document.createElement("option");
//alert("Jeason has Passed Data");
createOption.value = jsonObj[i].aId;
createOption.text = jsonObj[i].aName;
//alert("id" + createOption.value);
//alert("Name" + createOption.text);
vm.options.add(createOption); // <-- Here!
//alert("Added");
}
}
}
xmlhttp.open("get", "${pageContext.request.contextPath}/Admin_Search_con?flag=loaddetail", true);
xmlhttp.send();
}

HTML code works on Chrome but not IE

Anyone know why this works on Chrome but not IE? I am using IE 10/11
I am trying to incorporate this code into a Windows Widget, so I need it to work on IE.
I heard win 7 gadgets will render using the latest version of IE installed but this code doesn't seem to run on IE at all. Please help.
var xmlhttp;
function init() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function SendRequest() {
var data = "<some data>";
var url = "some url";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/xml");
xmlhttp.setRequestHeader("Accept", "application/xml");
xmlhttp.send(data);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
xmlDoc = xmlhttp.responseXML;
txt = "";
x = xmlDoc.querySelectorAll('id,owner,status');
for (i = 0; i < x.length; i++) {
txt = txt + x[i].childNodes[0].nodeValue + "&nbsp";
}
document.write(txt);
}
}
}

Sending an array using javascript ajax

In jquery I can do this
myAray=['abc', '123', 'more'];
$.post('myscript.php', {data:myAray}, function(data){
alert(data);
});
How can I do the same thing using plain javascript ? I want to send an array to my php script using POST method. I have found so many examples but all of them are jquery related.
Thanks in advance.
You will have to use XMLHttpRequest and serialize the array yourself:
function ajax(myArray) {
var xmlHTTP;
if (window.XMLHttpRequest) {
xmlHTTP = new XMLHttpRequest();
} else {
xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHTTP.onreadystatechange = function () {
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
// do whatever it is you want to do
}
}
//Serialize the data
var queryString = "";
for(var i = 0; i < myArray.length; i++) {
queryString += "myArray=" + myArray[i];
//Append an & except after the last element
if(i < myArray.length - 1) {
queryString += "&";
}
}
xmlHTTP.open("POST", "www.myurl.com", true);
xmlHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlHTTP.send(queryString);
}
Mess around with this.
JS
var myarray = Array("test","boom","monkey");
send("test.php", myarray);
function send(url, data)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
console.log(xhr.responseText);
}
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("data= " +data);
}
PHP
<?php
$array = explode(',', $_POST["data"]);
for($i=0,$l=count($array); $i<$l; $i++)
{
echo $array[$i].'<br>';
}
?>
Something like this:
post is either POST or GET.
params are only used in POST otherwise include what you need in the url for GET.
success and error are both string names of the functions, not the functions themselves, which is why you need executeFunctionByName, thanks to Jason Bunting:
How to execute a JavaScript function when I have its name as a string
getRemoteData = function (url, post,params, success, error){
var http = false;
if (navigator.appName === "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
http.open(post, url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {var resp; if (http.readyState === 4 && http.status == 200) { resp=http.responseText; executeFunctionByName(success, window, resp); }else if(http.status == 400){resp=http.responseText; executeFunctionByName(error, window, resp);}};
http.send(params);
return false;
};
function executeFunctionByName(functionName, context, args) {
args = Array.prototype.slice.call(arguments).splice(2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(this, args);
}
function loadXMLDoc()
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","jsArrayPhp.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("test[]=Henry&test[]=Ford");
}
Take attention here:
test[]=Henry&test[]=Ford"
Where test is the name of array you'll use in php.
In php
<?php
print_r($_POST['test']);
?>
It'd produce: Array ( [0] => Henry [1] => Ford )

Parsing or using variables from a called script?

I have an AJAX function which loads content from a file and displays in the file that called it.
But the script that was called I want to loop an array which is actually set in the script that called it... this is main script that calls the file:
function call_file(file, div_id) {
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) {
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send();
}
var global = new Array();
global[0] = 1;
global[1] = 2;
call_script('html.html', 'main');
html.html is the file that is called which has this:
<script>
i = 0;
for(var id in global) {
alert(i + ' = ' + id);
i++;
}
</script>
Is this at all possible?
One way is to extract the script and eval it yourself. For example:
//....
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
var str = xmlhttp.responseText;
var reg = /<script>([^>]*)<\/script>/img;
while(reg.test(str))eval(RegExp.$1);
//...

Categories