Reputation: 1165
I am making a cross browser jsonp call in which my backend to which i am sending some values is made using django
and getting some after callback to my front end which is in php . The problem is its giving Uncaught SyntaxError: Unexpected token :
error The data is being send from the django and i have checked that. i am using the code below to make jsonp calls
$(document).on('click', '.miloginme', function(event) {
var username = $('#username').val();
var password = $('#password').val();
var token = $('#token').val();
var dataString="uid="+username+"&token="+token;
$.ajax({
type: 'POST',
url: "http://localhost:8000/b/authenticate/",
crossDomain: true,
data: dataString,
async: false,
dataType: 'jsonp',
success: function(data) {
alert(data);
}
});
});
the values in callback that i am getting is in format
{"token": "KAMWMS151UWPR4Q", "authenticate": "1", "userid": "brad", "fname": "rahul", "booster_number": "1"}
Upvotes: 1
Views: 5709
Reputation: 7719
tldr; The server is not sending back JSONP.
Value reported in the post is JSON (and it is valid JSON) - it is not JSONP. If it were to be treated as JSONP (i.e. evaluated by a <script>
) then it would be a syntax error because it is not a valid JavaScript program.
Try this in a JavaScript console:
{"token": "KAMWMS151UWPR4Q", "authenticate": "1", "userid": "brad", "fname": "rahul", "booster_number": "1"}
Error look familiar? (Different browses can return different error messages: Chrome -> "Unexpected token :", FireFox -> "invalid label", IE9 -> "Expected ';'".)
A valid JSONP result would look similar to:
theCallback({"token": "KAMWMS151UWPR4Q", "authenticate": "1", "userid": "brad", "fname": "rahul", "booster_number": "1"})
(The name of theCallback
is taken from the jsonp
variable passed to the server and the client - e.g. jQuery - creates this function before the injecting <script>
element is created so that the function can be invoked using the above syntax.)
Valid JSONP works because the "JSON" data is then run in an expression context (in which it is treated as a valid JavaScript Object Literal), not a statement context (where it is treated as a label and then "some junk" leading to a syntax error).
Common approaches to return JSONP from Django utilize View Decorators:
Upvotes: 3