Not able to print <> brackets in XML output in html - javascript

So this is with regards to one of my previous questions, where in i wanted to replace "\n" with a "br" tag in HTML using JS.
For the same page, if someone passes a XML or RPC query, i want to return an XML output.
A typical XML output looks like:
<racks>\n
<rack>\n
<rack-name>0</rack-name>\n
<chassis>\n
<serial-number>XYZ789</serial-number>\n
</chassis>\n
</rack>\n
</racks>\n
</diag>\n
</data>\n
</rpc-reply>\n
**I want to be able to print it in this way: (replacing \n with a br)
<racks>
<rack>
<rack-name>0</rack-name>
<chassis>
<serial-number>XYZ789</serial-number>
</chassis>
</rack>
</racks>
</diag>
</data>
</rpc-reply>
**
But i am only getting the plain text in the output, which is 0 and XYZ789 with so many \n's.
The JS:
$(function() {
$('button').click(function() {
$.ajax({
url: '/runCommand_query',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
response = response.replace(/(\n)/g, "<br>");
console.log(response);
$("#opt").html(response);
},
error: function(error) {
console.log(error);
$("#opt").val(error);
}
});
});
});

You should use text() instead of html() like :
$("#opt").text(response);
Else the browser will interpret the code as HTML tags, and shows you just the text.
Hope this helps.
UPDATE :
var response = "<racks>\n<rack>\n<rack-name>0</rack-name>\n<chassis>\n<serial-number>XYZ789</serial-number>\n</chassis>\n</rack>\n</racks>\n</diag>\n</data>\n</rpc-reply>\n";
$('#opt').text(response).wrap('<pre />');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="opt"></div>

Just tweaking Zakaria Acharki's answer a bit to get the final outcome as per my requirement:
response = response.replace(/</g, "<").replace(/>/g,">").replace(/(\n)/g,"<br>");

Related

Returing a list of strings and iterating over it

I am new to jQuery and I am trying to iterate through a list of strings after making an ajax call to a controller. In this controller, I am returning a list of strings and I want to iterate over this list in jquery and present it to the screen. Here is my code.
This is my controller
[HttpPost]
public ActionResult GetComments() {
var cmts = ex.GetComments(psts, psons);
var lstCmt = ex.GetCommentsList(cments, psons);
return Json(lstCmt);
}
This is my view:
<div>
<button id="ldBtn" class="btn btn-primary">Load</button>
</div>
<div id="cments">
</div>
<script src="~/Scripts/jquery-3.2.1.js"></script>
<script>
$(document).ready(function() {
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
type: "POST",
dataType: "html",
url: '#Url.Action("GetComments")',
data: {},
success: function(lists) {
//Something needs to be fixed here
$.each(lists, function(i, name) {
$('#comments').append('<p>' + name.Value + '</p>');
});
}
});
});
});
</script>
When I return the list, I am getting a huge string. How do I fix this?
Thanks in Advance
There's a couple of issues in your JS code. Firstly you're telling jQuery to expect a HTML response in the dataType setting. This is why you see the response as a string. This should be changed to JSON instead, that way jQuery will deserialise the response for you.
Secondly you're attempting to concatenate a Value property on each item in the list, yet they are strings (as you state you're returning a List<string> from your action), and will not have that property. You can simply append the name itself. Try this:
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
url: '#Url.Action("GetComments")',
type: "POST",
dataType: 'json',
success: function(comments) {
$('#cments').append('<p>' + comments.join('</p><p>') + '</p>');
}
});
});
I assume the #comments/#cments discrepancy is only due to amending parts of your code when creating the question.
Also note that I simplified the append() logic so that it appends all comments in a single call, which should be slightly faster.

Show Turtle-File on html page with line brakes

i am trying to show a turtle file on a very simple homepage i made.
<p class="lead" id="testbed-meta">
<script>
$.ajax({
cache: false,
type: "GET",
async: false,
url: "/native/api/resources/turtle",
success: function(data,status){
document.getElementById("testbed-meta").innerHTML = data;
},
error: function(xhl,status){
document.getElementById("testbed-meta").innerHTML = "Error";
},
statusCode:{
201: function(){
alert("Error");
}
}
});
</script>
HTML don't understand that it's turtle and makes it to one long String without line brakes and also deletes some parts. Maybe because there are some "<" and ">" that are not escaped.
Is there a nice way to show a ttl file via html and maybe javascript?
EDIT:
By the way, i forgot to say that i get something like this in the answer:
#prefix omn-federation: <http://open-multinet.info/ontology/omn-federation#> .
But HTML don't show the "http:/....." part. Only:
#prefix omn-federation: .
Maybe because of the "<" and ">" ?!
Try this in your success callback:
$("#testbed-meta").text(data);
jQuery's text() method escapes all HTML for you.
Additionally, if you'd like to get new lines in your HTML, you need to replace all new line characters to HTML's <br> tag:
$("#testbed-meta").text(data).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, "$1<br>$2");
try with a pre tag instead of p tag:
<pre class="lead" id="testbed-meta"></pre>
The HTML Preformatted Text (<pre>) represents preformatted text. Text within this element is typically displayed in a non-proportional font exactly as it is laid out in the file. Whitespaces inside this element are displayed as typed.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
<pre class="lead" id="testbed-meta"> </pre>
<script>
$.ajax({
cache: false,
type: "GET",
async: false,
url: "/native/api/resources/turtle",
success: function(data,status){
document.getElementById("testbed-meta").innerHTML = data.replace(/<br\s*\/?>/gi, '\n').replace(/</g, '<');
},
error: function(xhl,status){
document.getElementById("testbed-meta").innerHTML = "Error";
},
statusCode:{
201: function(){
alert("Error");
}
}
});
</script>
See this small snippets:
data = '<br/> \#prefix omn-federation: <open-multinet.info/ontology/omn-federation#>; . <br/> \#prefix rdf: <w3.org/1999/02/22-rdf-syntax-ns#>; . <br/>'
document.getElementById("testbed-meta").innerHTML = data.replace(/<br\s*\/?>/gi, '\n').replace(/</g, '<');
<pre id="testbed-meta"></pre>

Issue populating ajax response into a div

What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data

Put json result from php script into divs jQuery

I have two divs, each one should have a record name from a json result.
<div class="first"></div>
<div class="second"></div>
My json file is as follows :
[{"Name":"name1","Instruction":"instr"},
{"Name":"name2","Instruction":"instr again"}]
I want to put in the first div's value, the ‘Name‘ value of the first record, same for the second div but with the second record.
I'm using jQuery :
<script>
$(document).ready(function() {
$.post("data/result.php",
function(data) {
//alert("Data: " + data);
$('div.first').append(data.Name); //data.Name returns undefined
}
);
});
</script>
Any help would be appreciated.
as far as you are using post for you ajax call, the data returns as a json string, do this:
$(document).ready(function() {
$.post("data/result.php",
function(data) {
data = JSON.parse(data);
$('div.first').append(data[0].Name);
$('div.second').append(data[1].Name);
}
);
});
As previously mentioned you need to parse the result as json. You could use the built in parser in jquery. Like this:
<script>
$(document).ready(function() {
$.ajax({
url: 'data/result.php',
type: 'POST',
dataType: 'json',
success : function (data) {
$('div.first').append(data[0].Name);
}
});
});
</script>
First of all, you can give a datatype with a request:
$.post('data/result.php',function(data) { },'JSON');
If you are not posting any information, why not just use $.get ? (it's the same syntax btw)
$.post('data/result.php',function(data) {
var $first = $('div.first'),
$second = $('div.second');
$first.text(data[0].Name);
$second.text(data[1].Name);
},'JSON');
Also, if you use .append(..) it will be appended to whatever is already in the div. If that is your intention, use .append(...). However, if you want to replace the content of it, even if it is empty, use .text(...) or .html(...)

Parse complete html page with jquery

I load a html with ajax. I want to load the result in a jquery object. I tried that but it returns null. How can I do this? I got a complete page including doctype, head elements and body elements.
var test = $(result); //result contains html code
alert(test.html()); //returns null
I load the data with this function.
function ajaxLoadContent(element) {
$.ajax({
url: "url to the page",
type: "GET",
timeout: 5000,
datattype: "html",
success: function(result) {
//handler
},
});
return false;
It's a while ago, but maybe you're still interested in it..
The intern implementation of $(String) is not able to build an jQuery object that contains head or body tags. It will simply ignore them and move all elements inside on level up.
So if your string is for example
<html>
<head>
<meta ...>
</head>
<body>
<div id="a"/>
</body>
</html>
the resulting jQuery object will be an array of two elements
[<meta ...>, <div id="a" />]
to get a body-like jQuery object cut everything but the body content before passing it to jQuery:
body = '<div id="body-mock">' + html.replace(/^[\s\S]*<body.*?>|<\/body>[\s\S]*$/ig, '') + '</div>';
var $body = $(body);
now things work as expected.. for example
$body.find('#a')
Hope that helps..
test is just an html string, so you could simply do this to show the contents
alert(result);
and if you want to bind that to an element
$("#myDiv").html(result);
function ajaxLoadContent(element) {
$.ajax({
url: "url to the page",
type: "GET",
timeout: 5000,
datattype: "html",
success: function(data) {
var result = $(data);
},
});
return false;
You should now be able to call the result like this (remember it's not added to the DOM yet):
alert(result.html());
Add to the DOM
result.appendTo("body");
Let me know if this works for you.
Try the load method of jQuery object: http://api.jquery.com/load/
Load data from the server and place
the returned HTML into the matched
element.

Categories

Resources