Correct use of JSONP - javascript

To successfully use JSONP (e.g. via jquery - $.ajax ... etc.) must always be that the requested page is designed to provide data corresponding to this format?
In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also will I get an error?
This question might seem trivial to some users, but I'm starting right now to learn these technologies, and the matter is a bit complicated.
Based on these (ref1 ref2) references it would seem that there must be consistency between the request with JSONP and implementation of the server response.
Edit
I have this jQuery request
$.ajax({
url: "https://sites.google.com/site/problemsstore/javascript/test.js",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
And I have loaded in https://sites.google.com/site/mysite/javascript/test.js?attredirects=0&d=1 this test.js file:
function myCall(data) {
console.log('succeed');
}
myCall({ some : "data" });
When I am connected I hope to obtain as console's output: succeed succeed.
Instead this is what I get:
succeed
failed
Edit2
$.ajax({
url: "https://sites.google.com/site/bentofelicianolopez/jscript-jsonp/test.js?attredirects=0&d=1",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
jsonp: 'myCall',
//contentType: 'application/json',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
The .js file:
myCall({ some : "data" });
The output:
failed test4.html:94:9
ReferenceError: myCall is not defined /*this is the syntactical error of which I said*/
test.js:1:1

To successfully use JSONP (e.g. via jquery - $ .ajax ... etc.) must always be, that the requested page is designed to provide data corresponding to this format?
Yes. A request for JSONP will only work if the response is expressed as JSONP.
In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also I will get an error?
You can have a static JavaScript program that conforms to the JSONP format (it requires hardcoding the callback function name), so not necessarily.

Related

Jquery not passing any parameters data

My Code is as below for Javascript
$.ajax({
type: "POST",
url: "page/rSales.aspx",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function (res) {
alert('Success');
},
error: function (res) {
alert('Fail');
}
});
I use http tracer tools to trace whether or not the parameter is passing on to my backend - and it is not. I have also tried adding contentType: 'application/json; charset=utf-8', adjust parameter by adding colon, but none of it is working.
My Backend code C# :
Request.Params["ListID"].ToString();
It always returns null, due to the parameter not passing on. I am wondering what is causing this problem and how should I resolve it.
The Request.Params collection does not support JSON requests, so you have to parse response body manually (or send it as form data).
https://msdn.microsoft.com/en-us/library/system.web.httprequest.params(v=vs.110).aspx says "Gets a combined collection of QueryString, Form, Cookies, and ServerVariables items."
For firefox you declare var event; before your ajax call this is very well known issue in firefox.

How to get the response text from an AJAX request using jQuery

I am trying to make a JSONP request to a server. This is my code:
$.ajax({
type: 'GET',
url: myURL,
async: false,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
headers: {
'Accept': 'application/json', //this is required by the server
'key': key
},
success: function() {
alert('1');
},
error: function() {
alert('2');
},
complete: function(){
alert('3');
}
});//code indentation
When I run the code it errors. But if I open the developers tools in Chrome (ctrl+shift+I) I can see the request under "network". Clicking on it shows the correct response (and shows the request was accepted).
Apologies is there is a really obvious solution (I have tried searching, but with no luck), but at this point I am well and truly baffled. Any help would be really appreciated.
::EDIT::
changing the error function to:
error: function() {
console.log('error', arguments);
},
returned the message "jsonCallback was not called" Thanks to Aaron Digulla below.
The response from the server is JSON, not JSONP (checked with JSONlint)
When you say "it errors", my guess is that you get alert(2). To find out why, log the function arguments to the console:
...
error: function() {
console.log('error', arguments);
},
...
jQuery will pass additional information (like the error message) to the function. That should help you understand why it fails.
The same is true for the success function which gets the server response, for example.
[EDIT]
I get the error jsonCallback was not called
That means your server isn't returning JSONP. JSONP looks like name({...}) while normal JSON looks like {...}. Please check your server's configuration and make sure it actually supports JSONP and that the response looks correct.
I should have seen this from your code:
dataType: 'jsonp'
headers: {
'Accept': 'application/json', //this is required by the server
}
That means you're sending a JSONP/JSON mix which can't work. If you use a certain dataType, then let jQuery build the correct headers.
The success function has argument and from that argument you can get the response text.
$.ajax({
type: 'GET',
url: myURL,
async: false,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
headers: {
'Accept': 'application/json', //this is required by the server
'key': key
},
success: function(response) {
alert(response);
alert('1');
},
error: function() {
alert('2');
},
complete: function(){
alert('3');
}
});
You cannot set async: false for a jsonp request due to nature of it, adding script tag to handle response method.
dataType: 'jsonp
as you mentioned,the type of data that you're expecting back from the server is jsonp but may be your server will return any other format rather than jsonp.. so check it which type of response your server is returning in under Network in browser console... then if it is not jsonp format, change your respons return type....

How to access Recurly API with AJAX?

I'm using a jquery ajax call to a recurly API endpoint, but I get cross-origin errors. From my understanding, this is because Recurly only returns results as XML... when I use JSONP to get around cross-origin errors, I get an error because it receives the XML data but expects JSONP. Pretty obvious. But I'm trying to understand how exactly can one use this API at all via AJAX calls. I've been successfully able to access the API with PHP, but unfortunately, for this project, I can't use any client-side code.
Even if I find some sort of middle-code solution to get the XML and convert it to JSON for my side to accept, I need to utilize the API for POST requests (creating accounts, subscriptions, etc.) so I would like to understand how to utilize the API properly.
Here is an example of my code:
$.ajax({
url: "http://[DOMAIN].recurly.com/v2/accounts",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + window.btoa("[API KEY]"));
},
crossDomain: true,
type: "GET",
accepts: "application/xml",
dataType: "application/xml; charset=utf-8",
success: function (data) {
console.log("SUCCESS:", data);
},
error: function(e){
console.log("ERROR:", e);
}});
Anyone with Recurly API experience have any tips/advice?
From https://docs.recurly.com/api/recurlyjs/jsonp_endpoints
$.ajax({
dataType: 'jsonp',
url: 'https://{subdomain}.recurly.com/jsonp/{subdomain}/plans/{plan_code}',
data: {
currency: 'USD',
},
success: function (data) {
// do stuff
},
}
You should not use the V2 API from the browser. Doing so risks exposing your private API key. If someone has your API key they can make calls charging customers, modifying subscriptions, causing all sorts of problems.
Look at the JSONP endpoints that Byaxy linked to.

SyntaxError: missing ; before statement jquery jsonp

I am using below code to access rest service hosted on another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
I am able to get the data correctly, but I get this error in firebug in mozilla:
SyntaxError: missing ; before statement
{"Hello":"World"}
Can anyone suggest me what I am doing wrong here? Even though Json data is valid. I tried all the suggestions posted in this question But still I am getting same error.
If it's really JSON you ask for, don't set "jsonp" as dataType, and don't provide a callback :
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
the format of JSON and JSONP are slightæy different
JKSONP is a function invocation expression
callback({"hellow":"world"});
whereas JSON is simply a serialized object
{"Hello":"world"}
fromyour posting it would seem that the server is returning JSON and not JSONP
So you either need to change the server to reply correctly (The actual callback name is a get parameter to the request). You should do this if you are using the ajax call across domains
If you are not using ajax across domains stick to regular JSON

Get JSONPto work

I am trying to access data from a php server with a cross domain support. So when i try $.ajax with dataType : 'jsonp' i have an error in console: Uncaught SyntaxError: Unexpected token The file is interpret as a javascript file an the request fail. Have you an idea for get data whithout this error.
$.ajax({
url : 'http://domaine.com/json.php',
contentType: "application/json; charset=utf-8",
dataType : 'jsonp',
success : function(data){
console.log(data);
// no enter in this callback
},
complete: function(data1, data2, data3){
// no data from file.js
}
});
First make sure that your PHP script supports JSONP. Identify the query string parameter that needs to be passed so that the script returns JSONP. Then test it in your browser by directly entering the following address in your address bar:
http://domain.com/json.php?callback=abc
You should see something along the lines of:
abc({ ... some JSON here ... })
You might need to adjust the callback name parameter if your PHP script expects a different one. This could be the case if you see the following output ({ ... some JSON here ... } without being wrapped in your javascript function)
And once you have ensured that you have a valid PHP script that returns JSONP you could consume it:
$.ajax({
url : 'http://domain.com/json.php',
jsonp: 'callback',
dataType : 'jsonp',
success : function(data){
console.log(data);
// no enter in this callback
},
complete: function(data1, data2, data3){
// no data from file.js
}
});
Things to notice:
I have specified the callback using the jsonp: 'callback' parameter
I have gotten rid of the contentType: 'application/json' parameter because jQuery's implementation of JSONP uses script tags which doesn't allow you to set any request headers.
You need to add ?callback=? to the request so that the proper callback is evaluated. It may not be called callback, though. You need to find out what it is called from the domain.
If the domain (and browser) supports CORS, you don't even need to use JSONP. You can use a normal request.

Categories