before I explain my issue I would like to mention that I'm a naive on jsonp. This is actually my very first attempt to work with JSONP.
Im using jquery ajax call to pullback data from a website.
my jquery code is below
$.fn.checkTPS = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function() {
var api_key = 'asdfasfsadfsadfsad';
var format = 'json';
var username = 'dame#example.co.uk';
var self = $(this);
var selfValue;
var feedback = $('.tps-feedback');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()) {
selfValue = self.val();
if (selfValue.length > 9){
$.ajax({
url: 'https://www.selectabase.co.uk/api/v1/tps/' + selfValue + '/',
type: 'get',
dataType: 'jsonp',
data: {
format: format,
username: username,
api_key: api_key
},
success: function(data) {
console.log(data);
},
error: function() {
},
jsonp: 'jsonp'
});
}
}
},3000);
}
});
});
};
I want to accommodate a service from selectabase.co.uk, according to them this is how I should use the service https://www.selectabase.co.uk/api/v1/tps/[number]/?format=json&username=[username]&api_key=[api key]
when I send request using ajax I get this error Uncaught SyntaxError: Unexpected token : and when clicked this opens up
{"ctps": false, "number": "1452500705", "resource_uri": "/api/v1/tps/01452500705/", "tps": false} by the way this I want but don't know what's this error is unexpected token :
I've copied the following link from inspect element tab (you can see the image below) I think this is the call that has been generated by json https://www.selectabase.co.uk/api/v1/tps/01452500705/?jsonp=jQuery17102731868715648129_14120077325500&format=json&username=dame40example.co.uk&api_key=asdfasfsadfsadfsad&_=14120077325500
I copied the link below from inspect element > source tab in chrome.. I think I should add an image to describe properly where this json data and link I've copied from.
I hope I've manage to convey my message across... please help if you have any Idea what do i need to add... Regards
The format=json in your query string should probably be format=jsonp. The server is replying with JSON, but you're expecting a JSONP response. But I don't know that they support format=jsonp, it's just a guess.
Alternately, if that server supports CORS and allows requests from your origin, you could handle JSON instead (just remove dataType: "json" from your ajax call). Beware that that would require that the user be using a browser that properly supports CORS, which IE8 and IE9 don't. (They support CORS, but not via the normal XMLHttpRequest object, and this is a browser inconsistency that jQuery doesn't smooth over for you. If you search, though, you can find "plugins" or similar that will handle it.)
Related
I'm having a big problem over the last week and I can't seem to figure out a solution.
I'm trying to post some raw XML to a server that another company has developed for us that has, I think a listener to receive this XML input. I'm posting and sending the information just fine the thing is that I don't get any response back (just like every girl I liked in highschool...).
The error i get from Chrome is: >POST http://xx.xxx.xxx.xxx:xxxx/SLISMESSAGE net::ERR_EMPTY_RESPONSE
and I've tried other browsers also but all of them the same deal except for Firefox that gives me a CORS error.
When I post the listener on the the server just says: Get Request /SLISMESSAGE.
var template = [
'<?xml version="1.0"?><request type="create-order"><PATIENT><CODE><?CODE?></CODE><DEPARTURE_DATE><?DEPARTURE_DATE?></DEPARTURE_DATE><LASTNAME><?LASTNAME?></LASTNAME><FIRSTNAME><?FIRSTNAME?></FIRSTNAME><BIRTHDAY><?BIRTHDAY?></BIRTHDAY><SEX><?SEX?></SEX><PHONE1><?PHONE1?></PHONE1><EMAIL><?EMAIL?></EMAIL><HOTEL><?HOTEL?></HOTEL><HOTELNO><?HOTELNO?></HOTELNO></PATIENT><ORDER><ORDERNO><?ORDERNO?></ORDERNO><ORDERDATE><?ORDERDATE?></ORDERDATE><ORDERTIME><?ORDERTIME?></ORDERTIME><SENDERCODE><?SENDERCODE?></SENDERCODE></ORDER><TESTS><TEST><?TEST?></TEST></TESTS></request>'
].join('\r\n');
function update() {
var len = 10;
var randomId = parseInt((Math.random() * 9 + 1) * Math.pow(10,len-1), 10);
//console.log(randomId.toString());
var variables = {
'CODE': $('input[name="wpforms[fields][25]"]').val(),//randomId.toString(),
'DEPARTURE_DATE':$('input[name="wpforms[fields][3][date]"]').val(),
'DEPARTURE_TIME':$('input[name="wpforms[fields][3][time]"]').val(),
'LASTNAME': $('input[name="wpforms[fields][6][last]"]').val(),
'FIRSTNAME': $('input[name="wpforms[fields][6][first]"]').val(),
'BIRTHDAY': $('input[name="BIRTHDAY"]').val(),
'SEX': $('input[name="wpforms[fields][9]"]').val(),
'PHONE1': $('input[name="wpforms[fields][14]"]').val(),
'EMAIL': $('input[name="wpforms[fields][15]"]').val(),
'HOTEL': $('input[name="wpforms[fields][16]"]').val(),
'HOTELNO': $('input[name="wpforms[fields][17]"]').val(),
'TEST':$('input[name="wpforms[fields][2]"]').val(),
'ORDERNO':$('input[name="wpforms[fields][25]"]').val()
};
var newXml = template.replace(/<\?(\w+)\?>/g,
function(match, name) {
return variables[name];
});
console.log(newXml);
var parsedNewXml = $.parseXML(newXml);
//console.log(parsedNewXml);
var order_num = document.getElementById("wpforms-1034-field_25")
$.ajax({
url: "http://xx.xxx.xxx.xxx:8008/SLISMESSAGE",
method: 'POST',
crossDomain: true,
cache: false,
async: true,
timeout:0,
data: newXml,
contentType: "application/xml",
dataType: "xml",
success : function(){
console.log('XML Sent');
alert("Data sent");
},
error : function (xhr, ajaxOptions, thrownError){
console.log(xhr.status);
console.log(thrownError);
console.log('HEYYYYYYYYYYYY');
alert(order_num);
}
});
The thing is when I try to post the same XML from postman I get a response. And the weirdest of them all, when I try to post with a python script I also get a response! ????????
Note that I'm not that good at JS or jQuery and there might be something I'm really missing here but if not then WTH?
I don't know what to do. At this point I'm almost at the point of giving up even though that would mess up a lot of things in the future but I have no idea what to do...
Python Code
Response Time
Results of Python Code and JS jQuery
Python is in blue JS in red
Note that I'm not that good at JS or jQuery and there might be something I'm really missing here but if not then WTH?
I don't know what to do. At this point I'm almost at the point of giving up even though that would mess up a lot of things in the future but I have no idea what to do...
It could be a CORS issue. You can see in the console tab in developer tools if you are getting cors error. Because browser blocks the response if cors is not properly configured. When you hit the api from Python the cors issue wont be happening because the cors check happens in the browser and not in Python
I am developing i small app that displays some JSON data
inside of a listview. To receive the data I am using a simple request.
And I am getting always the same issue:
Uncaught SyntaxError: Unexpected token :
my code:
$.ajax({
url: 'http://localhost/documents.json',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
// do something with the data
},
type: 'GET'
});
});
My JSON file is valid. I checked it with a JSON validator.
Invalid JSON (no matter how mangled) cannot generate a JavaScript syntax error if you parse it with JSON.parse() or any decent dedicated parser (and that's what jQuery does). The same happens with all other standard data types (XML, HTML, plain text...). All symptoms suggest you're expecting JSONP but getting some other data type. The builtin browser network pane should reveal what you're getting exactly.
Whatever, if you only want JSON and nothing but JSON you should simplify your code as follows:
Omit protocol and host:
url: 'http://localhost/documents.json',
should be:
url: '/documents.json',
(Probably not required, but will help to void errors.)
Ask for the correct data type:
dataType: 'jsonp',
should be:
dataType: 'json',
Do not parse again what jQuery already parsed for you:
var json = $.parseJSON(data);
should be:
var json = data; // Yeah, nothing :)
This should be enough for local AJAX. If you really need a cross-site request (I asked twice and never got an answer) you have to tweak your server to either return the appropriate CORS headers or implement JSONP data type and change your client-side code accordingly because you'll no longer have JSON—because JSONP is not JSON!
Check if your json is valid by using jsonlint.com or you can use jsonmate.com. These are very helpful to me when I'm debugging json.
Also - it would help to have a link to the full code. Use jsfiddle.net to put your code into - then link it to this post. This will help the community debug your code.
I am working with an API from another website and I am trying to get a JSON object back. Unfortunately due to the site origin issue I have to use JSONP to retrieve my data.
The function is working but I am stack on how to sanitize the data coming as a JSONP format to be able to use it as JSON?
This is my function
$('.loginForm').click(function(){
var url = 'https//api.example.com';
$.ajax({
type:'GET',
url: url,
dataType: 'jsonp',
error: jsonpCallback,
success: jsonpCallback,
jsonp: "callback"
});
function jsonpCallback(response){
console.log(response);
}
});
EDIT
This is the response I get before the error
Object { readyState=4, status=200, statusText="success", more...}
And this is the error i'm getting
SyntaxError: missing ; before statement
{"accountID":1328031,"authToken":"D81CDCB......
I went through every post in SO and the web in general to find where I am making a mistake but so far I can't find anything.
If you are getting the response in jsonP then you can use jXHR for making cross domain request , below is the link of jXHR (Library) :
https://gist.github.com/1576277/f4aead6741e0d7b0c40db6601048d9db6be1a5f9
And here is an example to use jXHR :
function sendRequest()
{
var xhrReq = new jXHR();
xhrReq.onreadystatechange = function(data)
{
if (xhrReq.readyState === 4)
{
//data contains your jsonp response..
}
};
var url = "http://" + SERVER_NAME + "yourCodeFile.aspx?callback=?";
xhrReq.open("GET",url);
xhrReq.send();
}
Always remember to add 'callback=?' as a query string parameter in url for jXHR request as the respone is jsonP.
Hope this helps you.
try using JSON.parse
function jsonpCallback(response){
console.log(JSON.parse(response));
}
Essentially, if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
Here's the latest code tried.
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
also tried:
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
},
});
But when I try and alert(access_token); or run a foursquare api call I get the following errors
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token : checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)
I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!
Browsers natively implement a global function JSON.parse(), and if for some reason that doesn't work you can use jQuery's parseJSON() function.
Here's how it works. Let's say your JSON object has the following format:
{
Status: "Success",
Resource: {
Name: "Person's Name",
URL: "http://blahblahblah.com/extrastuffhere?querystuff=here"}}
Then you can access the "URL" element by using JSON.parse() like so:
var url = JSON.parse(json).Resource.URL;
(I'm unfamiliar with Foursquare but it should look similar, and you can do console.log(json) to see its structure.)
So your code might look something like this:
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
var parsed = JSON.parse(json);
console.log(parsed);
access_token = parsed.access_token;
});
});
Hope that helps!
With help from others I've gotten to the point where I can see the json return from foursquare but any attempts to call it yield an error.
Essentially, if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
Here's the latest code tried.
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
also tried
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
},
});
But when I try and alert(access_token); or run a foursquare api call I get the following errors
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)
I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!
Try removing the "&callback=?" from the url. I think jQuery adds that for you if you set the dataType to jsonp.
EDIT:
from the jquery ajax documentation describing the dataType parameter:
"jsonp": Loads in a JSON block using
JSONP. Will add an extra "?callback=?"
to the end of your URL to specify the
callback.