Problems Reading json data return to jQuery - javascript

I have some json return data, I am unable to access any of the data within the JSON, I have used this method before and it works, but I can't seem to figure out what is going wrong here.
the data["json"] will print out the json data but data["default"] or data.default will not print out the individual information within the json data.
JSON: {"default":"y","mqdefault":"y","hqdefault":"y","sddefault":"y","maxresdefault":"y"}
the jquery is:
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(data) {
$(".the-return").html(
"default: " + data["default"] + "<br />mqdefault: " + data["mqdefault"] + "<br />hqdefault: " + data["hqdefault"] + "<br />JSON: " + data["json"]
);
//alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});

Well i had run into a similar type of situation where i was getting a json data in the response from my server that i was able to print in log, but i was not able to access its variables.
Later i found out that this was because the data that was being received in the callback success function was not actually a json value. You might need to check if it is actually a json or else you can parse it to a json.
Possibly your data is not a proper json format due to which you are not able to access data["default"]

Related

Ajax get function with endpoints

I have an endpoint on the server:
app.get('/A/:A_Id/B/:B_Id/C?', callbackFunction);
After I type "http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00" the server responds with data in callbackFunction, I can see the data in address http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00 (the startTimeUtc and endTimeUtc can change depending on the user inputs),
but I am not able to get data with an ajax get function:
$.ajax({
type: 'GET',
url: '/A/:A_ID/B/:B_ID/C?', success: function(result){
// result is NaN
}
What should be the correct endpoint in this case?
First off, you're not actually providing any data to the ajax call.
API_URL = "http://xx.xx.xx.xx:3000/A/" + A_ID + "/B/" + B_ID + "/C"
$.ajax({
type:'GET', //mostly here for readability; is default for ajax
url:API_URL,
data:{
startTimeUtc:user_input_for_start_time
endTimeUtc:user_input_for_end_time
}
}).done(function(result){
console.log(result);
}).always(function(result, status){
console.log(result);
console.log(status);
});
Not sure whether the always will help you at all, but thought it might be worth a shot. You also need to include the full URL. As a wikipedia api example, it'd be : "https://en.wikipedia.org/w/api.php". i.e. you just need to go to the ?, and then the ? is optional for GET calls (regardless of whether or not the type is supplied, see jQuery ajax documentation).
An alternative approach is pasting the entire URL:
url:API_URL + "?startTimeUtc=03:00:00&endTimeUtc=05:00:00". I personally prefer using data, but it's totally up to you.
You can do something like:
var url = "http://xx.xx.xx.xx:3000/A/" + A_ID + "/B/" + B_ID + "/C?startTimeUtc=" + startTime + "&endTimeUtc=" + endTime;
$.get( url, function( data ) {
console.log(data);
});
Where A_ID, B_ID, startTime and endTime are the variables containing the respective values.

How to get URL of Facebook Post made using Graph API?

I have been able to successfully post a status update with image to Facebook using the graph API via an AJAX call. Now I would like to get the URL of the post, and redirect the user to the post as soon as it has been made, but I can't figure out how to get the URL. I thought the URL would be included in the response success data object, but I have tried iterating through it, and all I got was seemingly random numbers. Does anyone know how I can get the URL of the post and send the user there? Thanks. Here is my code below:
$.ajax({
url:"https://graph.facebook.com/" + userID + "/photos?access_token=" + accessToken,
type:"POST",
data:fd,
processData:false,
contentType:false,
cache:false,
success:function(data){
console.log("success " + data);
for (var key in data) {
if (data.hasOwnProperty(key)) {
var obj = data[key];
for (var prop in obj) {
// important check that this is objects own property
// not from prototype prop inherited
if(obj.hasOwnProperty(prop)){
console.log(prop + " = " + obj[prop]);
}
}
}
}
},
error:function(shr,status,data){
console.log("error " + data + " Status " + shr.status);
},
complete:function(){
console.log("Ajax Complete");
}
});

jQuery AJAX POST Send Variable

I have the following code:
var result = confirm("You want to Subscribe to our Newsletter?");
var emailAddress = $("#subscribeEmail").val();
if (result == true) {
$.ajax({
type: 'POST',
url: '/php/subscribeNewsletter.php',
data: '{"email": "' + emailAddress + '"}',
complete: function(r){
alert(r.responseText);
}
});
}
I believe the problem is to do with:
data: '{"email": "' + emailAddress + '"}',
I am receiving an empty $_POST array on the server side of things.
Pass an object literal, not a string:
data: {email: emailAddress },
jQuery will transform the object into the URL encoded key/value pairs, which will be picked up in the $_POST array on the PHP side.
Your current code is actually sending a JSON string as the raw POST data. jQuery is seeing the data type is a string, and so it doesn't do any processing, so you'd have to access the raw POST data on the PHP side and do a JSON decode to get it.
yes problem is: data: '{"email": "' + emailAddress + '"}', it should be object:
...
data: {"email": emailAddress},
...
provide the data attribute in the ajax call as a json object instead of string.
like
data: {"email": emailAddress },
You can use like below
$.get('/Presentation/AjaxData/History.aspx', { itemID: itemid }, function (data) {
$('.history-listing-tabs>.tab-item').html(data);
});
Try this format
data: {email: emailAddress}
Better pass data to a variable and use it while sending,
var temp = 'email:' + emailAddress;
...
data: temp;
.....

Returning JSON from an Ajax GET call - receiving an Undefined error on all but the first record in the JSON object

Here's my client side code:
$.ajax({
url: 'http://localhost/App.WebAPI/api/Messages/AppName',
type: 'GET',
dataType: 'json',
crossDomain: true,
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
function WriteResponse(messages) {
var strResult = "<table><th>AppId</th><th>Message</th>";
$.each(messages, function (index, message) {
strResult += "<tr><td>" + message.AppId + "</td><td> " + message.Message + "</td></tr>";
});
strResult += "</table>";
$("#divResult").html(strResult);
}
The URL in the Ajax call returns 3 records, but when they are output to the browser via "WriteResponse", here's what I get (blurred out to protect company information):
Is my .each method not formed correctly? I am not an expert in jQuery, so I wouldn't be surprised if I goofed up something simple. Notice that it does see all 3 records but it outputs "Undefined" in the 2nd and 3rd records... any ideas why??
The problem was that I had a foreign key relationship defined in my table (MSSQL) - I am using Entity Framework - and so when the JSON was returned by the WebAPI, the foreign key was included in the JSON, as expected, but for some reason it made the JSON look all funky. I removed all relationships in my table, ran the API call again, and now I am getting all my records back.
But I know that just works around the issue of having foreign keys, which I will investigate further.

JSON Request appended with [object%20Object] in jQuery

I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.

Categories

Resources