JQuery display XSLT into my html page - javascript

Can someone help me with this please?
basically I am trying to display the result of my transformed XSLT into an existing page, the transformation seem to be working, but it's not displaying the results when I run my html page. I have tried to run the XSL independently and it's seem to display correctly on his own, so that will leave me with jQuery.
Thank you
This is my code:
$(document).ready(function(){
displayResult();
});
function loadXMLDoc(filename)
{
var deferred = $.Deferred();
var promise = deferred.promise();
$.ajax({
url: filename,
type: 'get',
dataType: 'xml',
success: function(data) {
console.log("resolved");
deferred.resolve(data);
}, error :function(v1, v2)
});
return promise;
}
function displayResult(){
var xmlPromise = loadXMLDoc("my.xml");
var xslPromise = loadXMLDoc("my.xsl");
$.when(xmlPromise, xslPromise).done(function(xml, xsl){
if (document.implementation && document.implementation.createDocument)
{
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
var resultDocument = xsltProcessor.transformToFragment(xml, document);
$('#example').append(resultDocument);
} else if (window.ActiveXObject)
{
/* IE */
var ex = xml.transformNode(xsl);
$('#example').innerHTML = ex;
}
});
}

Related

File not reaching till handler's method

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
$(document).ready(function () {
$("#Button1").click(function (evt) {
var fileUpload = $('[id$=FileUpload1]')[0].value.split(",");
var data = new FormData();
for (var i = 0; i < fileUpload.length; i++) {
data.append(fileUpload[i].name, fileUpload[i]);
}
var options = {};
options.url = "Handler.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) { alert(result); };
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
evt.preventDefault();
});
});
This was my jquery and below is my handler file code ......
till end i am getting value while debugging but in motto of making upload multiple images at a while i am unable to have any value in handle
handler code
public void ProcessRequest (HttpContext context) {
string filePath = "FileSave//";
foreach (string file in context.Request.Files)
{
HttpPostedFile filed = context.Request.Files[file];
filed.SaveAs(context.Server.MapPath(filePath + filed.FileName));
context.Response.Write("File uploaded");
}
}
You can try this way if you would like to.
$(document).ready(function () {
$("#Button1").click(function (evt) {
evt.preventDefault();
var formdata = new FormData();
var fileInput = $('#sliderFile'); //#sliderFile is the id of your file upload control
if ($(fileInput).get(0).files.length == 0)
{ //show error
return false;
}
else
{
$.each($(fileInput).get(0).files, function (index,value) {
formdata.append(value.name, value);
});
$.ajax({
url: 'Handler.ashx',
type: "POST",
dataType: 'json',
data: data,
processData: false,
contentType:false,
success: function (data) {
if (data.result) {
//return true or any thing you want to do here
}
else {
//return false and display error
}
},
error: function (data) {
//return false and display error
}
});
}
});//button click close
});//document.ready close
Try it and let me know
EDIT: Remember but, HTML5 FormData is not available in older browsers and your code will silently fail. If you need to support older browsers you might need to perform progressive enhancement by testing the capabilities of the browser and falling back to a standard form POST if the browser doesn't support FormData:
if(window.FormData === undefined) {
// The browser doesn't support uploading files with AJAX
// falling back to standard form upload
} else {
// The browser supports uploading files with AJAX =>
// we prevent the default form POST and use AJAX instead
e.preventDefault();
...
}
For more information on this you can see answer I have accepted for one of my questions. It's pretty much clear there what is the issue regarding. Here is the link
EDIT : Just adding these LINK1 and LINK2 for those who come looking for the answer.
use HttpContextBase[] instead of just HttpContext

How to Call a Web Service in a Cross-Browser way

I want to call a Web Service from Mozilla, Internet Explorer and Chrome.
Bellow is my LaboratoryService.js file which calls the Web Service:
function StringBuffer() {
this.__strings__ = new Array;
}
StringBuffer.prototype.append = function (str) {
this.__strings__.push(str);
};
StringBuffer.prototype.toString = function () {
return this.__strings__.join("");
};
function LaboratoryService() {
this.url = "http://25.48.190.93:8082/labratory?wsdl";
}
LaboratoryService.prototype.buildRequest = function () {
var oBuffer = new StringBuffer();
oBuffer.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" ");
oBuffer.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
oBuffer.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
oBuffer.append("<soap:Body>");
oBuffer.append("<getLabratory xmlns=\"http://nano.ito.ir/\" />");
oBuffer.append("</soap:Body>");
oBuffer.append("</soap:Envelope>");
return oBuffer.toString();
};
LaboratoryService.prototype.send = function () {
var oRequest = new XMLHttpRequest;
oRequest.open("post", this.url, false);
oRequest.setRequestHeader("Content-Type", "text/xml");
oRequest.setRequestHeader("SOAPAction", this.action);
oRequest.send(this.buildRequest());
if (oRequest.status == 200) {
return this.handleResponse(oRequest.responseText);
} else {
throw new Error("Request did not complete, code " + oRequest.status);
}
};
LaboratoryService.prototype.handleResponse = function (sResponse) {
var start = sResponse.indexOf('div') - 4;
var end = sResponse.lastIndexOf('div') + 7;
return sResponse.substring(start, end);
};
Bellow is my HTML code which uses LaboratoryService.js to show data:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Labratories</title>
<script language="JavaScript" src="LaboratoryService.js"></script>
<script language="JavaScript" src="jquery-1.8.0.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function () {
$("#btnGetLaboratories").click(function () {
var oService = new LaboratoryService();
var fResult = oService.send();
var newData = $('<div/>').html(fResult).text();
$("#divResult").html(newData);
});
});
</script>
</head>
<body>
<input id="btnGetLaboratories" type="button" value="Get Laboratories" />
<div id="divResult">
</div>
</body>
</html>
This approach works fine in Internet Explorer.
The problem is that this approach does not work in FireFox and Chrome.
I think that the oRequest.send(this.buildRequest()); does not work in FireFox and Chrome.
Edited Web Service Call Using JQuery
I changed LaboratoryService.prototype.send to use JQuery to call Web Service as bellow:
LaboratoryService.prototype.send = function () {
$.ajax({
type: "POST",
url: this.URL,
contentType: "text/xml",
headers: { "SOAPAction": this.action },
success: function (msg) {
return this.handleResponse(msg);
},
error: function (e) {
alert('error');
}
});
};
But it alerts error. How do I call Web Service using JQuery?
Again Edited Code
I changed my JQuery AJAX call as bellow. It works fine in Internet Explorer but returns error in Chrome and Firefox.
LaboratoryService.prototype.send = function () {
$.ajax({
type: "POST",
url: this.URL,
contentType: "text/xml; charset=\"utf-8\"",
dataType: "xml",
data: this.buildRequest(),
processData: false,
success: function processSuccess(data, status, req) {
if (status == "success") {
var sResponse = req.responseText;
var start = sResponse.indexOf('div') - 4;
var end = sResponse.lastIndexOf('div') + 7;
var newData = $('<div/>').html(sResponse.substring(start, end)).text();
$("#divResult").html(newData);
}
},
error: function () {
alert('error');
}
});
};
Just change :
LaboratoryService.prototype.send = function () {
var oRequest = new XMLHttpRequest;
oRequest.open("post", this.url, true);
oRequest.setRequestHeader('User-Agent','XMLHTTP/1.0');
oRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oRequest.setRequestHeader("SOAPAction", this.action);
oRequest.send(this.buildRequest());
if (oRequest.status == 200) {
return this.handleResponse(oRequest.responseText);
} else {
throw new Error("Request did not complete, code " + oRequest.status);
}
};
Please, refer this link.

Javascript - XMLHttpRequest failing in Internet Explorer

* SOLVED * Answer is in separate post below
This code runs fine in FireFox but it will not run in Internet Explorer 8. It gives me the error of "access denied. Is there something I am missing?
function loadXMLDoc(dname){
if (window.XMLHttpRequest){
var xhttp=new XMLHttpRequest();
}
else{
var xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname,false);
xhttp.send();
return xhttp.responseXML;
}
var xmlDoc=loadXMLDoc("notSchema.xml");
var x=xmlDoc.getElementsByTagName('ROOT_NODE_ID');
It specifically doesn't like the .open() and the .send()
Edited...
var x;
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(http){
xmlDoc = http;
alert(http);
x=http.getElementsByTagName("ROOT_NODE_ID");
},
error: function(html){
alert('failure: ' + html);
}
});
}
loadXMLDoc("notSchema.xml");
for (var i=0;i<x.length;i++)
{
if(x[i].childNodes[0] == undefined) {
treeArray[count]="null";
count++;
}else{
//return ROOT_NODE_ID
treeArray[count]=x[i].childNodes[0].nodeValue;
count++;
}
}
Edited the Code once again. What I'm trying to do is load the XML, parse for the tag "ROOT_NODE_ID" and then get that value and store it into an array
When I run that code in firefox, it returns 51, which is the number of ROOT_NODE_ID tags and fills the tree that I am making.
When I run the same exact code in IE8, it does not even alert.
I'm Stumped.
I figured it out. Like I said before, if you run the code above in Firefox, it returns the 'object' and if you run it in IE8, it returns the contents of the object. I solved this problem by loading the content of the object again in IE8, thus turning the content of the object back into an object that will be ready to be parsed. If that makes any sense.
Just to clarify to people that are just visiting this thread. When I called 'alert(http);' in firefox, it would return '[object XMLDocument]', but in IE8 it would return the actual contents of '[object XMLDocument]'.
var treeArray=new Array();
var count = 0;
var x;
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(http){
var xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
//Loading the contents of the object 'http' a second time, which turns it into an object again.
xmlDocument.loadXML(http);
x = xmlDocument.getElementsByTagName("ROOT_NODE_ID");
alert(x.length);
},
error: function(html){
alert('failure: ' + html);
}
});
}
loadXMLDoc("notSchema.xml");
for (var i=0;i<x.length;i++)
{
if(x[i].childNodes[0] == undefined) {
treeArray[count]="null";
count++;
}else{
//return ROOT_NODE_ID
treeArray[count]=x[i].childNodes[0].nodeValue;
count++;
}
}
Zack,
You can use jquery to do the ajax call - jquery will do everything properly behind the curtains.
In your case here:
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(html){
var x=xmlDoc.getElementsByTagName('ROOT_NODE_ID');
},
error: function(html){
alert('failure: ' + html);
}
});
}

jQuery AJAX works on mobile safari, but not a UIWebView?

I have a basic jQuery ajax function to log the user in via a UIWebView. However, for some reason it returns blank when it's in a UIWebView. It works fine in mobile safari, and chrome and firefox on my computer.
Here's my code:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});
The theRetrievedData just returns blank on the alert.
Please help!
PS: The app is called "Dudles" in the app store (it's free) if you want to try to login. You will get a blank message from the alert.
Can you post your PHP code as well?
I refactored the code you wrote into how I would write it just to see if I could spot any bugs, and nothing seemed glaringly incorrect. Here is what I have so far:
$(document.body).on('click', '#login_button', function () {
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: $(this).closest('form').serialize(),
success: function (response) {
var delimiter = "?!?success?!?";
var isSuccessful = response.indexOf(delimiter) !== -1;
if (!isSuccessful) {
// handle error
return;
}
$('#content').fadeOut(500, function () {
location = response.split(delimiter)[1];
});
}
});
});
try to send ajax request with async:true, like this:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
async:true,
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});

Jquery Ajax call doesn't work fine in IE8

I'm loading some data lively from the database and each row have some links that do some things over that.
They work flawlessly except for the last one I've implemented which seems not to be working on IE
$('.lockFile').click(function(){
var url = "functions/lock_call.php";
var unlock = 'assets/lock-unlock.png';
var lock = 'assets/lock.png';
var action = 'unlock';
var id = $(this).parent().parent().attr('id');
var image = $(this).children(0);
if (image.attr('src') == unlock)
action = 'lock';
var data = 'id='+id+'&action='+action;
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
success: function(){
alert (action);
if (action == 'lock')
image.attr('src', lock);
else
image.attr('src', unlock);
}
});
return false;
});
What could be wrong?
The alert is performer on "success" but nothing is made. That is, the script doesn't run.
IE 8 has some amazing variables reserved, try this one
$('.lockFile').click(function(){
var Aurl = "functions/lock_call.php";
var AunAlock = 'assets/lock-unlock.png';
var Alock = 'assets/lock.png';
var Aaction = 'AunAlock';
var Aid = $(this).parent().parent().attr('id');
var Aimage = $(this).children(0);
if (image.attr('src') == AunAlock)
Aaction = 'Alock';
var data = 'id='+Aid+'&action='+Aaction;
$.ajax({
type: "POST",
url: Aurl,
data: data,
cache: false,
success: function(){
alert (Aaction);
if (Aaction == 'lock')
Aimage.attr('src', Alock);
else
Aimage.attr('src', AunAlock);
}
});
return false;
});
try to declare data in JSON format
var data = {'id':id, 'action': action}

Categories

Resources