I'm trying to fetch the data of a JSONP, but it returns a Syntax error when the function is called. I'm really new to this topic and don't understand why. Probably because I didn't understand everything of JSONP requests. It would be nice if someone could help me out.
Executed code:
$.ajax({
url: "https://backpack.tf/api/IGetMarketPrices/v1?format=json&callback=JSONP&key=XXX&appid=730",
dataType: "jsonp",
data: {format: "json"},
type: "GET",
jsonp: "response",
jsonpCallback: "response",
success: function( response ) {
console.log( response ); // server response
}
});
(I had to censor my API key.)
Error: Uncaught SyntaxError: Unexpected token :
The response is:
{"response":{"success":1,"current_time":1486000891,"items":{"AK-47 | Aquamarine Revenge (Battle-Scarred)":{"last_updated":1485997229,"quantity":80,"value":1092},...
The first : is underlined by Chrome.
Here is the API documentation.
From trial and error - impressive as I have no API key
$.ajax({
url: "https://backpack.tf/api/IGetMarketPrices/v1?format=jsonp&key=XXX&appid=730",
dataType: "jsonp",
type: "GET",
success: function( response ) {
console.log( response ); // server response
}
});
or
$.ajax({
url: "https://backpack.tf/api/IGetMarketPrices/v1",
dataType: "jsonp",
type: "GET",
data: {
format: 'jsonp',
key: 'XXX',
appid: 730
},
success: function( response ) {
console.log( response ); // server response
}
});
To explain... jQuery automatically adds a query parameter called callback on jsonp requests... as the API states that you need to define the callback name in a parameter called callback, you can let jQuery use the default value of callback
Then, jQuery creates a function with a long random name, and sets the value of the callback parameter to that function - so you don't have to worry about the jsonp or jsonpCallback parameters - defaults are good
I must be missing something basic, because this should work!
Related
and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"
I am trying to get a json response from the comicvine api but am getting the following error. comicvine.gamespot.com/:1 Uncaught SyntaxError: Unexpected token :
I see my json result, formatted, in the response body but am getting the console error above.
export function getSeriesFromComicVine() {
const url = "http://comicvine.gamespot.com/api/characters/?api_key=f18c6362ec6d4c0d7b6d550f36478c1cd6c04a49&filter=gender:male,name:hawkeye&format=json&callback=?";
$.ajax({
url: url,
// data: {test: "test"},
type: 'GET',
crossDomain: true,
jsonpCallback: 'callback',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: "myJsonMethod"
success: function (data) {
console.log(data);
}
});
}
You need to set format=jsonp not json
the jsonp callback parameter name needs to be json_callback according to comicvine.gamespot.com - I found this out by going to url https://comicvine.gamespot.com/api/characters/?api_key=[your api key]&filter=gender:male,name:hawkeye&format=jsonp in the browser, and it told me what was missing - very friendly API - the response had an error value
"'jsonp' format requires a 'json_callback' argument"
and no need for callback=? in the url - seeing as jquery adds the callback parameter and it isn't named callback
function getSeriesFromComicVine() {
const url = "https://comicvine.gamespot.com/api/characters/?api_key=[your api key]&filter=gender:male,name:hawkeye&format=jsonp";
$.ajax({
url: url,
type: 'GET',
dataType: 'jsonp',
jsonp: "json_callback",
success: function (data) {
console.log(data);
}
});
}
I make a call with Ajax to an IP with some arguments. Before the call that matters (lets call that "call 2") can be executed, it has to make an Ajax call to get a sessionId (and lets call that "call 1"). The sessionId is necessary to make any call to the IP and have it do something with the arguments.
But when I have the function below each other, it first does "call 2" and after that "call 1". Classic async behavior but since in the Ajax call I say async: false, I don't really understand why it isn't doing what I say it has to do.
Complete Ajax Call "call 1":
Url = "_ip_?action=getsessionid";
$.ajax({
url: Url,
type: "Post",
dataType: "jsonp",
async: false,
success: function( json ){
var j = $.parseJSON(json);
var sessionid = j['sessionId'];
},
error: function( errorThrown ) {
console.log(errorThrown);
}
});
And Ajax call "call 2":
Url = "_ip_?action=action&sessionId=" + sessionid;
$.ajax({
url: Url,
type: "Post",
dataType: "jsonp",
async: false,
success: function( json ){
var j = JSON.parse(json);
//do something with j
},
error: function( errorThrown ) {
console.log(errorThrown);
}
});
Just assume variable sessionid does give the sessionid to "call 2".
As you can see, I get an json string returned.
What I did now is that the next Ajax call only gets initialized and executed when the first Ajax call was successfully executed. This seems a workaround to me and not a proper way to do what I try to accomplish.
from JQuery.ajax documentaton:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
With that. My solution is to make the next ajax request inside the success function. The JQuery documentation explains this more. http://api.jquery.com/jquery.ajax/
Define var sessionid as global variable and assign the value to the same in ajax call1 and then access this value in call2.
var sessionid='';
Url = "_ip_?action=getsessionid";
$.ajax({
url: Url,
type: "Post",
dataType: "jsonp",
async: false,
success: function( json ){
var j = $.parseJSON(json);
sessionid = j['sessionId'];
},
error: function( errorThrown ) {
console.log(errorThrown);
}
});
I'm calling a page (external, on other domain), with this code:
var instagram_container = $('div#instagram-answer');
if (instagram_container.length>0)
{
var url = 'http://www.xxxx.it/admin/get_instagram_token';
$.ajax({
type : 'GET',
url : url,
async : false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(response)
{
console.log(response);
instagram_container.html(response.client_id);
},
error: function(e)
{
console.log(e);
}
});
}
I have answer with console.log(e) (basically it recognizes as error)?
Object { readyState=4, status=200, statusText="success", altri elementi...}
But in Firebug, under NET tab, I have the right answer...
This is the console. Line 19 is exactly the
console.log(e);
in error section.
My goal is obtain that Json. Thank you
Is your server returning plain text, or an actual JSON file? Jquery will ignore the response if the server returned a string instead of JSON.
The response type should be: "application/json"
EDIT:
I'd recommend you to use the basic jquery ajax call:
$.ajax({
url: "test.html",
cache: false
})
.done(function( response ) {
console.log(response);
});
I'm making ajax POST request from javascript function:
function UpdateMetrics() {
$.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
...
}
});
}
From my handler, I'm sending json string with:
context.Response.write(json);
I think I'll get it in msg.
I also want to send other string (count). So I'm trying to use header info along with json data. So I added this line:
context.Response.Headers.Add("MaxCount",Convert.ToString(tempList.Count));
If this is right way to do it, how can I access it in my success function?
To access headers in your success function, add in 2 more arguments to your function, the status code and the jqXHR object, which you can read the documentation for at api.jquery.com.
So, your function should look like:
success: function (msg, status, jqXHR) {
var jsonUpdatedData = msg;
...
}
However, as pointed out in comments, it's probably best not to use the header to send data. You should probably just include it in the json you send out.
You also need to tell jQuery to interpret the response as json by setting
dataType: "json"
Otherwise, it will just be returned to you as text.
Your requirement to get the header data in ajax post success can be achieved using getResponseHeader method please refer the below code snippet.
function UpdateMetrics() {
var callback = $.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
var headerdata = callback.getResponseHeader("MaxCount");
// Where MaxCount is name provided in the header.
...
}
});
}
Thanks