jQuery.html() result, not interpreted as HTML by the browser - javascript

After a successful ajax call, I want to print the result on screen (in a DIV).
This result is a piece of HTML code.
$.ajax({
url: window.location.pathname + '/feedback-campaigns',
type: 'GET',
contentType: 'text/html',
success: function(data, textStatus, jqXHR) {
var result = data.campaigns.campaigns[0].text;
// result = "<b>TEST - do you see me?</b>"
$('.campaign-top-product-detail-page').html(result);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('NOK');
}
});
But, on screen I see this:
<b>TEST - do you see me?</b>
instead of the text in bold.

Use following
$.ajax({
url: window.location.protocol + '//' + window.location.host + window.location.pathname + '/feedback-campaigns',
type: 'GET',
contentType: 'text/html',
success: function(data, textStatus, jqXHR) {
var result = $.parseHTML(data.campaigns.campaigns[0].text); // result = "<b>TEST - do you see me?</b>"
$('.campaign-top-product-detail-page').html(result);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('NOK');
}
});
Update: write like this $.parseHTML(data.campaigns.campaigns[0].text);

It is because the response from server contains HTML entities, not actual HTML tags. To solve this, simply send the HTML such as <b>TEST - do you see me?</b>. (If you're using PHP on your server, then don't use htmlspecialchars on the output).

Remember that things like &lt will be not regarded as a part of HTML code but some character. So if you want to show the text which is bold, you should let it return as below
<b>TEST - do you see me?</b>
However, if you don't have permission to edit the result, other answers are good.

Related

Get content of paginated pages via ajax, filter it and append it to current page

I would like to load more functionality on my blog. I now have paginated pages, which is not what I want. I thought it would be easy to get the contents of these paginated pages via ajax, filter it, and append it to a div.
I'm not really sure if this is the way to go. This is what I tried:
$("a.next").on("click", function(e){
e.preventDefault();
var nextLink = $(this).attr("href");
console.log(nextLink);
$.ajax ({
url: "http://localhost:8888/" + nextLink,
datatype: 'html',
type: "GET",
success: function(data) {
var response = data;
$(".blogItems .holder").append(response);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
Can you guys point me in the right direction?
Your solution would work, providing that you'd detect the ajax call in the back end, and instead of the entire page, return just the parts where you are interested in (use Director::is_ajax() for that, and follow the hints in the comment of #micmania). If you would rather not make your controllers more complex and you don't mind the extra data being sent, you could also just retrieve the entire page (as you are doing now), and pick just the parts that you want to append to your existing document:
$.ajax ({
url: "http://localhost:8888/" + nextLink,
datatype: 'html',
type: "GET",
success: function(data) {
var response= $("#theDivIWant", data); //<- Here (untested, but should do the trick
$(".blogItems .holder").append(response);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
This solution also degrades nicely for people not using javascript, although I'm not exactlye sure if that's of any added value these days :-)

set an image sent as binary data from node.js in jquery ajax

I am retrieving an image which is stored as in binary form from mongoDB. and sending it as a json to jquery ajax. but console.log from node.js show it is fine but when request comes back to jquery ajax nothing happens, cannot see an image. And also image is saved in DB with type BUFFER. below is the code
jquery ajax code
$.ajax({
url: config.ipaddress+'/getCompanyImage',
contentType: 'image/png',
type: 'GET',
success: function(data, textStatus, jqXHR) {
$.each(data, function(index, result) {
alert('image result ' + result);
$("#headerCompanyImage").attr("src", result);
});
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
node.js code
exports.getCompanyImage = function(req,res) {
var_company.find({_id : req.session.company},function(err,company){
company.forEach(function(companyLoop){
console.log(companyLoop.company_image.contentType);
console.log(companyLoop.company_image.data);
res.contentType(companyLoop.company_image.contentType);
res.json(companyLoop.company_image.data);
})
});
}
I have got the solution. It has to be in binary form and then convert it toString('base64') and then send the response. and now it is working
var img = new Buffer(companyLoop.company_image.data, 'binary').toString('base64');
res.contentType(companyLoop.company_image.contentType);
res.send(img);
and in jquery it would be
$("#headerCompanyImage").attr("src", "data:image/png;base64," + data);

ajax method and SyntaxError : Unexpected token ":"

I'm in trouble with a simple script. I need to parse some xml response from a webservice
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function callws() {
$.ajax(function(){
type:"GET",
contentType: 'text/xml',
dataType:"xml",
url:"http://thewebservice/service.action?my=parameter",
timeout:4000,
async:false,
success: parseXml,
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.textStatus);
}
}); // ajax
function parseXml(xml) {
$(xml).find("result").each(function(){
$("#risposta").append($(this).find("row").text() + "<br />");
});//each
} //function parse
} // termine callws
I don't understand why nothing work! I've only an error log from Chrome console
SyntaxError : Unexpected token ":" at line 12 (contentType: 'text/xml',)
I try to use other parameters but all the rows below the first (type:"GET") seems wrong... imho the syntax is ok in all of the script!
Advices?
Vito
I think you have the ajax syntax wrong. The first parameter is a regular ole' object, not a function. Try this:
function callws() {
$.ajax({
type:"GET",
contentType: 'text/xml',
dataType:"xml",
url:"http://thewebservice/service.action?my=parameter",
timeout:4000,
async:false,
success: parseXml,
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.textStatus);
}
}); // ajax
// termine callws
^ All I did was take out function()
$.ajax(function(){
supposed to be
$.ajax({

jquery ajax function with json

Hi i am using this code to get contents from a json file but i am not able to show results
my code is
$(document).ready(function(){
$.ajax({
url: 'http://50.116.19.49/rest/user.json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 50000,
success: function(data, status){
alert(data);
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
In google chrome i can see that the request status is 200 and data is loaded. here is the link from which i am copying code The Link.... Any help!!!!
Thanks
Your code doesn't work because the http://50.116.19.49/rest/user.json resource return a JSON response instead of JSONP (difference).
So you can't make cross-domain calls via ajax BUT you can create a some proxy script ON YOUR SERVER which will make it for you. Example:
cross-domain-call.php
<?php echo file_get_contents('http://50.116.19.49/rest/user.json');?>
And change your script to
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1/cross-domain-call.php',
dataType: 'json',
timeout: 50000,
success: function(data, status){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
});
Since you don't seem to have access to remote webservice to convert it to JSONP, here is a solution using Yahoo's YQL as a proxy. YQL will retrieve file contents from any remote site and return as xml or jsonp.
Working DEmo http://jsfiddle.net/Uh8cz/2/
You will notice the response object has additional properties created by YQL
var yqlBaseUrl = 'http://query.yahooapis.com/v1/public/yql?q=';
var restUrl = 'http://50.116.19.49/rest/user.json';
var yqlQuery = 'select * from json where url="' + restUrl + '" ';
var yqlFormat = 'format=json'
var jQueryCallback = '?'
var fullQueryUrl = yqlBaseUrl + yqlQuery + '&' + yqlFormat + '&' + jQueryCallback;
$.getJSON(fullQueryUrl, function(json) {
var jsonString = JSON.stringify(json.query.results.json.json, null, ' ')
$('body').append('<h1>Response</h1><pre>' + jsonString)
}) ​
If you can control the content of "user.json", wrap it around a function:
user.json content:
execute_jsonp({you_json)
your javascript:
$(document).ready(function(){
$.ajax({
url: 'http://50.116.19.49/rest/user.json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 50000,
success: function(data, status){
data(); //execute the function that is sent
},
error: function(){
output.text('There was an error loading the data.');
}
});
function execute_jsonp(json){ //recreate the function so you may access the json as a parameter
alert(json);
}
});
Hope this helps ;)

Cross site HTTP authentication in JQuery

I want to see if it is possible to log into a third site that uses HTTP authentication. Ideally, the browser will store the credentials. Unfortunately this fails every time. Any help would be much appreciated, I'm using the base64 Jquery plugin, which I've tested to work.
So, two questions:
How can I view the HTTP status code?
Will this ultimately work, in principle?
<script>
$("#login_button").click(function() {
var username = 'myFunUsername';
var password = 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + $.base64.encode(username + ":" + password));
},
success: function(data) { $("#label").text("Logged in, yay!"); }
}).fail(function(){ $("#label").text("It didn't work"); });
});
Thanks!!
var user= 'myFunUsername';
var pwd= 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
crossDomain:true,
username :user,// Keep the variable name different from parameter name to avoid confusion
password:pwd,
xhrFields: { /* YOUR XHR PARAMETERS HERE */}
beforeSend: function(xhr) {
// Set your headers
},
success: function(data, textStatus, xhr) {
alert(xhr.status);// The status code
//Code for success
}
}).fail(function(){
//Fail code here
});
For more details on parameters refer to http://api.jquery.com/jQuery.ajax/

Categories