Encoding error in ajax request to rails application - ruby-on-rails

I am working on an application in which i have a situation to send text data to backend through Ajax call.
But when the text "%" occurs in the text to be sent through ajax, i get the below response from my rails app
Internal Server Error
invalid %-encoding
i tried adding escape characters infrot of % symbol, but its not useful.
Any suggestion on this issue would be helpful.
Jquery ajax call used :
thanks,
Balan

You can pass jquery an object for the data option and it should correctly escape it for you:
$.ajax({
type: "POST",
url: "/controller",
data: {
text: text_from_text_area,
current_poster: current_poster
},
success: function(data){
alert(data);
}
});
See the docs here: http://api.jquery.com/jQuery.ajax/

Related

Grails: Why is the JSON from a GET request not getting bound to the command object in the controller action?

Note: I'm using Grails 2.5.5.
This is my method in the controller (I know save() shouldn't be a GET, but I'm just testing things out):
def save(Test cmd) {
println cmd.duration
println params.duration
}
This is my client code:
let data = JSON.parse($('#req').val());
$.ajax({
url: url,
data: data,
method: 'GET',
contentType: 'application/json'
});
When this flow is executed, on the controller side, cmd.duration does not print what was sent from the client side (instead it's the default value of zero since duration is typed as an int). On the other hand, params.duration does print what was sent from the client side.
So this indicates that it's not a problem with how the data is getting sent, but instead has to do with some data binding issue?
Also, just for reference, POST works perfectly fine with the above server-side code. The command object gets populated appropriately as long as I change the client code accordingly (changing method type and stringifying the JSON):
let data = JSON.parse($('#req').val());
$.ajax({
url: url,
data: JSON.stringify(data),
method: 'POST',
contentType: 'application/json'
});
I know there are similar questions out there, but it seems like most of them deal with issues with POST requests. So this is a bit different.
Any help is appreciated!
It looks like I just needed to remove the contentType in the ajax call on the client side for the GET request. Once I did that, everything worked as expected.
Not sure if that is expected behavior, but it works for me for now.

Render FileContentResult using javascript

I have an Web API written in Core 2 that returns a FileContentResult.
You need to do a GET with an Auth Token in the header for it to work.
If you try it with postman, the file renders fine and it also renders well in an MVC View.
Now we have an external Salesforce system trying to consume the API but due to the limitations of the APEX language they have to use Javascript to inject the token into the GET method.
Example code:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'https://file-store.com/document/{! docId}',
headers: {
'Authorization': 'Bearer {! oauthToken}',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).done(function (data) {
console.log(data);
});
});
This seems to work as the "data" that is returns contains a file - or at least an array of squiggles that look like the file serialized.
However, there seems to be no way to get the web view to render this.
I tried using embed
var object = '<embed scr="' + data + '" />';
or using an iframe
$('#iFrame').html(data);
or
$('#iFrame').html(object);
and lots of other things but so far had no success.
I do understand that in MVC this is simple, but is it at all feasible using javascript?
We do successfully receive the file, and we do have the data in memory, I just need way to render it on the browser.
Any suggestion is very welcome

ajax call to database in rails

I'm trying to get rows that match a var, In my case a url. in the database and return the whole row as a json format.
Basically if url in table1 matches the url under eventurl in table2. Then the whole row is passed through to the ajax request as a jsonformat.
Heres what i have so far.
Routes.rb
resources :gig do
scope constraints: { format: "json" } do
get :gigdata, on: :member
end
end
In my ajax call i have this
url: 'gigdata/' + gigurlofevent , (no need to include the whole url ajax file here as its working elsewhere)
and in my controller i have this
respond_to :json, only: :gigdata
def gigdata
gig = Gigstable.where(eventurl: (params[:gigurlofevent]))
render json: gig
end
Now at the moment, I can't get into the gigdata with a byebug.
I'm wondering what i need to do/ what ive missed
Thanks
Sam
edit
Heres the start of the ajax call down the the success function
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-Type", "application/json");
},
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'gigdata/' + gigurlofevent ,
success: function(json) {
debugger;
Common problem:
You wrote:
(no need to include the whole url ajax file here as its working
elsewhere)
Actually you need to include complete code because common problem lays in Content-Type field. You need to specify content type of request in header like 'application/json'.
I am testing my backend api with curl
For example:
curl http://localhost/api/v1/some_action -H 'Content-Type: application/json' -vvv
Last parameter -vvv very useful to debug requests because it makes curl to output request and response with headers in console.
Another way to debug ajax
Open developer tools (for chrome it's: F12 or ctrl+shift+i), click on network tab and click on XHR filter button. Reload page with ctrl+r and execute your ajax request one more time. Information about your ajax request will appear in the window below filters. Now you can check out what kind of data comes from server and whats going wrong.
Golden rule
Rails server outputs all requests in console. Don't be shy to read output when something works not like you expected.

JIRA Worklog API not working

I am trying to log work in JIRA using the Web API :-
My data is:
var post = {};
post.commment = "Test";
post.timeSpent = "6h";
My Ajax call is:
$.ajax({
url: lv_url,
type : 'POST',
data : post,
headers: {
Accept : "application/json; charset=utf-8",
},
contentType: "application/json; charset=utf-8",
dataType : 'json',
xhrFields: {
withCredentials: true
},
async: false,
success : function(data) {
}
});
https://jiraserver.co/rest/api/2/issue/SOCOMPT-1575/worklog
"GET" call is working fine but when i try to POST i get the error:-
1) OPTIONS https://jiraserver.co/rest/api/2/issue/SOCOMPT-1575/worklog 500 (Internal Server Error)
2) XMLHttpRequest cannot load https://jiraserver.co/rest/api/2/issue/SOCOMPT-1575/worklog. Invalid HTTP status code 500
These are the 2 errors is get.
Please Help Guys i really need to get this working.
Thanks in advance,
Vishesh.
I was also strugging on this one as I kept getting HTTP 500 when trying to post to the worklog endpoint.
if you are able check the jira server logs (under logs/catalina.out)
jira seems to be very picky with the iso8601 date format
Try setting also the "started" timestamp in your payload as I believe this is required (for the API like the web UI) even if the documentation is not really clear on that.
post.started = '2015-02-25T14:01:30.000-0500';

Execute controller action with Dojo sending the AntiForeignKey in MVC5

How can I execute a controller action in ASP.NET MVC4 sending the anti foreign key too?
My request is formed as follow code snippet:
var _antiForeignKey = dojoQuery('input[name="__RequestVerificationToken"]', dojo.byId('#__AjaxAntiForgeryForm'))[0].value;
xhr.post({
url: 'Account/LogOff',
handleAs: 'json',
contentType: 'application/json',
postData: '__RequestVerificationToken=' + _antiForeignKey
});
And I receive an error from server with a html which contains the
The required anti-forgery form field "__RequestVerificationToken" is
not present.
message as response. Obviously, the action in the controller is not executed.
I've seen this post: jQuery Ajax calls and the Html.AntiForgeryToken(), which answers my question but using jQuery.
I have got to execute the controller action by using the previous code snippet but modifying the value of two parameters, 'handleAs' and 'contentType':
var _antiForeignKey = dojoQuery('input[name="__RequestVerificationToken"]', dojo.byId('#__AjaxAntiForgeryForm'))[0].value;
xhr.post({
url: 'Account/LogOff',
handleAs: 'text',
contentType: 'application/x-www-form-urlencoded',
postData: '__RequestVerificationToken=' + _antiForeignKey
});
As you can see, I've changed the 'handleAs' property because we are not handling json data in the response, and the 'contentType' to specify we are sending other type of data as request's parameter.

Resources