Malformed JSON response being sent by Play Server - ajax

I am using jquery Ajax to send data to the client and get reply from the Client.
I am using Play Framework as backend.
AJAX:
$.ajax({
type: "GET",
url: '/authenticate',
data: {'type':type, 'redirectURL':getRedirectURL},
contentType: "application/json; charset=UTF-8",
dataType: 'json'
}).success(function( msg, txtStatus, jqXHR) {
console.log("asdasd5= "+msg);
console.log("asdasd5= "+msg.authUrl);
console.log("asdasd5= "+jqXHR.authUrl);
window.location = msg;
});
SERVER DATA CREATION:
response.setContentTypeIfNotSet("text/plain; charset=UTF-8");
Logger.info("response content type ="+response.contentType);
renderJSON("{\"authUrl\": " + authUrl +"}");
The server is sending something like "www.mywebsite.com/yoohoo/auth/1231"
But the response received by Ajax is �����������������{"authUrl": www.mywebsite.com/yoohoo/auth/1231}
DUE to these weird character the JSON response received cannot be parsed by jQuery.
Kindly, help on this.
Thanks

I noted that you are sending back (server-side) a MIME type of "text/plain". Perhaps switch to "application/json". Additionally, you could take the return string and strip any junk from the string before parsing the JSON out on the client side. This would help sanitize in case you change something again server-side and accidentally introduce new/different "junk".

Related

Ajax request error with elasticsearch

I simple make get req with ajax to elasticsearc to get all indices,
in browser it works here:
its same in my ajax, I expected the json data in browser return to my success method but failed:
Response is not JSON, you can change the response to a JSON in your server program.
It should work if you replace json by jsonp in your dataType parameter, like this:
$.ajax({
url: "http://localhost:9200/dicoms/dicoms/_search",
dataType: "jsonp", <--- change this
type: "GET",
success: function(data) {
...
});

Unable to download csv file even though content coming in response header

I have this stupid problem that I am seeing my csv data in the response header but it's not downloading the csv.
On client side, I have a button and on it's click an ajax post request is fired like
$.ajax({
url: 'xyz/GenerateCSV',
type: 'POST',
data: postData,
contentType: "application/json; charset=utf-8"
});
On the server side I have set Response as
Response.AddHeader("content-disposition", "attachment;filename=ListExport.csv");
Response.ContentType = "text/csv";
The http response header is coming fine as -
Cache-Control:private
content-disposition:attachment;filename=EncounterListExport.csv
Content-Encoding:gzip
Content-Type:text/csv; charset=utf-8
Date:Mon, 22 Sep 2014 14:18:05 GMT
Server:Microsoft-IIS/8.0
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:4.0
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?
Any idea what's going on? I did not make use of any Form or 'submit' button.
Thanks,
Vaibhav
Regarding your comment above:
It fails in the sense that nothing happens.
That's kind of incorrect. By your own admission, "Response content has data." Therefore something does happen. The response sends the data to the client.
The question is, what do you do with that data? According to your code, nothing:
$.ajax({
url: 'xyz/GenerateCSV',
type: 'POST',
data: postData,
contentType: "application/json; charset=utf-8"
});
Look at the documentation for $.ajax(). You need to provide it with some code to invoke after the response is received. That code would handle the response in some way. Something like this:
$.ajax({
url: 'xyz/GenerateCSV',
type: 'POST',
data: postData,
contentType: "application/json; charset=utf-8"
}).done(function (response) {
// use the data from the response
}).fail(function (response) {
// handle an error from the response
});
What you do with that data is up to you. It's structured CSV data, I imagine there exists some JavaScript library out there which can parse that easily. If you want to save the data to a file then you're going to have to prompt the user in some way (which could involve some trickery and workarounds) or save it to local storage. JavaScript can't write directly to the file system (for obvious security reasons).

Attach requestbody to jQuery ajax

I am trying to attach data to my requestbody while sendign using jQuery ajax.
If I tried to do it using the extension RESTCLient is either firefox or chrome it works fine, which means that my method on the serverside is working fine.
That is why I am pretty sure that it the ajax call I am making
$.ajax({
url: 'lingosnacks/delete/'+ id,
type: 'POST',
data: $('#email').val() + $('#password').val()
dataType: "json",
success: function(data) {
console.log("FILL| Sucess| ");
console.log("FILL| Sucess| Data| " + data);
fill(data);
}
});
The data line is wrong, it should be very similar to a JSON string, like this:
data: {email: $('#email').val(), password: $('#password').val()},
You need to have the data you are sending in this format:
email=blah%40blah.com&password=pass123
You can do that with jQuery using $('form').serialize()
Also, you are missing a , after your data string in the Ajax call.
Actually data param in jQuery Ajax method is for sending url params.
You can send the same by appending then into the url but to make the code more readable e and organized i would prefer to use data variable.
So your data content should look like :
data : "email="+$('#email').val()+"&password="+$('#password').val();
I am not pretty sure if sending params like a json object will work or not because i never used it.

Sending javascript dictionary with array values via ajax through a bookmarklet

I have data that I want to send through an ajax GET request in following format -
{'url':['www.google.com','www.yahoo.com']}
Here is the ajax request - $.ajax({type:'GET',url:'http://www.example.com/',processData:false,data:JSON.stringify({'url':['www.google.com','www.yahoo.com']})
And since I am doing this in a bookmarklet it looks like this -
<a href="javascript:function iprl5() { $.ajax({
type:'GET',
url:'http://www.example.com/',
processData:false,
data:JSON.stringify({'url':['www.google.com','www.yahoo.com']}),
dataType:'json',
contentType: 'application/json',
success: function(json){$('#confirm').html('<p>Thanks!</p>');},
error: function(){$('#confirm').html('<p>Something went wrong :( please reload</p>');} })}} iprl5(); void(0)">BLAH</a>
The problem is that when I hit the bookmarklet browser sends a get request like this -
GET http://www.example.com/?{"url":["www.google.com","www.yahoo.com"]}
I want to send a json as a string but unable to do so, I also tried encodeURIComponent to encode string but that didn't work either.
I would try: data: 'url=' + JSON.stringify(['www.google.com','www.yahoo.com']),

Not able to send POST request through jQuery Ajax

I was trying to send an ajax request as POST request. But when i verified it on httpFox on firefox, the request is sent as GET. I tried both $.ajax() and $.post().
Many had a query regarding the same and had missed the "type" in $.ajax(), but even if i mention the type as "POST", the request will be of type GET.
Here is my code:
$('.test').click(function(){
alert("clicked");
$.ajax({
type: "POST",
url: "www.testsite.com",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
Any idea why it happens?
A possible cause might be the fact that you are trying to send an AJAX request to a different domain: www.testsite.com than the one hosting your page which of course is not possible and jQuery tries to use JSONP instead which works only with HTTP GET.

Resources