Ajax code control - javascript

Sorry for that stupid question but, is this code right because it seems to be broken.
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var nocache = 0;
function vloz() {
var kom= encodeURI(document.getElementById('komen').value);
var site_name = encodeURI(document.getElementById('user_id').value);
var p_id = encodeURI(document.getElementById('p_id').value);
var zed = encodeURI(document.getElementById('zed').value);
nocache = Math.random();
http.open('get', 'kmnt.php?site_url='+kom+'&site_name=' +site_name+'&site='+p_id+'& zed='+zed+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){
}
}
I have a form when i am sending komen, user_id, p_id and zed

Not sure if this is it but it appears that you have one too many curly braces in the beginning of your code:
if(browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
// } <- extra one here

Related

Get JSON from Web Service Using JavaScript

I get this error when I click the button in HTML to use my JavaScript.
myapp.azurewebsites.net/:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
JS:
function ajaxFunction() {
console.log("ajaxFunction()");
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Broken");
return false;
}
}
}
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var form = document.getElementById("myform");
var titleParagraph = document.getElementById("home_title");
titleParagraph.innerHTML = ajaxRequest.responseText;
form.style.display = "none";
}
}
var value1 = document.getElementById("field1").value;
var value2 = document.getElementById("field2").value;
var url = "https://webapp.azurewebsites.net/users/" + value1 + "/" + value2;
console.log(url);
// Call sign in web service
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
var jsonResponse = JSON.parse(ajaxRequest.responseText);
console.log("RESPONSE:");
console.log(jsonResponse);
}
This JSON is what I get when I go to https://webapp.azurewebsites.net/users/value1/value2
[{"ID":1,"UserName":"username","FirstName":"first","LastName":"last","email":"example#example.com"}]
ajaxRequest.open("GET", url, false);
Third parameter says if the request is asynchronous or not. So by looking at your code it should be synchronous.

Cache pages using XMLHttpRequest

Everything is and is run on the same domain in the latest versions of the major browsers.
var xmlhttp = new XMLHttpRequest();
var sites = ["/page1", "/page2", "/page3"];
var cache = {};
function xhrStart(url) {
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function isOkXhr() {
return (xmlhttp.readyState == 4 &&
(xmlhttp.status >= 200 && xmlhttp.status < 300));
}
function reload() {
var len = sites.length;
var i;
for (i = 0; i < len; i++) {
var url = sites[i];
xmlhttp.onreadystatechange = function() {
if (isOkXhr())
cache[url] = xmlhttp.responseText;
}
xhrStart(url);
}
}
Reload function should be to cache all pages, but in fact all queries return Aborted in the debugger, except the last one. What could be the problem?
You are using one XHR object and keep writing over it in the loop. When you call open() it aborts the previous request. The for loop does not wait for the request.
Either create a new XHR request or wait til the other request is done before you make the next request.
var sites = ["/page1", "/page2", "/page3"];
var cache = {};
function xhrStart(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status >= 200 && xmlhttp.status < 300) {
cache[url] = xmlhttp.responseText;
} else {
//what are you going to do for error?
}
}
};
xmlhttp.send();
}
for (var i = 0; i < sites.length; i++) {
var url = sites[i];
xhrStart(url);
}

How to make the data downloaded same across all the versions of browsers?

I am downloading a file in my java application using jquery.
It is downloading in correct format in IE8 where as Format is getting changed when i am using IE10.
Here is my code, where I am setting hearder.
function converthtml() {
var CustomerID = document.getElementById('customerID').value;
var ci = document.getElementById("ci").value;
var strvar;
strvar = term.textContent || term.innerText;
strvar = encodeURIComponent(strvar);
var xmlHttp;
var xmlHttp;
var flag = 0;
if (typeof XMLHttpRequest != "undefined") {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) {
alert("Browser does not support XMLHTTP Request");
return;
}
xmlHttp.onreadystatechange = stateChange2;
function stateChange2() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
//alert("response : "+xmlHttp.responseText);
alert("Session value saved successfuly");
}
}
var params = "sessiondata=" + strvar + "&ci=" + ci + "" + "&customerID=" + CustomerID;
xmlHttp.open("POST", "DownloadSession", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(params);
// xmlHttp.send("sessiondata="+strvar+"");
document.getElementById("downloadSession").disabled = false;
}
I suspect the following statement is causing the format change
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Kindly suggest me an alternative that keeps content-type same across all the browser versions......

Trouble with having global JavaScript variables updated

I am trying to get a XML document sorted and decided to go for the "sort via XSLT" approach.
However, I am having trouble updating my two global variables that should contain the content of the XML and XSLT files and I can't really figure out why.
Up until now I never had this kind of problem and global variables used to work... I also didn't declare them inside the functions, but used the global name instead and also tried using window.variable, but to no avail.
Does anyone have an idea why the code doesn't update the global variable?
best regards,
daZza
<script type="text/javascript">
var xml = "";
var xsl = "";
function callSort()
{
loadSortXML();
loadSortXSLT();
sortXML();
}
function loadSortXML()
{
var xmlHttp = null;
var xmlData;
var xmlFile = "data/LessonsLearned.xml";
if (typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp)
{
try
{
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e)
{
xmlHttp = null;
}
}
}
if (xmlHttp)
{
var url = xmlFile;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
xml = xmlHttp.responseXML;
}
}
xmlHttp.send();
}
}
function loadSortXSLT()
{
var xmlHttp = null;
var xmlData;
var xmlFile = "data/xslt.xml";
if (typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp)
{
try
{
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e)
{
xmlHttp = null;
}
}
}
if (xmlHttp)
{
var url = xmlFile;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
xsl = xmlHttp.responseXML;
}
}
xmlHttp.send();
}
}
function sortXML()
{
console.log("XML " + xml);
console.log("XSL "+ xsl);
var parser = new DOMParser();
var domToBeTransformed = parser.parseFromString(xml, "text/xml");
var xslt = parser.parseFromString(xsl, "text/xml");
var processor = new XSLTProcessor();
processor.importStylesheet(xslt);
var newDocument = processor.transformToDocument(domToBeTransformed);
var serializer = new XMLSerializer();
var newDocumentXml = serializer.serializeToString(newDocument);
alert(newDocumentXml);
}
</script>

Javascript Functions Confusing AJAX Responses from CGI Request/Response

I have 3 Javascript functions called from the body onload in the HTML page.
Each Javascript function is contained in it's own Javascript file. Each Javascript file corresponds to another CGI script on the server.
The bodyonload.js looks like:
function bodyOnload() {
getElementsA();
getElementsB();
getElementsC();
}
Each getElements function simply calls a CGI script to get the contents for 3 different selectboxes.
The problem is that as all 3 functions are called asynchronously the select boxes are getting the wrong results. It's almost like the 3 functions are stepping on each other and putting the CGI responses in the wrong selectbox. I know the CGI responses are correct. This works fine if I serially call each function from the others. Like calling the 2nd function from the first and the 3rd function from the second. The asynchronous nature of them running at the same time seems to cause the problem.
This is the general code for each javascript file that contains the getElements functions.
function getElementsA() {
strURL = "http://test.com/scriptA.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxA(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxA(str)
{
document.getElementById("selectBoxA").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxA");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
-------------------
function getElementsB() {
strURL = "http://test.com/scriptB.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form- urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxB(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxB(str)
{
document.getElementById("selectBoxB").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxB");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
------------------------
function getElementsC() {
strURL = "http://test.com/scriptC.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxC(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxC(str)
{
document.getElementById("selectBoxC").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxC");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
It's almost like the 3 functions are stepping on each other
That's exactly what's happening, you're overwriting the onreadystatechange handler set on getElementsA when you call getElementsB, and then again when you call getElementsC. That's because this and self are the global object in all three functions (assuming they're all similar to getElementsA).
You can circumvent that by changing your function calls to object instantiation:
function bodyOnload() {
new getElementsA();
new getElementsB();
new getElementsC();
}

Categories