how to get correct JSON object from flickr API - javascript

I used flickr photo search method to retrieve public photos.
when I run it with jquery, it works fine, I get the json object in correct form.
{
"photos": {
"photo": [
{
.........
}
]
},
"stat": "ok"
}
But when I use it with AngularJs, I got the same object with a prefix jsonFlickrApi
jsonFlickrApi({
"photos": {
"photo": [
{
......
}
]
},
"stat": "ok"
})
what I used in AngularJs is:
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.flickrPhotoSearch = function() {
return $http({
method: 'GET',
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=3f807259749363aaa29c2fa93945&tags=india&format=json&callback=?',
dataType: 'json'
});
}
});
Please tell me how can I convert the second JSON to the first one.
Is there anything I can do in $http call or have to alter JSON object.

There was problem in the url.
This Url works for me.
https://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=3f807259749363aaa29c712fa93945&user_id=61495424#N00&format=json&nojsoncallback=?

You have to add nojsoncallback=1 to the url, like this
https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=XXX&format=json&nojsoncallback=1
And that remove the jsonFlickrApi function on response.

The above answer which says to add nojsoncallback=1 is correct, but I'd like to provide more context and reasoning behind it.
If you take a look at the documentation (which is poorly formatted in my opinion): https://www.flickr.com/services/api/response.json.html and scroll all the way to the bottom you will find, tucked away:
Callback Function
If you just want the raw JSON, with no function wrapper, add the parameter nojsoncallback with a value of 1 to your request.
To define your own callback function name, add the parameter jsoncallback with your desired name as the value.
nojsoncallback=1 -> {...}
jsoncallback=wooYay -> wooYay({...});
The key part being: If you just want the raw JSON, with no function wrapper, add the parameter nojsoncallback with a value of 1 to your request
Therefore, add this to your request and it will remove jsonFlickrAPI wrapper that you are seeing in your response: nojsoncallback=1

You are getting a JSONP response (notice the P) which is basically a function call with an argument that is the response you are expecting.
Easy solution for you: Create a function named jsonFlickrApi with a parameter response and you can do your handing in there.
At this point, I am not sure if you can define your function inside your service but try it. If not, you can define it outside.
Alternatively, try using $http.get function instead. Were you specifying the return accepted by the client in your jQuery original code?
EDIT
Try this setting the data type of the request using $http or $http.get without forgetting to specify the data property in the settings object.
$http({
url: 'http://localhost:8080/example/teste',
dataType: 'json',
method: 'POST',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
$scope.response = response;
}).error(function(error){
$scope.error = error;
});

Related

"no element found" error when using JSON stringify method in jQuery ajax call

I want to update a section of a page using ajax when an image is clicked. When the image is clicked I pull values from a jQuery DataTable to populate an object. Then I call my action and pass in a JSON string of the object using JSON.stringify().
$("#image").click(function(e) {
data = {}
table = $("#myTable").dataTable();
$.each(table.fnGetData(), function(index, value) {
row = $(table.fnSettings().aoData[index].nTr);
data[row.find(".key")] = {
"val1": row.find(".val1").text(),
"val2": row.find(".val2").text(),
"val3": row.find(".val3").text(),
"val4": row.find(".val4").text(),
}
});
$.ajax({
url: "myAction",
contentType: "text/html",
data: {
json: JSON.stringify(data)
},
success: function(resp) {
alert(resp)
$("#myDiv").html(resp);
}
});
});
However, calling the ajax function results in an error in the javascript console that only says "no element found". When I check the network activity it tries to hit the correct url, but returns a 400 error.
I am sparing the back end details because I believe something in the stringify method to be the culprit here because when I pass a string literal as the ajax data such as data: {json: "foo"} it calls my action with no problem whatsoever.
The solution was to specify the ajax method as POST by adding the following attribute to the ajax call.
method: "POST"
No idea why this makes it work, but it does.

Jquery ajax success, not working no return data

I really need your help.
I got this problem in my jQuery, i try to make a ajax call to a Javascript there keep an array inside in this file.
test-ajax.js
var data = ["kategori", "Alarm"];
return data;
But it come not with an array or anything not a single error.
Here is the ajax call.
$(document).ready(function() {
$(".tip").mouseover( function() {
$.ajax({
url: "http://localhost:8080/kraftvaerk/falck/FalckAlarmWeb/FalckAlarmWeb.Website/js/test-ajax.js",
dataType: "javascript",
succes: function(resultat) {
console.log("here");
$(".tip").append("<span>Katagori: " + resultat[0] + " <br /> Beskrivelse: "+ resultat[1] +"</span>");
}
});
});
});
In Html i got a table inside that table is there an a tag with class tip.
When the user mouse over that tag it should make the ajax call.
WARNING.
I use jQuery 1.2.2 the customer site i canĀ“t upgrade it
Json is not ALLOW on thit project.
You don't need to define and return a variable in your test-ajax.js file. You can simply define it as follows:
["kategori", "Alarm"]
Also, you had an extra bracket on the end that was invalid syntax.
The method you are using is more similar to jsonp. jsonp works by including a script tag on your page that points to a js script that executes a function containing the data.
For example, your test-ajax.js would be:
testajax(["kategori", "Alarm"]);
and to request it, simply do this:
window.testajax = function(data) {
console.log(data[0],data[1]);
};
$.getScript("test-ajax.js");
There you go. you just performed your first JSONP request, and it didn't involve any "json".
i try to do the same like you but from $.ajax it is not returning the result but if you use the below example then you will get the result but your file should like this :
JScript1.js ["kategori", "Alarm"]
JScript1.json ["kategori", "Alarm"]
1. $.getJSON("JScript1.js", function (data) {
console.log(data);
});
2. $.getJSON("JScript1.json", function (data) {
console.log(data);
});
result:
Array[2]
0: "kategori"
1: "Alarm"
length: 2

Filter JSON response on a jQuery ajax request, for XSS text

I am falling into a silly issue where the server is giving JSON response with XSS safe text added.
The server gives only 2 kinds of response:
HTML page with hidden input field that contains the value I want
JSON String with the value which can be preferably converted to JS
Object.
The problem is, for preventing JavaScript XSS attacks, the JSON response is made like this:
while(1);{
"name": {
"abc": "123",
...
}
}
So this goes to parseerror in jQuery ajax method and therefore in the error callback.
How do I fix this?
Also, I tried putting a hook in the error function and change the JSON data:
error: function(jqXHR) {
removeJSCode (jqXHR.responseText);
}
// ...
function removeJSCode(json) {
.. Code to filter the response
}
But this does not work.
jQuery's $.ajax has dataFilter property in its configuration. Pass it a function and it runs after jQuery receives ajax data, but before jQuery has a chance to touch it.
The function is provided the string response as first argument and data type as second argument. The second argument will depend if you passed dataType in the configuration.
There, you can use .replace('while(1);','') and return the string from the function for jQuery to parse.
$.ajax({
...
dataType : 'json',
dataFilter : function(response,type){
//if not JSON, don't do anything with it
if(type !== 'json') return response;
//otherwise, replace and return
return response.replace('while(1);','');
}
...
});

JQuery Ajax POST throwing an empty error without making the request

I have a function that makes an Ajax request for any anchor. The request method can be GET or POST. In this case, I want to make a POST without using a form but the Ajax request throws an error before even sending the request. The error has the value "error" and all error/failure description variables are "".
function loadPage(url,elem_id,method,data) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: data,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
When the function is called the params are these (copied from the js console):
data: "partial=yes"
elem_id: "page"
method: "post"
url: "/projects/2/follow"
As asked, here is the code that calls the loadPage function.
$("body").on("click","a.ajax",function(event) {
var _elem = getDataElem($(this));
var _method = getRequestMethod($(this));
var _partial = getRequestPartial($(this));
handlers.do_request(event,$(this).attr("href"),_elem, _method, _partial);
});
var handlers = (function() {
var obj = {};
obj.do_request = function(event,url,elem_id,method,data) {
event.preventDefault();
loadPage(url,elem_id,method,data);
history.pushState({selector:elem_id,method:method,data:data},null,url);
};
}());
After the failure of the Ajax request, the request is made by default and it responds sucesss. In all I have read, this seems to be a valid way to make a POST request (that doesn't need a form).
Am I doing something wrong in the function? Why is the error information empty?
Thanks
EDIT:
I have been thinking, for a POST from a "form" that function works, when the variable "data" is made with the serialize function (e.g. "var data = $(this).serialize();"). Could it be that the format of the "data" when I make a POST without a "form" is wrong in someway? Maybe the JQuery Ajax function doesn't accept a simple string like "partial=yes" as data when a POST is made. Any thoughts on this?
I just experienced this problem and after an hour or two, thought to try setting cache to false. That fixed it for me.
$.ajax({
url: url,
cache: false,
type: method
});
Unfortunately, when I removed cache again, my request was working as if it had never had a problem. It seems as if setting cache:false made something 'click'.
Oh well.
Just a guess, but in the docs the type parameter is in all caps, i.e. 'POST' and not 'post'.
Try:
function loadPage(url,elem_id,method,dat) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: dat,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
I'm wondering if you are running into a problem using a variable named after a keyword. If this doesn't work, try calling loadPage with no arguments and hard coding all of your ajax parameters, just to see if that works.
Could not solve the problem, neither could find the reason why it was happening. Although, I found a way around, by using a hidden empty form instead of an anchor with the method 'POST'. For a form, the function worked nicely.
Thanks for the answers

Having problems with jQuery, ajax and jsonp

I am using jsonp and ajax to query a web-service written in java on another server. I am using the following jquery command:
$.ajax({
type: "GET",
url: wsUrl,
data: {},
dataType: "jsonp",
complete: sites_return,
crossDomain: true,
jsonpCallback: "sites_return"
});
function jsonp_callback(data) {
console.log(data);
}
function sites_return(data) {
console.log(data);
}
So my problem is that after the query finishes a function called jsonp_callback is called. Where I can clearly see the json formatted string:
{"listEntries":["ELEM1", "ELEM2", "ELEM3", etc...]}
But after the function sites_return is called when the complete event fires, I get the the following:
Object { readyState=4, status=200, statusText="parsererror"}
Also for reference the jsonp_callback function is called before the sites_return function. Also if i take the jsonp_callback function out of the code, I get a complaint it firebug that the function is not implemented.
My question three fold:
1) What am i doing wrong on the jquery side?
2) Why does the json get parsed correctly in jsonp_callback but not sites_return?
3) What can i do to fix these issues?
EDIT
Some new development. Per the comments here is some additional information.
The following is what comes out of the http response
jsonp_callback({"listEntries":["ELEM1", "ELEM2", "ELEM3"]})
I assume this is the reason jsonp_callback is being called. I guess my question now becomes, is there any way to control this (assuming i don't have access to the back end web-service).
Hope this helps~
var url = "http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";
var address = "1600+Amphitheatre+Parkway";
var apiKey = "+Mountain+View,+CA";
$.getJSON("http://maps.google.com/maps/geo?q="+ address+"&key="+apiKey+"&sensor=false&output=json&callback=?",
function(data, textStatus){
console.log(data);
});
I believe that the first argument to the sites_return function would be the jqXHR Object. Instead of complete try using success.
But still this may not work as it seems that there is a parsing error (mentioned in the return value of sites_return function called from oncomplete). Therefore, you would first need to check your json string.
To Validate JSON, you can use http://jsonlint.com/
I think that the problem is that your server is not behaving the way jQuery expects it to. The JSONP "protocol" is not very stable, but generally what's supposed to happen is that the site should look for the "callback" parameter and use that as the function name when it builds the JSONP response. It looks as if your server always uses the function name "jsonp_callback".
It might work to tell jQuery that your callback is "jsonp_callback" directly:
$.ajax({
type: "GET",
url: wsUrl,
data: {},
dataType: "jsonp",
complete: sites_return,
crossDomain: true,
jsonpCallback: "jsonp_callback"
});
Not 100% sure however.
If you don't have the ability to change the JSONP function wrapper that the remote server returns, jQuery's $.ajax() may be overkill here. Ultimately, all you're doing is injecting a script reference to wsUrl, which makes a call to jsonp_callback with a JavaScript object literal as its input parameter.
You could just as easily do something like this and avoid the confusion around the callback naming/syntax:
$.getScript(wsUrl);
function jsonp_callback(response) {
// Access the array here via response.listEntries
}

Categories