I'm trying to read XML with AJAX, all the data are took from a well formed XML file and then are sended to client page through AJAX. But xmlhttp.responseXML always remains unusable.
Here's my controller :
def fileGetter = {
if (params.fileId) {
try {
String resultStr = fileManipulatorService.fileProvider(params.fileId).getText()
println resultStr
render(text: resultStr, contentType: "text/xml", encoding: "ISO-8859-1")
response.sendError(200)
}
}
}
resultStr contains the proper xml, on my webpage xmlhttp response text contains the correct xml data too while xmlhttp response xml contains nothing. How can I send true xml data to my client page and exploit it? I need too work with an XML response. (I tried to send a new xml object created from the string, I tried to return the original file, but none of these methods worked)
(I'm using Chrome)
Thank you
I'm not sure if this is the cause of your problem, but this code doesn't make any sense
render(text: resultStr, contentType: "text/xml", encoding: "ISO-8859-1")
response.sendError(200)
Grails does not return after executing render so it will execute the response.sendError after returning valid data. Replace these lines with
render(text: resultStr, contentType: "text/xml", encoding: "ISO-8859-1")
You may try
render resultStr as XML
It should work, thougt I don't really like these converters.
Related
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.
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...
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).
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
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;
}
%>
`