JSONP call with invalid label - javascript

I'm trying to do a JSONP call to an api but I'm not sure if the API supports JSONP not sure how I can test for that. But below shows firebug console error which is invalid label. Does this mean the api does not support JSONP is this something wrong in my call.
Here is my call to the api. I changed the url because the client would not be happy of my giving out the url
jQuery.getJSON("http://blaa.blaa.com/api/services?format=js&callback=?",
function (data) {
console.log("services data = ", data);
});
When I test in firebug I get this
invalid label
{"services":{"service":[{"name":"tt"...
servic...2711124 (line 1, col 1)

Invalid label is the error you will get when what you expect to be served as JSONP content (i.e. Javascript code) is in fact JSON content.
This is not valid Javascript, even though it is a JSON object:
{'foo' : 'bar'}
This is because the { is treated as the opening of a block, rather than an object literal. 'foo' is then treated as an attempt to create a label, where it is invalid to have the surrounding quote marks.
This essentially functions as a cryptic message to tell you that the server doesn't understand JSONP, or that you haven't requested it properly (some servers ask for extra parameters beyond the standard callback=).

Related

403 Forbidden while sending data from JavaScript

It is neither issue of file permission nor existence of file.
While sending formData through jquery data is passing successfully, but when I try with pure javascript then it returns error POST 403(Forbidden).
It is sure that problem is generated from ckeditor content. because if I pass following parameters
var heading = document.getElementById('heading').value;
var date = document.getElementById('date').value;
And pass as follow
http.send('heading='+heading+'&date='+date);
It returns no error, works fine.
But if I add following parameters
var content = CKEDITOR.instances.editor.getData();
And pass as follow
http.send('heading='+heading+'&date='+date+'&content='+encodeURIComponent(content));
It returns error.
POST 403(Forbidden)
I think special characters that are inserted in textarea are the cause of problem. Because if variable content is empty there would no error. Jquery is passing data, but why forbidden issue while using javascript ? I need to pass special characters without escaping. Because I can't control ckeditor output, becuase it is user input.

"Unexpected end of JSON input" error on loading JSON file from local file system

Hi I'm trying to retrieve data from a title.JSON file into an index.html file using AJAX calls.Both these files resides in my local file system.I have created a new instance of the chrome and 've set its target property as "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"--disable-web-security --user-data-dir="c:/chromedev"(I'm aware that this is not a good practice. Just trying out a server less way).Below is my code
<h1><a id="headName" href="#">Name</a></h1>
<p onclick="spaLoad()">NameChange</p>
function spaLoad(){
var xhr = new XMLHttpRequest();
xhr.open('GET','title.json',true);
xhr.send();
xhr.onreadystatechange=function () {
//var obj=xhr.responseText;
var obj = JSON.parse(xhr.responseText);
console.log(obj);
console.log(xhr.readyState);
console.log(xhr.status);
console.log(xhr.statusText);
//document.getElementById('headName').innerHTML = obj;
document.getElementById('headName').innerHTML = obj.name;
}
}
title.json
{"name":"stackoverflow","age":"100"}
I get my h1 updated as "stackoverflow" through an ajax call along with the error
Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at XMLHttpRequest.xhr.onreadystatechange
Here are my doubts:
1.I hope AJAX is for the communication between the client and the server. Though I have avoided using a server by modifying the browser settings, how did the ajax call work for me?Is it logical?
2.The JSON file contains the data as objects.Then why should I use JSON.parse(responseText)?(JSON.parse() is for converting the string from server into object for client I hope).If i directly give var obj=xhr.responseText;I get undefined.
3.readystate is changing to 4, but status is always 0.Why is it so?How could I resolve it.
Please give a brief explanation of how this server less ajax call works.I'm very new to ajax and is confused with this.
It is because readystate change fires multiple times and you expect it to fire once. You would need to check for readystate to be equal to 4 and the status to be 200 (or zero in your case since you are on the file protocol). Or use the onload and onerror events instead.
And if you still get a parsing error than you need to debug what is being returned.
//see what is returned
console.log(xhr.responseText)
//Look to see if you have hidden characters in the file.
console.log(escape(xhr.responseText))
Parsing errors occur either the file you are loading returns something else like an error page OR it has special hidden characters that cause the parser to choke.

Invalid JSON data $.get() method - Uncaught SyntaxError: Unexpected token <

I need help guys.
I am trying to fetch data from the server which is returning JSON data but I am getting the following error message (in Chrome 52).
It seems like the JSON data that is returned is invalid or its not in the expected format.
ncaught SyntaxError: Unexpected token <
My server is returning data in the following JSON format
"[{\"ActionCardId\":1,\"ActionCardNumber\":\"279877\",\"AccountNo\":\"2202322179\",\"ClientName\":null,\"CellNumber\":\"0787596971\",\"TenantName\":null,\"TenantCellNumber\":null,\"AddressStandNo\":null,\"AddressStreet\":\"43 DELMAS AVENUE\",\"AddressSuburb\":\"BOKSBURG\",\"AddressCity\":null,\"AddressPortion\":null,\"AddressEarthNo\":null,\"AddressPremise\":null,\"AddressGISKEY\":null,\"AmountDueTotal\":4080.0,\"AmountDue30Day\":null,\"AmountDueCurrent\":null,\"AmountDue60Day\":null,\"ServiceLevy\":null,\"MeterNumberWater\":null,\"MeterNumberElectricity\":\"M22541\",\"MeterNumberElectricity2\":null,\"MeterNumberElectricity3\":null,\"MeterNumberPrePaid\":null,\"IsPrinted\":true,\"IsResidential\":null,\"ActionSuccessful\":false,\"ActionCardDate\":\"2016-08-20T00:00:00\",\"Remarks\":null,\"UnSuccessfulReason\":null,\"CaptureContractorId\":null,\"AddressCombo\":\", 43 DELMAS AVENUE, BOKSBURG, , \",\"BillCycleName\":\"120\",\"ServiceIndicator\":null,\"WaterReading\":null,\"WaterReadingDate\":null,\"ElectricityReading\":null,\"ElectricityReadingDate\":null,\"Unit\":null,\"ActionCardTypeId\":2,\"ContractorId\":1,\"ActionCardStatusId\":1,\"UnSuccessfulActionReasonId\":null,\"TechnicianId\":1,\"AccountInfoId\":null,\"ServiceDeliveryCentreId\":4,\"BillCycleId\":2,\"ActionCardType\":{\"ActionCardTypeId\":2,\"Active\":null,\"CreatedByOnlineUserId\":null,\"DateCreated\":null,\"DateModified\":null,\"Deleted\":null,\"Description\":\"Electricity Disconnection\",\"ModifiedByOnlineUserId\":null,\"Name\":\"ED\",\"CreatedByUser\":null,\"ModifiedByUser\":null},\"Contractor\":null,\"ActionCardStatus\":null,\"UnSuccessfulActionReason\":null,\"Technician\":null,\"AccountInfo\":null,\"ServiceDeliveryCentre\":null,\"BillCycle\":null,\"ActionName\":\"ED\",\"DateCreated\":\"2016-07-06T00:00:00\",\"DateModified\":\"2016-08-13T10:24:17.5833635\",\"CreatedByOnlineUserId\":null,\"ModifiedByOnlineUserId\":\"fa93e65d-e4a7-4a0c-91c6-4561e2612f9c\",\"CreatedByUser\":null,\"ModifiedByUser\":null}]"
I am using Javascript in my client side
$("#importDailyJobs").click(function () {
var technicianId = 1;
var serverUrl = "http://localhost:35825/Mobile/ImportDailyReadings"
$.get(serverUrl, { TechnicianId: technicianId }, function (data, status) {
alert("Success");
console.log(data);
}, "jsonp");
});
I using jsonp because I am using cross domain to get the data.
Your returned data is not a JSON. It's a string. You explicitly expect JSON via the jsonp argument, and you return a string, hence the error.
It seems like you are encountering an error on that URL and the response is enclosed inside an html tag <>.
As suggested by "Jason P" you should check the actual response in the "raw" format. If you are on Google Chrome, you can press F12, then navigate to "Network" Tab, and then select "XHR" after which you should trigger the respective event by clicking on #importDailyJobs. You should see the Ajax Request, on clicking of which you shall be able to view the details for that request, like Headers, Preview, Response etc.
You can view the raw data inside the Response tab.
Also on a side note, just wrap the string in single quotes when you have double quotes inside it, and if you have both then wrap the string in the one which is least used, to prevent lots of escaping as can be seen in your sample response.

DataCloneError: An object could not be cloned

I need to pass a Hash function by using the javascript postMessage. I'm using the browser Firefox. When I'm sending this I'm getting the below exception.
'DataCloneError: An object could not be cloned' The code which I have implemented so far is as below.
var mes = CryptoJS.SHA256(clientId + origin + sessionState);
opIFrame.postMessage(mes,endPoint);
When I'm sending a string value this works successfully. I tried to send mes.toString() but it still gives the same error. I saw several threads on this topic. But could not configure a solution. Please advice me on this.
Ensure that the mes variable contains a WordArray object after the call to CryptoJS.SHA256 by logging it into the console. It looks like the object you're trying to send via postMessage() is not what you're expecting (possibly an Error or a Function object).

Jquery.ajax API request in JSON format causes "Uncaught SyntaxError: Unexpected token :" in Chrome

I am trying to query the http://developer.pintlabs.com/brewerydb/api-documentation with jquery.ajax.
These are two of the Jquery requests i tried (note that "O3tmVI" is a dummy ID):
$.ajax({
url:"http://api.playground.brewerydb.com/beer/" + "O3tmVI" + "?key=A1029384756B&format=json",
dataType: "jsonp",
jsonpCallback: "callbackfunctie",
success:function(oData){
var returnData = oData;
console.log(returnData);
}
});
And:
$.getJSON("http://api.playground.brewerydb.com/beer/" + "O3tmVI" + "?key=A1029384756B&format=json&jsoncallback=?",
function(data){
console.log(data);
});
Both cause this error:
Uncaught SyntaxError: Unexpected token :
Now, the json object returned looks like this:
{"message":"Request Successful","data":{"id":"O3tmVI","name":"The Public","description":"The Public\u2122 is a delicious easy drinking pale ale made from a simple recipe of quality grain and top notch American hops. Tawny hues of caramel and amber are a trademark of the Public ale as well as a delicious spruce crispness resulting from a beautiful abundance of hops! This beer will be produced throughout the year and serves as the foundation of our product line.","abv":"6","glasswareId":8,"availableId":1,"styleId":33,"isOrganic":"N","labels":{"icon":"http:\/\/s3.amazonaws.com\/brewerydbapi\/beer\/O3tmVI\/upload_3sdJcU-icon.png","medium":"http:\/\/s3.amazonaws.com\/brewerydbapi\/beer\/O3tmVI\/upload_3sdJcU-medium.png","large":"http:\/\/s3.amazonaws.com\/brewerydbapi\/beer\/O3tmVI\/upload_3sdJcU-large.png"},"status":"verified","statusDisplay":"Verified","servingTemperature":"cool","servingTemperatureDisplay":"Cool - (8-12C\/45-54F)","createDate":"2012-04-05 04:02:36","updateDate":"2012-04-05 04:34:17","glass":{"id":8,"name":"Tulip","createDate":"2012-04-05 04:00:04"},"available":{"id":"1","name":"Year Round","description":"Available year round as a staple beer."},"style":{"id":33,"categoryId":10,"category":{"id":10,"name":"American Ale","bjcpCategory":"10","createDate":"2012-04-05 04:00:04"},"bjcpSubcategory":"A","name":"American Pale Ale","simpleUrl":"american-pale-ale","ibuMin":"30","ibuMax":"45","abvMin":"4.5","abvMax":"6.2","srmMin":"5","srmMax":"14","ogMin":"1.045","ogMax":"1.06","fgMin":"1.01","fgMax":"1.015","createDate":"2012-04-05 04:00:04"}},"status":"success"}
I have succesfully validated it as valid JSON
Now, the problem is i need a JSONP object in order to request it (cross-domain). So it has to be wrapped in a container function. This should be possible with the parameters in the request, but so far i have tried almost anything but have had no success...
I found this article wich has a short entry on this bug: http://www.jquery4u.com/json/ajaxjquery-getjson-simple/
Uncaught SyntaxError: Unexpected token :(in crome) Invalid Lable(in firefox)
“invalid label” error can be fixed by passing the JSON data to the js callback
But i don't really understand what he's saying there
What am i doing wrong?
My guess is that the service at http://api.playground.brewerydb.com/beer/ is returning json but NOT jsonp. Search the jsonp tag for "Unexpected token" and you'll find many explanations such as this one. The json must be wrapped in a javascript function, i.e. the callback but it is up to the cross domain Web Service to support jsonp. This is enforced by the browser and jQuery cannot overcome it.
The API doesn't support JSONP by design
no we don't [support JSONP], as you would have to expose your API key. Best thing to do is setup an intermediate proxy on your side.
see twitter.
Note the folks over at the Open Beer Database do support JSONP.

Categories

Resources