Reading cross domain csv file using JSONP and AJAX - 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.

Related

Why does JSONP work with JSON-formatted data?

There is a URL I am using in a project of mine, that is working just fine. I make a request from one web server, to a different IP address, invoking a page that outputs data in this format:
[{"PhoneNumber":"+123456789","Name":"Mark"},
{"PhoneNumber":"+123456789","Name":"Josh"},
{"PhoneNumber":"+123456789","Name":"Alex"},
{"PhoneNumber":"+123456789","Name":"John"},
{"PhoneNumber":"+123456789","Name":"Sean"}]
And I can get and process that data with a function call such as this:
$.ajax({
url: serverAddress + "/getpeople",
dataType: "jsonp",
timeout: 4000,
success: function(response) {
for(var i in response) {
alert(response[i].Name);
}
}
});
Here is what's confusing me. From what I've learned about JSONP so far, it isn't actually data, but is instead a function. So the response should be wrapped in a function call, such as callback(), and then I could implement a function callback(data) {} in my project to process the data.
But in this case, the data seems to be just JSON data, which I think should cause a cross-origin error to be generated? But it doesn't.
When I try to call another URL from the same server, fetching an ordinary plain text file, then I do get a cross-origin error, which complains in the console:
Reason: CORS header 'Access-Control-Allow-Origin' missing
But the original getpeople URL does not have that header either. When I examine the response headers in Firefox's document inspector, all of the headers are:
Connection: "close"
Content-Type: "text/html;charset=utf-8"
Date: "Mon, 5 Oct 2015 08:29:07 GMT"
Server: "ServerName/1.1.10011.2211"
So:
The data is not formatted as a JSONP callback
It is served from a different IP address than the web application
The response doesn't have a Access-Control-Allow-Origin header
Why does this work?

Blueimp jQuery file upload force iFrame Transport server response

I am using Blueimp JQuery File Upload, with the option forceIframeTransport: true, I am able to upload the file and form fields to a cross domain endpoint for processing.
However, the server response is something bother me for a long time.
I have come across a online material about the library:
http://missioncriticallabs.com/blog/lessons-learned-from-jquery-file-upload
I have followed the link's instruction but failed to get the server response correctly.
Here is my code:
jQuery("#newFile").fileupload({
url: "https://mydomain/cgi-bin/get_file.cgi",
forceIframeTransport: true,
type: "POST",
cache: false,
contentType: false,
processData: false,
autoUpload: false,
replaceFileInput: false
done: function(e, data) {
console.log("done");
console.log(e);
console.log(data.result);
}
});
For now, my server endpoint is to print the JSON response out only:
#!C:/Perl64/bin/perl.exe
use CGI;
use JSON;
print "Content-type: text/plain; charset=iso-8859-1\n\n";
#print header("application/json;charset=UTF-8");
my %rawText = (message => "Processed");
my $json = encode_json \%rawText;
print $json;
I have tried to print the header as "text/plain" and "application/json", but I cannot get the server response in my "done" function in the JS code.
My console.log(data.result) is always print "undefined".
I am quite fresh to the library and the concept behind,
so I will be much appreciated if anyone could guide me to use the library.
Thank you very much.
In order to make the widget work with Perl, you have to implement a custom server-side upload handler. Your CGI script must return a JSON reponse in the format described in the documentation.
Fortunately, someone has already done the work for you. Have a look at the module jQuery::File::Upload on CPAN.

Parsing Json results in uncaught syntax error

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).

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

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