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>
Related
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>");
I am adding dynamic span with onclick .
$.ajax({
url:path,
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: formdata,
success: function (result) {
if(result==1){
for (var FileName of formdata.entries())
{
var fileName=FileName[0].trim();
**$("#"+PreviewControl).append('<span onclick="showaleart("'+fileName+'")">'+fileName+'</span>');
$("#"+hdnHasFile+"").val(1) ;**
}
}
}
});
function showaleart(filename){
alert(filename);
}
But when i click on that span element its giving error as Uncaught SyntaxError: Unexpected token }
But if i replace onclick="showaleart("'+fileName+'")" to onclick="showaleart()" with out any argument.
It does not give error.and the click is working.
when i click on element and inspected the element . it was creating element like this.
<span onclick="showaleart(" bank.jpg")"="">Bank.jpg</span>
You aren't using quotations properly, the second set of " renders the bank.jpg outside of the onclick. You need to use different type of quotes and escape them. Try this instead:
'<span onclick="showaleart(\''+fileName+'\')">'+fileName+'</span>'
or
`<span onclick="showaleart('${fileName}')">${fileName}</span>`
I am trying to set the content of an empty div after an AJAX call with the data message. I also wired the function to my CHtml::submitButton, which should call the function when clicked, but nothing is happening. Any suggestions?
<div id="myResult">
</div>
JavaScript:
function successMessage(){
$.ajax({
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
PHP:
echo CHtml::beginForm(array('myForm'), 'get', array('form'));
echo '<div class="row form">';
echo '<div class="row buttons">';
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
echo '</div>';
echo '</div>';
Your problem relies in the following line:
$('myResult').html(data);
Here, you are trying to do a jquery selection to an element, which you are not using in your html (this is only possible via pollyfils). So you have to select the element by its ID:
$('#myResult').html(data);
And another thing i've seen, what is the url where you are doing the request?
<script>
function successMessage(){
$.ajax({
type: "GET",
url: "/please/add/an/url/",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
</script>
first of all, when you are using onclick function like this :
<input type="submit" onclick="successMessage()">
you should use this instead:
<input type="submit" onclick="successMessage();result false;">
but when you are already using jquery, then better approach is:
$( document ).ready(function() {
successMessage(){
// your ajax goes here
}
$('#myResult').click(function(e){
e.preventDefault();
successMessage();
});
});
Then you need to repair your successMessage function. You see, the data you are setting there are not the data, that are coming out as an output. If you need ajax then you probably want to get the result from some php script on some other url. Then you should do it like this :
function successMessage(){
$.ajax({
type: "GET",
url : 'index2.php',
dataType: "json",
data: { mydata: '<div> Replace div with this content</div>'},
success: function(data){
$('#myResult').html(data);
}
})
}
Then you need a php file named index2.php which can look like this :
<?php
echo json_encode($_GET['variable']);
?>
And i dont know if this your line :
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
also put the </form> tag after the form to close it.
This should work for you. I tried it and it works fine.
Try this:
$.ajax({
url: "test.html",
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('#myResult').html(data);
}
})
selector jQuery incorrect in response ajax. and define Url in ajax.
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.
I have been working on a shopping cart that the user can add/remove order items as they please and am returning an updated sub-total via a webservice using jQuery $.ajax
Here is how I am calling the webservice and setting the sub-total with the response.
//perform the ajax call
$.ajax({
url: p,
data: '{' + s + '}',
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#cartRow" + orderID).find(".subTotal").text(sTotal);
},
failure: function() {
//if the orer was not saved
//console.log('Error: Order not deleted');
}
});
The response I am getting seems perfectly fine:
{"d":"128.00"}
When I display the total on the page it displays as 128 rather than 128.00
I am fully sure it is something very simple and silly but I am so deep into it now I need someone with a fresh brain to help me out!!
Cheers :)
EDIT
I am also using $.ajaxSetup to set the correct contentType:
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data) {
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
});
That is because the value is treated as a number, while you want it treated as a string.
When you are using '.. .text(sTotal)', you are actually calling the .toString() method on the Number object wrapping the primitive sTotal. And since this is a whole number, it displays it without decimals.
You need to use a format the number as a string prior to calling .text(foo) for the number to be formatted like that.
This will give you two decimals
var a=1/3;
a = a.toString();
switch(a.lastIndexOf(".")){
case -1:
a+=".00";
break;
case a.length-2:
a+="0";
break;
default:
a=a.substring(0, a.indexOf(".") + 3);
}
alert(a);
I don't see anywhere in this code where you access the d property of the response.
Perhaps you mean to do this?
$("#cartRow" + orderID).find(".subTotal").text(sTotal.d);
// --------------------------------------------------^^
EDIT
Ok, I see the problem. You're returning JSON but not defining a dataType in the $.ajax() call. This means that jQuery sees your application/json mimetype and interprets the response as JSON. 128.00 in JSON is a Number, not a String. However, "128.00" would be a String.
In order to keep this working, You need to format the response before printing it (as others have suggested), or adjust your endpoint to return a valid JSON string.
Here's my test to prove the solution
<div id="test">
Subtotal <span class="subTotal"></span>
</div>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" charset="utf-8">
google.load("jquery", "1.4.2");
</script>
<script type="text/javascript" charset="utf-8">
$.ajax({
url: 'test.php',
data: {},
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#test").find(".subTotal").text(sTotal);
}
});
</script>
and test.php
<?php
header( 'Content-type: application/json' );
echo '128.00';
Output
Subtotal 128
But when I change test.php to be this
<?php
header( 'Content-type: application/json' );
echo '"128.00"';
The expected output is generated
Subtotal 128.00
Or, you could alternatively tell jQuery to treat the response as text by specifying a dataType parameter, for example
$.ajax({
url: 'test.php',
data: {},
dataType: 'text', // <---- here
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#test").find(".subTotal").text(sTotal);
}
});
EDIT 2
Ok, after messing with this some more, I see what's going on. The dataFilter handler you defined converts the response into JSON itself, and in this case, returns the string 128.00. However, jQuery still applies the intellgent-guessed dataType (which is JSON) to this value before sending it to the success handler.
There are a multitude of ways to fix this, all of which depend on what other AJAX calls your application relies on this setup for. The quick-fix I applied in my test was to do this
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
// define the text data type so that we return data.d, jQuery doesn't parse it as JSON again
dataType: 'text',
dataFilter: function(data) {
data = $.parseJSON( data ); // Use jQuery's parsing
if (data.hasOwnProperty('d'))
{
return data.d;
}else{
return data;
}
}
});
But that may not work across the board for you
Please try this:
$("#cartRow" + orderID).find(".subTotal").text(sTotal.toFixed(2));
HTH