I am trying to get a cross-domain JSON data via $.ajax method
$.ajax({
type: "GET",
dataType: 'jsonp',
url: "http://nrb.org.np/exportForexJSON.php?YY=2016&MM=06",
crossDomain : true,
})
.done(function( data ) {
console.log("done");
console.log(data);
})
.fail( function(xhr, textStatus, errorThrown) {
console.log(xhr);
console.log(xhr.responseText);
// alert(xhr.responseText);
// alert(textStatus);
});
The JSON returned by the url is
{
"Conversion": {
"Currency": [{
"Date": "2016-06-23",
"BaseCurrency": "INR",
"TargetCurrency": "NPR",
"BaseValue": "100",
"TargetBuy": "160.00",
"TargetSell": "160.15"
}, {
"Date": "2016-06-23",
"BaseCurrency": "USD",
"TargetCurrency": "NPR",
"BaseValue": "1",
"TargetBuy": "107.76",
"TargetSell": "108.36"
}, {
"Date": "2016-06-23",
"BaseCurrency": "BHD",
"TargetCurrency": "NPR",
"BaseValue": "1",
"TargetBuy": "285.75",
"TargetSell": "N/A"
}]
}
}
I checked if the JSON is valid by using http://jsonlint.com/. The JSON is Okay. I get a console error.
Uncaught SyntaxError: Unexpected token :
The console is pointing to the error in the following screenshot
Try changing dataType to "json"
Responses with javascript content-type are evaluated automatically.
JavaScript JSON parser treats { and } as a block instead of object.
Set correct Content-Type header for the JSON file.
OR save it with .json extension.
Your url has .json extension while header is jsonp
, Try making it same
Not quite sure of POST and JSONP
: Post data to JsonP
Related
I am working on a Java application using Struts 1.2. I am facing a blocking error when I make an AJAX call to a Struts action.
The struts action, getInfos.html, is called successfully but after that when I make the AJAX call I get the following error in the console:
Invalid Character/parsing error
The data variable is a correct JSON format. Why would it trigger this error?
I've gone through all the similar questions online but I don't know why it's triggering an invalid character error.
$.ajax({
type: "POST",
url: "getInfos.html",
dataType: "json",
async: false,
cache: false,
data: {
Code: "code1",
type: "type",
mand: "mand",
signature: "signature"
},
success: function(data) {
console.log('succes');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
In the execute method that is handling the ajax request, i am calling the attributes using the request
final String code = (String) request.getAttribute("code");
final String signature = (String) request.getAttribute("signature");
final String type= (String) request.getAttribute("type");
/*
Making a call to a webservice using the attributes bellow,
using **response** Object
*/
if (reponse != null &&
(CodeReponseHttp.OK.equals(reponse.getCodeReponse()))) {
jsonObj.put(SUCCESS_CALL, true);
} else {
jsonObj.put(SUCCESS_CALL, false);
}
return new JsonResult(jsonObj);
But they are set to null; which means that the ajax data is not passed into the request, when I debug the execute method and I explicitly set values to these attributes everything works fine.
new JsonResult(jsonObj) is a generic class with a constructor that accepts a JSONObject
Like Rory McCrossan Comment it could be the response you got is not a json and your code expect a json response
When i comment dataType param it work fine
$.ajax({
type : "POST",
url : "getInfos.html",
//dataType : "json",
async: false,
cache: false,
data: JSON.stringify({
Code : "code1",
type : "type",
mand : "mand",
signature : "signature"}),
success : function(data){
console.log('succes');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
The problem had been solved, after debugging, the response type was not a JSON since there is a redirection to an error page if an exception is thrown, the exception was thrown because the data attributes were null, and it turned out that they are parametres not attributes, so getting the parameters solved the problem.
request.getParameter("code");
thank you all for your collaboration.
I have Java REST API generated using swagger, in that if client is unauthorized then then i am sending custom error messages in response
public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, String authBase64String) throws NotFoundException {
// do some magic!
ErrorRequestObject erb;
ArrayList <ErrorRequestObject> erbs = new ArrayList<ErrorRequestObject>();
if (authBase64String == null)
{
erb = new ErrorRequestObject(); erb.setError("Missing Authorization in Header"); erb.setPath("Header:Authorization");
erb.setProposedSolution("Authorization Header should contain user:pwd:nhPath as Base64 string");
erbs.add(erb);
}
if (erbs.size() == 0)
{
//success code here
}
else
{
return Response.status(400).entity(erbs).build();
}
}
I call this API using ajax as follows,
$.ajax({
url : URL,
type : "DELETE",
dataType : "json",
contentType : "application/json",
async : false,
success : function(result){
Response.resolve(result);
console.log("Response : " + JSON.stringify(result));
}
});
now when i call this API with ajax call it without authorization in header it gives me 400 status that is fine as expected but how do i get error object created with java ? can anyone please tell me how do i get this error object at javascript client ?
Something like this:
$.ajax({
url : URL,
type : "DELETE",
dataType : "json",
contentType : "application/json",
async : false,
success : function(result){
Response.resolve(result);
console.log("Response : " + JSON.stringify(result));
},
error: function(err) { /* your code here*/})
});
You can use the error function like
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
Where,
The jqXHRobject, textStatus - a string describing the type of error that occurred and an optional exception object as errorThrown, if one occurred. So, you can manipulate the statusCode and everything from this parameters like,
jqXHR.status == 400
So I can easily pass data to my table when the JSON data is read from a .txt file.
However, when I use ajax to hit an endpoint and return data, I get errors. Can anybody see what's wrong?
var table;
$.ajax({
url: '../forms/test/get_data',
type: 'GET',
dataType: 'json'
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function(data) {
console.log(data); // This comes back correctly and in the same format as the txt file.
table = $('#feeds').DataTable( {
//"ajax": "/javascripts/test/ajax/data/object.txt",
"ajax" : function(dataa, callback, settings) {
callback(data)
},
"scrollX" : true,
"data" : data,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "id" },
{ "data": "status" }
]});
});
I get "Uncaught TypeError: Cannot read property 'row' of undefined
at n.fn.init.createdRow (eval at (jquery-1.12.0.min.js:2), :63:45)" as an error in my console.
User to JSON.parse() method for convert string data to object data like
: "data" : JSON.parse(data),
try above Code..
I'm attempting to retrieve data from my Pocket account using the Pocket API by accessing it with a jQuery post function. I have obtained the consumer key and access token and when I execute the following code I get a parseerror ...but the data shows up in JSON format in Firebug.
var myPost = $.post("https://getpocket.com/v3/get",
{ "consumer_key": "<<consumer key here>>",
"access_token": "<<access token here>>",
"count": "3",
"detailType": "simple"
},function(data) {
return data
},
"jsonp");
myPost.done(function( msg ) {
console.log(myPost)
alert(msg);
});
myPost.fail(function( jqXHR, textStatus ) {
console.log(jqXHR)
alert( "Request failed: " + textStatus );
});
If I change the dataType on the post call from "jsonp" to "json" I don't get the parse error but instead get a generic error (literally just "error") with nothing returned in teh response tab in Firebug.
Attempts to do this call using jQuery.ajax() have also failed, yielding an error 400.
var something = $.ajax({
"accepts": 'application/json',
"type": 'POST',
"url": "https://getpocket.com/v3/get",
"contentType": 'application/json; charset=UTF8',
"data": {"consumer_key": "<<insert consumer key here>>",
"access_token": "<<insert access token here>>",
"count": "3",
"detailType": "simple"},
"dataType": 'json',
"success": ""
});
Seems like I am close using $.post() but how to I clear that error so I can get the actual response data returned?
I am baffled by this for very long now. I want to gain this precious knowledge of making JSON call properly. Help me Humans.
So I'm making a call exactly like this:
$.ajax({
type : "POST",
url : "http://quote.mythicalQuotes.com/unicorn/service/historical/json?callback=callme&symbols=APPL",
dataType: "text",
cache : false,
data : My_Array,
error : function(request,error){alert(request+" "+error); },
success : function(data)
{
alert("Response" + data);
}//success
}).fail(function(textStatus, errorThrown) { alert("error Error");
console.log("The following error occured: "+ textStatus, errorThrown); });
But it fails and throws 'error' alert. Good Coding!
Now pasting "http://quote.mythicalQuotes.com/unicorn/service/historical/chart/lite/json?callback=callme&symbols=APPL" on my browser URL gives me nice JSON of format:
callme(
{
"SYMB" : [
{
"DESCRIPTION" : "APPL,
"BARS" : {
"CB" :[
{
"lt" : "09-01-2011::20:00:00",
"op" : "16.31",
"cl" : "15.22",
"hi" : "16.45",
"lo" : "14.72",
"v" : "17768019"
},
{
"lt" : "09-02-2011::20:00:00",
"op" : "15.22",
"cl" : "14.22",
"hi" : "19.45",
"lo" : "10.72",
"v" : "17768000"
}
]
}
]
})
So what atrocity am I doing here which is provoking my anger toward this particular Javascript semantics/syntactics?
Couple of reasons I thought which might cause this.
1. Same origin policy.
2. Wrong JSON format being return.
3. Stupidity of my code.
Please help.
This is a JSONP-type response. Add dataType: jsonp to the JQuery AJAX request. Since you're also specifying the callback function explicitly, add jsonpCallback: callme also. See the JQuery docs for more info (scroll down to the "dataType" section).
$.ajax({
dataType: "jsonp",
jsonpCallback: "callme",
// ...
success: function(data) {
alert(data); // should show the JSON: { "SYMB" : ... }
}
});
You mentioned the cross-domain policy; the JSONP spec is a workaround for this policy blocking cross-domain requests. The idea is that, rather than returning data, the server returns a Javascript snippet containing data. The client then executes the returned function to retrieve the data. The JQuery ajax method has built-in functionality to handle all this "behind the scenes".