Ajax response xml is null Java script - javascript

Servlet response:
for (int i = 0; i < projNames.size(); i++) {
sb.append("<project>");
sb.append("<projectName>" + projNames.get(i) + "</projectName>");
sb.append("</project>");
res.setContentType("text/xml");
res.setHeader("Cache-Control", "no-cache");
System.out.println(" test="+test);
res.getWriter().write(sb.toString());
}
System.out.println shows "sb" value as
<project><projectName>sample</projectName></project><project><projectName>sample 2</projectName></project>
I'm trying to retrieve the response XML and but when I checked the length "object value is null" ( debugged in IE 8 )
function displayValues()
{
var response;
if (req.responseXML != null)
alert("res xml is ther=="+ response); //displays UNDEFINED
else
alert("no res xml");
response = req.responseXML.getElementsByTagName("project")[0];
alert("child node"+response.childNodes.length); // alert is not displayed
}
Please enlighten. Thanks
AJAX code:
<SCRIPT type="text/javascript">
var response;
var firstName;
var icdatevalue;
function getProject()
{
var url ="DBActionServlet?action=getProject";
initRequest(url);
req.onreadystatechange = processRequest;
req.open("POST", url, true);
req.send(null);
}
function initRequest(url)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
alert("status="+req.status);//status is shown as 200
displayValues(); //this function code mentioned above
}
}
}
</SCRIPT>

Related

Ajax function in javascript is not working in mozilla firefox browser, why?

Follownig is my javascript code, ajax function is used to read response from
server. but xmlhttp.status is always 0 in firefox browser, why? please help me.
function ajaxAsyncRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveObject("Microsoft.XMLHTTP");
}
//creating asynchrounous GET request
var tempValUrl = $(".urlVal").val();
var urls = tempValUrl + '/Department/departmentAdminTokenReceive';
xmlhttp.open("GET", urls, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert("readyState"+xmlhttp.readyState);
alert("status"+xmlhttp.status);
if (xmlhttp.status == 200) {
var data = xmlhttp.responseText;
//for signing
var signarr = data.split("$$");
//for signing
document.getElementById('signName').value = signarr[1];
document.getElementById('signCertName').value = signarr[2];
document.getElementById('signCa').value = signarr[3];
document.getElementById('signExpiryDate').value = signarr[4];
document.getElementById('signPublicKey').value = signarr[5];
}
}
}
}

AJAX does not return object

I am using AJAX GET to get a local JSON file and it does that, but once i try to return it says undefined.
ScoreHandler = function () {
this.getScores = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
//This logs object
console.log(data);
return data;
}
};
xmlhttp.open("GET", "JSON/Scores.json", true);
xmlhttp.send();
};
};
HighScores = function (scoreHandler) {
var scoreHandler = scoreHandler;
var scores = this.scoreHandler.getScores();
//This logs undefined
console.log(scores);
}
Just implement a callback for response, something like this
ScoreHandler = function () {
this.getScores = function(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
//This logs object
console.log(data);
if(typeof callback === 'function')
callback(data);
//return data;
}
};
xmlhttp.open("GET", "JSON/Scores.json", true);
xmlhttp.send();
};
};
HighScores = function (scoreHandler) {
var scoreHandler = scoreHandler; //why this line use it directly
var scores = this.scoreHandler.getScores(function(data){
console.log("response", data); //you can see the data here
});
//This logs undefined
console.log(scores);
}

Returning the XML received on readystatechange - JavaScript

This is my first post here on Stack. I am trying to make a Get request which is succeeding but I am having trouble getting the responseXML into a variable for processing. I think I am supposed to be using a callback function, but I still can't get it quite right. I am hopeful that somebody can point me in the correct direction. Code below.
<script type="text/javascript">
function buildOptions() {
var data = null;
/*xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
callback.call(xhr.responseXML);
}
});*/ //This code block worked, but I couldn't figure out how to get the result back
getXML = function(callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
}
}
function XMLCallBack(data) {
alert(data); // These two functions were the most recent attempt but I'm still missing something
}
xmlDoc = getXML(XMLCallBack); // this is supposed to start the processing of the returned XML
console.log(xmlDoc);
var campaignName = xmlDoc.getElementsByTagName('self')[0]; //XMLDoc contains a null variable when I get to this line
console.log(campaignName);
var campaigns = ["","Freshman Campaign","Sophomore Campaign","Junior Campaign","Senior Campaign"]; //Code from here and below will be changing slightly once I can get XMLDoc to be correct
var sel = document.getElementById('campaignList');
for(var i = 0; i < campaigns.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = campaigns[i];
opt.value = campaigns[i];
sel.appendChild(opt);
}
}
</script>
I believe you should move open ---> send outside the onreadystatechange, like this:
getXML = function(callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
}
EDIT: This code should work:
<script type="text/javascript">
function buildOptions() {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = XMLCallBack;
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
function XMLCallBack() {
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc = xhr.responseText;
var campaignName = xmlDoc.getElementsByTagName('self')[0];
var campaigns = ["","Freshman Campaign","Sophomore Campaign","Junior Campaign","Senior Campaign"];
var sel = document.getElementById('campaignList');
for(var i = 0; i < campaigns.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = campaigns[i];
opt.value = campaigns[i];
sel.appendChild(opt);
}
}
}
}
</script>
I haven't tried it so I might have made some mistakes. If you want to, you can move XMLCallBack() outside of buildOptions() and use this.readyState, this.status and this.responseText instead of xhr.readyState etc..

Loop Calling Function in Native Ajax

Here's my native ajax code:
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined'){
alert('Data Found:' + result);
//start: new request data for #valdata
xmlhttp.open("POST", "inc.php?q="+str, true);
document.getElementById("valdata").value = xmlhttp.responseText;
xmlhttp.send(null);
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined'){
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q="+str, true);
xmlhttp.send(null);
}
From the code, let me explain that:
I want to get data/value from result and dataval. After I get the data, I execute script_dkill() function.
However, It creates loop and never get to script_dkill.
So, the question is: How to get to script_dkill and execute it?
For example:
The script_dkill() has content as follow:
function script_dkill(){
alert('Hallo, you call me!');
}
Any help, please...
You need to use a different XMLHttpRequest object for the second request, since you are using the same object it will call the same onreadystatechange event again and again
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined') {
alert('Data Found:' + result);
//start: new request data for #valdata
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
document.getElementById("valdata").value = xmlhttp2.responseText;
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined') {
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
}
}
xmlhttp2.open("POST", "inc.php?q=" + str, true);
xmlhttp2.send(null);
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q=" + str, true);
xmlhttp.send(null);
}

call generic handler in aspx without jquery

Can i call Generic handler in aspx without using jQuery?
yes, jQuery itself is a javascript, so you can call by writing your own script. The benefit of using jQuery is you don't need to worry about browser compatability, have to write less code, can get advantage of using jquery plugins etc, only the cost of adding jQuery.js.
Example:
<script type="text/javascript">
// Intialize XMLHTTP object
function GetXmlHttpObject() {
var A;
if (window.XMLHttpRequest) {
A = new XMLHttpRequest();
} else {
var msxmlhttp = new Array(
'Msxml2.XMLHTTP.6.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP');
for (var i = 0; i < msxmlhttp.length; i++) {
try {
A = new ActiveXObject(msxmlhttp[i]);
break;
} catch (e) {
A = null;
}
}
}
return A;
}
function sendAjaxRequest(url, postVars, callbackFunc) {
var isPost = (postVars && postVars.length > 0);
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
if (!isPost) {
if (url.indexOf('?') == -1) {
url += '?' + uncache();
} else {
url += '&' + uncache();
}
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) { //This function will execute on receive
var callback;
var extra_data = false;
var data = xmlHttp.responseText;
callback = callbackFunc;
callbackFunc(data, extra_data);
}
};
//Send data to the url through ajax
if (isPost) {
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-Length", postVars.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(postVars);
} else {
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
}
function uncache() {
var d = new Date();
var time = d.getTime();
return 'time=' + time;
}
function comp(result) {
alert(result);
}
sendAjaxRequest('test.html', '', comp);
</script>

Categories

Resources