$.ajax('http://blog.yahoo.com/#apac3/ajax/getComment?ugcId=68197&commentCount=30&ownerGuid=IQDTYHIWBYN4PPB6DXQWU7JWN4&page=2&type=blog&.crumb=UxHpRaVVUMo&jsoncallback=?', {
type: "GET",
crossDomain:true,
async: false,
dataType: "jsonp",
success: function(comment){
alert("myObject is " + comment.toSource());
}
});
I can see some callback is in chrome's console, however, there is some errors that making success event cannot function normally.
Does anyone know how to obtain the values in the callback?
Your biggest issue is that comment is probably not an instance of a class but is either a string or is a basic JSON object. Unless you have some library which will change the way that Strings or JSON work by modifying the prototypes.
Related
Due to the (my perceived) nature of the $.ajax GET I'm not sure what I'm looking for is possible in this method, but thought I should ask as it's causing me some trouble. I am in no way an expert on JS, apologies if this is obvious, the title is poor, couldn't think of a different way to say it.
What I'm doing - using $.ajax to get values from the back-end API functions (these work). In the success property I'm using an anonymous function to pass more data across that would not otherwise be brought back. When stepping through the console breakpoints in the Chrome console the success function is often skipped as it's not brought back quick enough.
What I would like - in the example below, I don't want getStuff to complete, before its success DoSomething has returned, as I'm missing loads of data from the API which I need to pass through to DoSomething - is this possible to achieve?
Example
function getStuff(id, hid) {
$.ajax({
type: "GET",
url: "/api/GetMyStuff/" + id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (vData) {
DoSomething(vData, id, hid); // not always being hit
}
});
}
You could use the async option and set it to false to get a synchronous call:
function getStuff(id, hid) {
$.ajax({
type: "GET",
url: "/api/GetMyStuff/" + id,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // HERE
success: function (vData) {
DoSomething(vData, id, hid); // not always being hit
}
});
}
But that is not a good way to do ajax request, you should rethink your code organization (like giving a callback function to your getStuff method and calling it in the success callback).
What you are trying to do is impossible. Asynchronicity is "leaky", meaning that any asynchronous action requiring a callback (e.g., $.ajax()) necessarily forces asynchronous control flow all the way up the call chain.
Please note that in the near future (thanks to async/await in ES7), this situation gets a little better. The asynchronicity is still leaky, but the new keywords make the refactoring scenario a little easier than hand-jamming callbacks everywhere.
i am trying to take the responseJSON from an AJAX call and just extract one element to the variable formDigestValue. I have tried about a dozen ways of trying to return the response, using JSON.parse(), $.parseJSON() and some others, but there are 2 main issues that i cant seem to figure out. I put in a check for if (data.lenght > 0){do something}, response.length, responseJSON, jqXHR, XHR, i cant seem to find the variable that holds the data that would end up sent to success function. I've tried just setting the ajax call to a variable (var y = $.ajax()...) and manipulating it that way.
I just keep reading different articles and trying different ways, but nothing seems to quite get it right and it seems to be fairly simple, but i feel like im just missing something simple on this.
$(document).ready(function () {
var siteURL = "xxx";
var formDigestValue = "";
jQuery.ajax({
url: siteURL + "/_api/contextinfo",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function(){
contextHeaders = $.parseJSON(responseJSON);
formDigestValue = contextHeaders.FormDigestValue;
}
});
...
any advice would be greatly appreciated. For reference, the JSON returned looks like the below. i am trying to figure out if i also need anything extra to get at child nodes, as it looks like it comes back buried a bit (i broke it out with indents just to show the depth):
{
"d":
{
"GetContextWebInformation":
{
"__metadata":
{
"type":"SP.ContextWebInformation"
},
"FormDigestTimeoutSeconds":1800,
"FormDigestValue":"0xADC9732A0652EF933F4dfg1EF9C1B75131456123492CFFB91233261B46F58FD40FF980C475529B663CC654629826ECBACA761558591785D7BA7F3B8C62E2CB72,26 Jun 2015 21:20:10 -0000",
"LibraryVersion":"15.0.4631.1000",
"SiteFullUrl":"http://example.com/",
"SupportedSchemaVersions":
{
"__metadata":
{
"type":"Collection(Edm.String)"
},
"results":["14.0.0.0","15.0.0.0"]
},
"WebFullUrl":"http://www.example.cm"
}
}
}
edit 6/27
Alright, I think between the comment on accessing the child nodes and the rest on passing the argument to success function, ive almost go it. My main thing is, I cannot seem to pass it as an argument. I tried to say it initially, but dont think I write the explanation properly. I tried:
Success: function(responseJSON)...
As well as
Success: function(data)...
But the data never seems to actually enter the function, its null values. I know the json returned, but having issues passing it into success function
Here is a look at firebug when this runs:
Try to add dataType option with json value and don't forget the callback success function take at least one parameter which is the data returned by the server.
jQuery.ajax({
url: siteURL + "/_api/contextinfo",
type: "POST",
dataType: 'json',
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function(data){
console.log(data);
}
});
Posting from my iPhone, so, it's hard. From the first look, you're not capturing the returned result in success. Try the following.
success: function(responseJSON) {
contextHeaders = $.parseJSON(responseJSON);
if that block of json is what you get returned by $.parseJSON(responseJSON) then you're right, you just need to dig a bit deeper:
contextHeaders = $.parseJSON(responseJSON);
formDigestValue = contextHeaders.d.GetContextWebInformation.FormDigestValue;
hope that helps :)
I am new in the area of jQuery/Ajax and my little test function doesn't work. And my page is also refreshingcan any one help me
<script type="text/javascript" >
$(document).ready(function() {
$("#ser_itm").change(function() {
var id=$(this).val();
var dataString = 'id='+ id;
alert(dataString);
$.ajax({
type: "POST",
url: "bar_pull.php",
data: dataString,
cache: false,
success: function(html) {
$("#tbl").html(html);
}
});
});
});
Pass the function, not the result of the function call:
$('.linkDetails').on('click', getDetailsFromServer);
Apply the same to your AJAX success callback:
success: postToPage
Also, the getDetailsFromServer() function needs to be defined before you bind it to an event. Move the function declaration before your .on('click', ...) call.
So I'm going to try and explain these points more clearly:
You cannot access C:\Users\yah\Desktop\text.txt. This is a server side path, your javascript runs on the client side. So this needs to be a path you can browse to in your browser, something like /pathinURL/text.txt. How you do this is dependant on your hosting technology, etc.
Your call backs are also wrong,
$('.linkDetails').on('click', getDetailsFromServer());
&
success: postToPage()
these will execute the function when they are hit, (well it actually binds the function result) not when the event happens. To make these work you need to remove the braces:
$('.linkDetails').on('click', getDetailsFromServer);
&
success: postToPage
this then hooks up the actual functions as function pointers and thus the actual functions will be fired when you want them to be.
so your final code will look like:
$('.linkDetails').on('click', getDetailsFromServer);
function getDetailsFromServer() {
$.ajax({
type: 'GET',
url: '/someURL/text.txt',
success: postToPage
});
}
function postToPage(data) {
$('.textDetails').text(data);
console.log(data);
}
what Arun P Johny said is right! but your code has another probloem
$('.linkDetails').on('click', getDetailsFromServer);
try above
The same origin policy implemented by browsers prevents local file system urls... if the page and the files are in same folders it might work.
See SOP for file URI for FF
I'm fairly new to JQuery. The code below works and I can see the correct JSON response in Firebug. But I couldn't find a way how to get and parse it in the code. Alert window only shows
"[object Object]" but not any json text.
<script>
$.ajaxSetup({ cache: false });
var _token;
function make_token_auth(user, token) {
var tok = user + ':' + token;
return "Token " + tok;
}
$.ajax
({
type: "GET",
url: "url",
dataType: 'json',
beforeSend: function (xhr){
xhr.setRequestHeader('Auth', make_token_auth('userid', 'token'));
},
success: function (data){
alert(data);
}
});
</script>
The fact you precised
dataType: 'json',
tells jQuery to parse the received answer and give it as a javascript object to your success callback.
So what you have here is fine and what is alerted is correct (this is an object, so
alert simply prints the result of data.toString()).
Use console.log to see what it is exactly :
success: function (data){
console.log(data);
}
and open the developer tools in Chrome or the console in Firebug to browse the properties of the object.
don't use alert() for debugging -- it's often unhelpful (as in this case), and also has serious issues when used with asyncronous code (ie anything Ajax) because it interrupts the program flow.
You would be much better off using the browser's console.log() or console.dir() functions, and seeing the object displayed in the console. It is much more functional, and doesn't interrupt the flow of the program.
So instead of alert(myjsonvar) use console.log(myjsonvar).
You can get the json string by using JSON.stringify
var jsonstr = JSON.stringify(data);
alert(jsonstr);
The alert function expects you to pass in a string or number.
Try doing something like this:
for(x in data) {
alert(x + ': ' + data[x]);
}
Update in response to comments: You can use alert in development or production to see string and number values in the object returned by the server-side code.
However, carefully rereading your question, it looks like what you really want to see is the actual JSON text. Looking at #dystroy's answer above, I think that if you remove the dataType: 'json' from your $.ajax invokation, jQuery will treat the response as plain text instead of automatically converting it to an Object. In this case, you can see the text by passing it to the alert function.
Try using
data = JSON.parse(data)
Then do whatever you want with the data.
Source: JSON.parse() (MDN)
Stuck on the first stage of a big project. I am trying to display the JSON value that I get from URL shown below. It shows the data when I past the URL on the a browser. But when I put the URL in variable and try to show in html it doesn't show the phrased value.(I will delete the app/key one I get the solution.) Thanks in advance.
http://jsfiddle.net/rexonms/6Adbu/
http://api.flickr.com/services/rest/?format=json&method=flickr.photosets.getPhotos&photoset_id=72157629130565949&per_page=10&page=1&api_key=ccc93a20a1bb9060fa09041fa8e19fb5&jsoncallback=?
Have you tried using the $.getJSON() or the $.ajax() method? This seems to return the data just fine:
$.getJSON(apiCall, function(data) {
console.log(data);
});
Here's a working fiddle.
Additional Information
It seems like you may benefit from a simple tutorial that explains AJAX in relation to jQuery's $.getJSON() and $.ajax() methods.
$("<span>").html(apiCall)
apiCall is a string (containing the URL). All you're doing here is setting a span to have the URL as its content. You need to actually use AJAX to load said URL.
$.ajax({
url: 'http://api.flickr.com/services/rest/',
dataType: 'jsonp',
type: 'GET',
data: {
format: 'json',
method: 'flickr.photosets.getPhotos',
photoset_id: '72157629130565949',
per_page: 10,
page: 1,
api_key: 'ccc93a20a1bb9060fa09041fa8e19fb5'
},
jsonp: 'jsoncallback',
success: function(data){
console.log(data);
}
});
Inside success, data is the JSON object returned by the API.