Output XML code with Jquery - javascript

Consider the following script for outputting some XML code:
var xmlAsString = '<?xml version="1.0"?><person><name gender="male"></name></person>';
$(document).ready(function(){
$(".generator").click(function(){
alert(xmlAsString);
$("#container").append("<div id='contXML'>"+xmlAsString+"</div>")
});
});
The alert outputs everything as I want but nothing shows later. If I put some random string variable (without the < > chars everything works fine).

That's because you have to html encode your xml otherwise the browser tries to parse it. I use this simple function.
var xmlAsString = '<?xml version="1.0"?><person><name gender="male"></name></person>';
function htmlEncode(value){
return $('<div/>').text(value).html();
}
$(document).ready(function() {
$(".generator").click(function() {
alert(xmlAsString);
$("#container").append("<div id='contXML'>" + htmlEncode(xmlAsString) + "</div>")
});
});
Fiddle here http://jsfiddle.net/DqDEU/

Related

JSON.parse() not working even though JSON string is valid

I am trying to post a form through AJAX jQuery. The PHP script to which it points returns a JSON encoded array. But, at the receiving end on the main page JSON.parse() is not working.
Please suggest if I am missing on some file types which need to be included
Here is my code.
< script type = "text/javascript" >
$(document).ready(function() {
$("#send").submit(function() {
//$("#submit_form").html('');
$("#modal-text2").html("<img src=" + "img/loader1.gif "
+ "/></br</br><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>");
$("#myModal2").modal('show');
$.post($("#send").attr("action"), $("#send").serialize(), function(data) {
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}
});
//Important. Stop the normal POST
return false;
});
});
< /script>
The JSON encoded array which is being sent back by the PHP script is:
{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}
don't know if its the cause of hte problem or if its just a typo in here, but you have a typo in the following line:
<img src="+"img/loader1.gif "+"/></br</br>
you aren't closing the first linebreak, and the slash should come after the br - also not sure why you have so many quuotes in that html block - it should be :
$("#modal-text2").html("<img src='img/loader1.gif'/><br/><br/><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>")
You should console.log(data) to check if the data value has any problem.
use try/catch to catch message if error happened in JSON.parse.
try {
var decode = JSON.parse(data);
}catch(e){
console.log(e) ;
}
Make sure your php responses the json in the right way. Or there may have some invisible character and make the problem.
<?php
$data = ... ;
header('Content-type:application/json;charset=utf-8');
echo json_encode($data) ;
?>
I thought there is a sytax error in your script just check it out in the last line of script the closing tag of < /script> has space, remove it and try -
</script>
i execute the parsing snippet of your code it is working fine.
var data = '{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}';
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}

How do I fetch PHP script output from Javascript?

This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/

document.documentElement function does not display proper result

I am trying to parse XML file using java-script. According to the tutorial I read I found That To get the Root element, I have to use document.documentElement.
I use that syntax but when I tried to display the returned value from that Syntax, the browser displays [object HTMLHtmlElement].
My question is: (1) Why I am getting [object HTMLHtmlElement] displayed in the web browser.
(2) According to the below posted XML-File, What should I expect the output to be
after usingrootElement = document.documentElement;
Please find below the code I used(Javascript) and the XML file.
Javascript
function findWriter()
{
var schriftstellerKnoten, SpracheKnoten;
var FuellerKnoten, DichtungKnoten, Anzeige, rootElement;
rootElement = document.documentElement;
document.write(rootElement);
}
XML file:
<?xml version="1.0" ?>
<Schriftsteller>
<Englischsprache>
<Dichtung>
<fueller>
<name>Jane Austin</name>
<name>Rex Stout</name>
<name>Dashiell Hammett</name>
</fueller>
</Dichtung>
</Englischsprache>
</Schriftsteller>
document.documentElement will get you the root HTML tag of the page in which your javascript is present.
To fetch and display the XML content, you must get access to the XML document and then use it to load the XML file like the following:
function findWriter()
{
var schriftstellerKnoten, SpracheKnoten;
var FuellerKnoten, DichtungKnoten, Anzeige, rootElement;
if (window.XMLHttpRequest){
xhttp=new XMLHttpRequest(); //For non IE browsers
}
else { // for IE 5/6
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","test.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML; //Fetch the XML file contents
var nameEl = xmlDoc.documentElement.getElementsByTagName("name"); //Get all <name> tags in it
for (i=0; i<nameEl.length; i++){
document.write("Name" + i + ": " + nameEl[i].firstChild.nodeValue + "<br/>"); //write names
}
}

Parsing XML JQuery Ajax Response with Namespace

I'm executing a web service call using JQuery and it's ajax function and I'm unable to parse the data coming back. When I alert the data (alert($(data).find("return").text()) its empty. I see the server responding with xml data as outlined below and when I alert(data) I get [object XMLDocument]. Is txt = $(data).find("return").text() valid given my XML structure with a namespace below? I can see the full xml string in firebug. Any ideas?
var txt = $(data).find("ns1\:return").text(); works on Chrome and Firefox, but not Safari
index.js:
$(function () {
$.ajax({
url: url,
success: function (data) {
var ndx = 0,
row,
**txt = $(data).find("return").text(),**
xml = unescape(txt),
xmlDoc = $.parseXML(xml),
firstrow = $(xmlDoc).find(
"results").children(":first");
// populate the table based on the results returned by
// the web service
$("table.results thead").empty();
$("table.results tbody").empty();
row = $("<tr/>");
row.append($("<th/>").text("#").addClass("ndx"));
firstrow.children().each(function () {
row.append($("<th/>").text(this.nodeName));
});
row.appendTo($("table.results thead"));
$(xmlDoc).find("row").each(function () {
row = $("<tr/>");
row.append($("<td/>").text(ndx + 1).addClass("ndx"));
$(this).children().each(function () {
row.append($("<td/>").text($(this).text()));
});
row.appendTo($("table.results tbody"));
ndx++;
});
// clear the table if no results were returned
if (ndx == 0) {
// no rows returned
$("table.results thead").empty();
$("table.results tbody").empty();
}
statusNotice("Records Returned: " + ndx);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// display the error returned by the web service
var xmlDoc = $(XMLHttpRequest.responseXML);
statusError(xmlDoc.find("Text").text());
},
complete: function(XMLHttpRequest, textStatus) {
// hide the busy dialog
$("#busy-dlg").dialog("close");
}
});
});
index.html:
Demo
<script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-min.js"></script>
<script type="text/javascript" src="js/jquery.layout-latest.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
//table displaying results from ajax call here
</body>
</html>
XML:
<ns1:executeResponse xmlns:ns1="http://sqlws.test.com">
<ns1:return>
<results>
<row>
<attribute1>value1</attribute1>
<attribute2>value2</attribute2>
</row>
<row>
<attribute1>value1</attribute1>
<attribute2>value2</attribute2>
</row>
</results>
</ns1:return>
</ns1:executeResponse>
When an element is prefixed by a namespace, you have to also add the namespace:
.find('ns1:return') does not work, because : is used by jQuery as pseudo-selectors.
.find('ns1\:return') does not work either, because a single backslash in a string is used as an escape character. "ns1\:return" becomes "ns1:return" which is equal to the previous one.
.find('ns1\\:return') should be used. The double backslash is used to escape the colon.
It appears that the last solution works fine in IE and Firefox, but not Opera, Chrome or Safari. To get maximum compatibility, use jQuery selectors with, and without fake prefix, ie. "ns1\\:return, return" instead of a plain ns1\\:return.
Demo: http://jsfiddle.net/5BQjv/51/
// For example, this is the result:
var data = '<ns1:executeResponse xmlns:ns1="http://sqlws.test.com">' +
'<ns1:return>' +
'<results> <row> ... </row> </results>' +
'</ns1:return>' +
'</ns1:executeResponse>';
// The very first thing is to parse the string as XML. NOT later!
var $xmlDoc = $($.parseXML(data));
// Then, look for the element with the namespace:
var $txt = $xmlDoc.find('ns1\\:return, return');
// No need to use unescape or something, just use DOM manipulation:
// `results` is the immediate child. Don't use .find, but .children
var $firstrow = $txt.children("results").children(":first");
As you may have noticed, I have prefixed some variables with a dollar sign. It's the convention to prefix variables which refer to jQuery objects with a dollar sign, to avoid confusion during/after development.

AJAX parse + Yahoo YQL returning no results?

I'm working on a script that gets all the <table> elements from an external website by going through Yahoo's YQL. This has worked fine recently, but it stopped working as of today. I'm not entirely sure why, all websites used to work with this code:
<script type="text/javascript">
$(document).ready(function () {
var container = $('#target');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"
+ "q=select%20*%20from%20html%20where%20url%3D%22"
+ encodeURIComponent(url)
+ "%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("body");
container.append(justTable);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#target').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
data = data.replace(/<img[^>]*>/g, '');
return data;
}
doAjax('http://www.google.com');
});
</script>
I changed the url to google and changed it to find the <body> tag instead of <table> tags to better show its not working. I looked at the URL that it's requesting and it's not showing any content. Not sure what the problem is though.
Have you checked if the "external website" you have crawled has structural changes?
When it has worked before and now not anymore, then my tip is that the site structure has changed.
It looks like the problem was that YQL was down? I just tested it again and it worked out fine. I wish they would tell us in the future if an outage occurred.

Categories