why cant i get the json object out of the url - javascript

I have this url which brings back the yahoo time...im guessing the PST
so i need to get this value with javascript...here is my code
$j.ajax({
type: "GET",
url: "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo&output=json",
dataType: "jsonp",
complete: function(data){
console.log(data);
}
});
but i cant seem to pull out that Timestamp out of the json...what am I doing wrong

You're using the complete method, which returns the XHR object, not the result.
You want success:
$j.ajax({
type: "GET",
url: "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo&output=json",
dataType: "jsonp",
success: function(data){
console.log(data.Response.Timestamp);
}
});
Source: http://api.jquery.com/jQuery.ajax/

I think you want to use the success callback:
$j.ajax({
type: "GET",
url: "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo&output=json",
dataType: "jsonp",
success: function(data,status,xhr){
console.log(data.Result.Timestamp);
}
});​

The JSON looks like {"Result":{"Timestamp":1331089290}}. That is, an object property called Result, which is another object literal containing the property Timestamp:
// Use .success rather than .complete
success: function(data){
console.log(data.Result.Timestamp);
}

javascript:
//change
dataType: "jsonp",
//to
dataType: "json",
Then extract the timestamp with data.Result.Timestamp.
When you use the value, remember that UNIX timestamp is in seconds whilst the javascript Date object works in milliseconds.

Related

Returns error when consuming this php response

Return error in the query
From the browser the answer is correct.
$.ajax({
type: "POST",
url: url,
async: true,
contentType: " charset=utf-8",
dataType: "XMLHttpRequest",
success: function (response) {
console.log(response);
},
error: function (msg) {
console.log(msg);
}
});
The message says "error".
I see three issues. First, dataType is a choice of xml, json, script, or html, unless you did something really fancy. jQuery can guess it based on received data though, so there is normally no need to set it. But if you want to be explicit (assuming your page returns json):
dataType: "json"
Second, contentType value looks like some truncated thing. I would just completely remove it, as you are not sending any data and just requesting a page.
Finally, when you are sending no data and just requesting a resource, the best is to use GET.
All in all:
$.ajax({
type: "GET",
url: url,
async: true,
dataType: "html",
success: function (response) {
console.log(response);
},
error: function (msg) {
console.log(msg);
}
});

Trouble Converting cURL request to Javascript

I don't know what's wrong. I've spent almost an hour reading and re-reading, checking my spelling etc. I was hoping maybe someone can point out what I'm doing wrong.
This is the cURL statement that returns successfully in the terminal:
curl https://api.gumroad.com/v2/products \
-d "access_token=123456abcdef" \
-X GET
The following are some of my attempts that did not work. And yes, I'm certain jQuery has been loaded:
$.ajax({
url: "https://api.gumroad.com/v2/products",
data: "access_token=123456abcdef",
success: function(result){
console.log(result);
}});
And this one:
$.ajax({
url: "https://api.gumroad.com/v2/products",
data: "access_token=123456abcdef",
processData: false,
type: "get",
success: function(result){
console.log(result);
}});
And another one:
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("access_token", "123456abcdef")
}, success: function(data){
alert(data);
//process the JSON data etc
}
})
Looks like you are sending a string instead of a data object, try this:
$.ajax({
url: "https://api.gumroad.com/v2/products",
data: {access_token: "123456abcdef"},
processData: false,
type: "get",
success: function(result) {
console.log(result);
}
});

Jquery - Calling a ajax function within ajax function

Can I use ajax function withing a ajax function.
In my case there are two ajax calls. First ajax will return some data , If it is successful then the second ajax should be called .
Below is my code snippet,
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "my service url here"
dataType = "json",
//success - 1
success: function(data) {
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
$.ajax({
alert('inside ajax-2');
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function(data) {
//some functionality
} //success-2
} //success-1
}); //ajax - 2
}); //ajax - 1
Some more info :
I had checked chrome dev console and the error I am getting is
//success - 1
success: function(data) {
//Error message : Uncaught SyntaxError: Unexpected identifier
That was the error message I got.
And yes I cleared the syntactical mistakes and I was getting the same error message.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "my service url here",
dataType : "json"
//success - 1
success: function(data) {
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
$.ajax({
alert('inside ajax-2');
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function(data) {
//some functionality
} //success-2
} //success-1
}); //ajax - 2
}); //ajax - 1
I checked the service URL in RESTClient extension of firefox browser and again yes , there is Jsondata coming from that service.
Any good suggestion will be highly appreciable
Merry Christmas :)
There are some errors in your scripts.
In the first ajax call, where are the commas to separate the members ?
url:"my service url here",
dataType= "json",
and this should be:
dataType : "json",
Going back to your answer, yes you can but, what if you had the third ajax call?
Your code would be a mess and really hard to read.
The best would be to use promises.
This is the best way to work with asynchronous in javascript (that's also the reason why I've commented your async:false ).
You can read how promises work here.
$.ajax already returns a promise:
var promise = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url:"my service url here",
dataType: "json",
});
which could be chained with another one:
promise.then(function(result){ });
I tend to prefer the approach where I split my ajax call in different function which create a new promise and return it; just in case I want to manipulate the result:
You can split the two ajax calls:
function FirstAjaxCall()
{
var deferred = $.Deferred();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
// async : false,
url:"my service url here",
dataType: "json",
success: function (jsonData) {
deferred.resolve(jsonData);
},
error: function (req, status, error) {
var errorMessage = (error.message) ? error.message : error;
deferred.reject(errorMessage);
}
});
return deferred.promise();
}
and
function SecondAjaxCall()
{
var deferred = $.Deferred();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
// async:false,
url: "my second service URL here",
dataType: "json",
success: function (jsonData) {
deferred.resolve(jsonData);
},
error: function (req, status, error) {
var errorMessage = (error.message) ? error.message : error;
deferred.reject(errorMessage);
}
});
return deferred.promise();
}
Now you could resolve the first one and chain the second one:
FirstAjaxCall()
.then(function(result){
return SecondAjaxCall(result);
})
.then(function(result){
// final result
})
.fail(function(reason){
// reason should contain the error.
});
As you can see FirstAjaxCall() is resolve in the .then() branch and it passes it's result in the anonymous function. Same thing happens with the second ajax call SecondAjaxCall(). If something fails in the first or the second call the errors are trapped here:
.fail(function(reason){
// reason should contain the error.
});
The beauty of promises is you can chain them or execute them in parallel.
Yes you can.
Something wrong in your code that I can see is that }//success-1 is before });//ajax - 2 and it should be after.
also there is a missing coma ( ,) after url:"my service url here",
replace the '=' you have by ':' for your two dataTypes.
your should correct that and try again.
Try something like below in a structured way:
//First method with callback
function myFirstCall(callback) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my service url here",
dataType= "json",
success:function(data){
callback();
});
}
// Second method
function mySecondCall() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my second service url here",
dataType= "json",
success:function(data){
});
}
//Let's trigger it
myFirstCall(function() {
mySecondCall();
});
You have to change "=" after the first "dataType" to ":"
dataType= "json", => dataType : "json",
and move "alert" function to the outside the second $ajax block.
$.ajax({ => alert('inside ajax-2');
alert('inside ajax-2'); $.ajax({
Last, order of closing brackets are opposite.
}//success-1 => });//ajax - 2
});//ajax - 2 }//success-1
The following code should work as you thought.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my service url here"
dataType : "json",
//success - 1
success:function(data){
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
alert('inside ajax-2');
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function (data) {
//some functionality
}//success-2
});//ajax - 2
}//success-1
});//ajax - 1

jquery Post , data object

I try to understand one thing.
I want to post an object with jquery Ajax POST , something like this:
var dataPostYear = {
viewType:GetViewType(),
viewDate:'2009/09/08',
languageId:GetLanguageId()
};
$.ajax({
type: "POST",
url: url,
data: dataPostYear,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnLoadYearListSuccess,
error: OnLoadYearListError
});
and it doesn't work.
But this one works fine:
var dataPostYear = "{viewType:'"+ GetViewType() + "',viewDate:'2009/09/08',languageId:'"+GetLanguageId()+"}";
$.ajax({
type: "POST",
url: url,
data: dataPostYear,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnLoadYearListSuccess,
error: OnLoadYearListError
});
GetViewType() return --'0'
languageId() return --'1'
it's just a string
there is a way to post an object, something what I try to do in my first way ? Or not ?
Thanks
Use jQuery.param(). Here is the documentation
You should look at .postJSON.
Essentially, you just add json as a 4th argument to the $.post
From the site:
// Send the request
$.post('script.php', data, function(response) {
// Do something with the request
}, 'json');
If you want the .ajax call version, you can convert it using the .post docs.

retrieve the data from Json object

I am learning json now.
$.ajax({
async: true,
type: "POST",
url: "get.....values.asp",
data: "vendorId="+vendor,
success: function(json){
alert( "Data retrieved: " + json );
}
});
I am using this ajax call to get the data as json and data is coming as fallowing:
{"rows": [
{"cell":[
104,100,140,"2.99",0.1,1,14,123.55
]
}
]}
How can i retrieve the data from this json object?
can any one give Idea?
thanks in advance.
$.parseJSON(json) will do the work.
Have you tried...
json.rows[0].cell[0]
...etc.?
I also notice you haven't specific the datatype when calling your $.ajax function, e.g.
$.ajax({
async: true,
type: "POST",
url: "get.....values.asp",
data: "vendorId="+vendor,
dataType: 'json',
success: mySuccessHandler
});
Try running it through a for loop in the callback function and assign variables to the bits of information you want to use.

Categories

Resources