jquery ajax function with json - javascript

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 ;)

Related

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

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.

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 not working as expected

I Have to do a cross-domain request and fetch content from a url using $.ajax function.
But the below code only displays the first alert i.e alert(myUrl),
After that the execution stops.The second alert is not displayed. I don't know what is wrong with the code i have written.
Can somebody tell me what i am doing wrong here?Thanks in advance.
function getContentFromUrl(){
var myUrl="http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" +
encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
success: function () {
alert("***********"+data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function() {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
});
}
Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.
You can't use regular JSON for cross-domain requests because of the same-origin policy. Instead, you'll need to use JSONP. In jQuery, you can do so like this:
$.ajax({
dataType: 'jsonp',
crossDomain: true
// other info
});
Note that there are security issues involved with JSONP. Only use JSONP if you trust the host domain.
I assume this is jQuery?
Try the following:
url = "http://query.yahooapis.com/v1/public/yql?" +"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?";
getContentFromURL(url);
function getContentFromURL(url)
{
$.get(url, function (data) {
console.log(data);
});
}
If it dumps out to the console a response, you can build from there.
The data here is not defined
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
and you forget to add a param for the callback function
success: function (data) {
....
}
The finally code should like this
function getContentFromUrl() {
var myUrl = "http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: {},
success: function (data) {
alert("***********" + data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function () { document.getElementById("displayerrors").innerHTML = "Could not load the page."; }
});
}

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