Parsing Json results in uncaught syntax error - ajax

My browser (chrome) tells me this is what is being returned from the server which I have verified as being valid via JsonLint:
[{"Id":"bdd937ef-c0d4-4191-805f-316288144060","Name":"Accessories and Auto Parts, Moto ","L18nName":null,"State":null,"L18n":"1033","Index":0,"LevelId":0,"ImagePath":"/content/img/browse/sm/","Children":[]},{"Id":"b01bde48-6f1d-4168-aee4-a7e62eef7bd0","Name":"Car Rental","L18nName":null,"State":null,"L18n":"1033","Index":0,"LevelId":0,"ImagePath":"/content/img/browse/sm/","Children":[]},{"Id":"c039a467-1709-433f-a316-008f6ae301fb","Name":"Car Sales ","L18nName":null,"State":null,"L18n":"1033","Index":0,"LevelId":0,"ImagePath":"/content/img/browse/sm/","Children":[]}]
If I just copy this content into a script var it will also parse correctly.
However if i try and parse this content, as returned from the server, into an object I get an Uncaught Syntax error:
$.ajax({
type: "POST",
url: "/Browse/SubCategoryLister/",
data: { rfqID: parentRfqId },
dataType: "json"
})
.done(function (data) {
rp.hide();
sc.show();
console.log(data);
var status = JSON.parse(data);
console.log(status);
});
On the line
var status = JSON.parse(data);
However
console.log(data);
seems to produce a valid object that I can interrogate via developer tools:
So it seems like the data is already a json object? So Im not quite sure what is going on here. I thought it might have something to do with response headers but this payload is being sent down with an:
Content-Type:application/json; charset=utf-8
header just like in other pages in the application where i use JSON.parse(data); to create a JSON object from server returned data. So what is the difference here and why cant I parse it? If it's already a JSON object then how an where was it created?

You parse json twice. Data parameters function (data) is already javascript object, because you've used dataType: "json". From jQuery docs:
"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
You don't need to call var status = JSON.parse(data);. Just use data as you'd use result of JSON.parse.
Update
Also if your server return json content type, then jQuery will choose dataType to be "json". From docs:
If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

Related

Processing Response headers in a $http ajax call in AngularJS

I'm trying to process the response headers but not sure how to query for them. Here's the code snippet. I commented out a couple of lines when I attempted to read the headers and put some comments on what I noticed.
$http({
method: 'POST',
url: URL,
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function (data,status,headers) {
//Need to process the header to understand the server response
//console.log(headers()); //This returns null
//console.log(headers('custom-myapp-text');// Obvisouls returns null as the headers() returns null
deferred.resolve();
});
return deferred.promise;
};
As per their documentation, the 'headers' returns a function?? Not sure how to query for header values based on this.
data – {string|Object} – The response body transformed with the
transform functions.
status – {number} – HTTP status code of the response.
**headers – {function([headerName])} – Header getter function.**
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
I just tried it with a valid header and it was fine:
console.log(headers('Content-Length'));
This console logged 2 in my example. It will allow you access to any of the valid response headers.

sendAJAX data parameter in CasperJs

again, I got another problem with casperjs, now with sendAJAX function.
It says that sendAJAX has 5 parameters which are these followings :
url: The url to request.
method: The HTTP method (default: GET).
data: Request parameters (default: null).
async: Flag for an asynchroneous request? (default: false)
settings: Other settings when perform the AJAX request (default:
null)
So, it says the data method is object so, it should be filled with :
var data = new Object();
data.amount= 15;
and also with this one,
var data = {amount:15};
but there were no successful value send to my web service (always send 0 as value, but ajax request successful, even returning the json data) which has an url like this
"http://localhost:9000/TempCountryAmountREST/setCountryAmount"
It will be succeed if I direct bind my data variable to my url like this :
"http://localhost:9000/TempCountryAmountREST/setCountryAmount?amount="+amount
[UPDATE]
The TempCountryAmountREST is my controller name and setCountryAmount is my function inside my controller.
[UPDATE]
I forgot to include my usage of sendAJAX(), here is the code that I use :
return JSON.parse(__utils__.sendAJAX(wsurl, "POST" , data, false, { contentType: "application/json" }));
So how does I fill the data in the sendAJAX parameter?
Thanks in advance...
Sorry, I've found what the answer is.
I make some mistakes in contentType which I was set with contentType: "application/json" instead of contentType: "application/x-www-form-urlencoded" }
If we are looking about how ajax send the content from method send(), they were use x-www-form-urlencoded. See this for more detail
When we see through casperjs clientutils.js script, we should found how sendAJAX work.
On the `this.sendAJAX = function sendAJAX(url, method, data, async, settings) {
}
there are url construction logic which transformed our Object (if so) to x-www-form-urlencoded form. So that we need to set our contentType as application/x-www-form-urlencoded
Very well, thanks for your attention...

Access-Control-Allow-Origin trouble with Mootools

I've this error on my page but I can't solve it Access-Control-Allow-Origin.
Here is my code: I wrote this in my html file :
<div id="elapsed" data-url="http://myurl1.com/fr/chrono/">
And here is my:
var initChrono=function(){var e=$("dd"),t=$("hh"),n=$("mn"),r=$("ss"),i,s,o;(new Request.JSON({
url: 'http://myurl1.com/fr/chrono/',
callbackKey: 'callback',dataType: "jsonp",onSuccess:function(e){s=e.elapsed;o=e.status;a()}})).get();var a=function(u){i=s>0?"-":"";if(!u)s-=1;if(o==0){var l="00",c="00",p="00",v="00"}if(o==1||o==2){var g=Math.abs(s)
Can some help me?
I don't know how to work with this Jsonp
Access-Control-Allow-Origin warnings in this case would mean the url you are trying to load is not in the same domain as the page making the request.
You are using Request.JSON in your code above when what you need is Request.JSONP. This method injects a script tag to load the content as javascript wrapped in a method named with the value of callbackKey:
callback({ ... })
Your code example is incomplete and referencing undefined vars, so I am not entirely sure what you are doing here, but I think the request you are looking for is:
new Request.JSONP({
url: 'http://myurl1.com/fr/chrono/',
callbackKey: 'callback',
onComplete: function(data){
// do whatever
}
}).send();
Fiddle example: http://jsfiddle.net/GbTJp/
Mootools reference: http://mootools.net/docs/more/Request/Request.JSONP
If you are also developing the page that returns the JSON, you will need to read up on 'returning JSONP' in whatever server-side language you are coding in. This page will need to check if the get var 'callback' has been set, and if so, wrap the JSON string in a method defined by 'callback', then return with Content-Type: text/javascript.
http://en.wikipedia.org/wiki/JSONP

Reading cross domain csv file using JSONP and AJAX

Trying to read cross domain csv file :
remote_url = “http://www.example.com/buglist.cgi?bug_status=NEW&columnlist=bug_id%2Cshort_desc&query_format=advanced&ctype=csv";
$.ajax({
url:remote_url,
type:"get",
cache: false,
dataType: "jsonp",
success:function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
Although getting 200 status from server, It always going into error callback handler and logging a JavaScript syntax error:
SyntaxError: missing ; before statement 6230,"this is a ""short description"", blah blah blah..
My CSV file has two columns “bug_id” and “short_desc” with following values:
bug_id = 6230
short_desc = this is a "short description", blah blah blah..
I know the error is because of double quote in description, but I don’t know the solution. I tried “YQL” to convert CSV to JSON but it returned null as a result, may be because of an error.
The JSONP technique expects the response to be JavaScript. This is why you're getting a JavaScript error; it's trying to execute the CSV content as JavaScript.
JSONP works by defining a callback function in the server, adding a script tag with a URL that tells the server what function it will call, then the server responds with JavaScript that calls that function with the data as a parameter.
The destination URL must support this protocol in other words. You can't just use JSONP for any arbitrary request.
You may need to use a different technique to get your data, like a same-domain proxy that does the HTTP request to the server. If you are able to change the code at example.com, you have even more options.

Making jQuery $.ajax call to Twitter API 1.1 search

Here is a very simple example of a call to Twitter's search API to get all tweets from a tag known to have tweets, #fml.
I believe I am correctly using the application-only authentication as explained here: https://dev.twitter.com/docs/auth/application-only-auth (see Step 3 for example of a call)
I am being asked for a solution that does not involve any server-side code so I am including the bearer code in the javascript, which isn't good to begin with, but....
I would expect this code to work. Instead it produces the error '400 (Bad Request)'. Any ideas?
$.ajax({
url: "https://api.twitter.com/1.1/search/tweets.json",
dataType: "jsonp",
data: "q=%23fml",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Bearer XXmyBearerCodeXX");
},
success: function(json){ alert(json); }
});
EDIT 1 - Validated Twitter call
Using hurl.eu I was able to get a successful response from the API with the above query and Authorization header, so I assume this means my Twitter call is correct, just not set up correctly within jQuery.ajax(), but I just don't see what is missing.
You cannot set request headers using AJAX calls with dataType JSONP.
See this question: Set Headers with jQuery.ajax and JSONP?
The best solution is to use a server-side proxy to do the search for you. I know you are looking for a client only solution, but with this restriction, and with no way around CORS, this is how it seems to be done today for the Twitter API.
Edit It may be possible using a proxy like Yahoo's YQL if you don't have access to one.
on your severside create a jsp or servlet and from the client side make a JSON call to the .jsp/servlet and that will return back the json object to the javascript. In serverside use the twitter4j api.
sample code:
`
$.getJSON(http://localhost:8080/test.jsp?callback=?",
{
jspqueryStr : queryStr,
jspgeocodeStr : geocodeStr,
lat:latStr,
lan:lngStr,
radius:radiusStr,
}, displayResult);
//This function returns the data as json object from server.
function displayResult(data) {}
In the jsp the code is like below
<%
String jspqueryStr = request.getParameter("jspqueryStr");
String jspgeocodeStr = request.getParameter("jspgeocodeStr");
String diseasename = request.getParameter("jspqueryStr");
String lat = request.getParameter("lat");
String lan = request.getParameter("lan");
String radius = request.getParameter("radius");
Gson gson = new Gson();
String json = gson.toJson(tweetList);
json = request.getParameter("callback") + "(" + json + ");";
out.println(json);
public List<Status> searchstream(){
//here all the twitter4j api code to get the data
retrun tweetList;
}
%>
`

Resources