Rails post can't verify CSRF token authenticity - javascript

I've check this WARNING: Can't verify CSRF token authenticity rails
but I still can't figure it out why it cause this error.
Here is my ajax
$.post(
"<%= ajax_chats_path %>",
{timestamp :(new Date()).getTime(),msg: $('#msg').val()},
function (json) {
console.log(json);
});
If I add this
skip_before_action :verify_authenticity_token
in controller, it can solve this problem.
I am not sure it's the right way to do, because it looks like it may encounter some security attack.

You're missing the CSRF token in your Ajax call. You'll need to use a long-form $.ajax call, and add this:
beforeSend: $.rails.CSRFProtection
Instead of $.post, you can use the $.ajax equivalent, which would look like this:
$.ajax({
type: "POST",
url: "<%= ajax_chats_path %>",
beforeSend: $.rails.CSRFProtection,
data: {
timestamp: (new Date()).getTime(),
msg: $('#msg').val(),
beforeSend: $.rails.CSRFProtection
},
success: function (json) {
console.log(json);
}
});
You should also strongly consider adding the datatype field to the call, so that jQuery knows the disposition of the response and can handle it accordingly. You can choose from any of "xml", "json", "html", "script", "jsonp", or "text". See the jQuery.ajax() API documentation for more details.

This is worked for me,
$.ajax({
beforeSend(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},

Related

Ajax request failing?

I am trying to retrieve json data from an api.
It keeps failing, but when I look in the Net tab of Firebug I can see that the GET request executed and returned the correct data. Am I doing something wrong or does anyone have tips on how to debug this?
Edit: Have changed to dataType json and error status code is 0
Thanks
$.ajax({
url: 'http://localhost:55894/api/Test/All',
data: {
format: 'json'
},
error: function () {
alert('Error');
},
dataType: 'jsonp',
success: function (data) {
alert('Ok');
},
type: 'GET'
});
From the info you provided the reason it is failing is because you dont have a cross domain access policy setup. Because you are using different ports to host the website and the API you are running into this issue. You can either setup a crossdomain.xml with the proper security settings or you can move both the API and the webserver to the same port.
Have a look at this for more info: http://en.wikipedia.org/wiki/Same-origin_policy
u can try this way:
$.ajax({
type: 'GET',
url: 'url api here',
beforeSend: function() {
},
success: function(data) {
},
error: function(xhr) { // if error occured
},
complete: function() {
},
dataType: 'json'
});
JSON and JSONP are different. If you are using JSONP, the server side must be prepared to support it. Doesn't look like you are using JSONP.
So just change dataType to 'json', as you are "trying to retrieve json data".

Ajax jquery call to GET application/x-javascript

How do I get content of "application/x-javascript" using jquery Ajax call?
As it keep getting me null content.
What I am trying to use for now:
$.ajax({
dataType: "json",
contentType: "application/x-javascript;charset=utf-8",
url:the_url,
async:false,
success:function(r){
console.log("el result" + r) ;
response = r;
}
});
This:
dataType: "json",
tells jQuery to ignore what the server claims it is sending back and to process the result as JSON. JavaScript isn't JSON, so this breaks it.
Remove that line.
Then you should get the data in the success function.
Asides:
This:
contentType: "application/x-javascript;charset=utf-8",
claims you are sending JavaScript. You aren't making a POST request, so you aren't sending anything. Remove it.
Even if you were sending JavaScript to the server, the application/javascript MIME type hasn't been experimental since 2006, so it shouldn't have the x- prefix on it.
async:false, is a terrible idea. It locks up the JS event loop waiting for the response. You shouldn't use it.
response = r;: assigning data to globals is usually a terrible idea. Process the data in the success event handler instead.
Try this out :
$.ajax({
url: 'my/url',
type: 'GET',
data: 'test=mytest&test2=mytest2',
success: function (data) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
And read the documentation, to see what each parameter is made for :
http://api.jquery.com/jquery.ajax/

jquery ajax : what is the actual request sent?

What is the actual url sent to the server when I use the jquery ajax? And how do I access that value? For example, consider the following code:
<script>
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: {name:'Smith',age:10},
success: function(data) {
...
}
beforeSend: function(){
console.log(url);
// what do I put here to see what is being sent
// I am expecting to see "response.php?name=Smith&age=10"
}
...
So essentially what variable holds "response.php?name=Smith&age=10".
Thanks.
No variable holds
response.php?name=Smith&age=10
because you aren't sending the data as a query string. This would happen if you issued a GET request, but doesn't with a POST request.
You're sending the data in the request body of an HTTP post. The data is the data that you assigned to the data parameter. You don't need to round-trip it through jQuery's ajax methods. You've got it already. It's:
{name:'Smith',age:10}
does jQuery's interpretation of your data really matter?
The settings object is fully populated when beforeSend is called:
beforeSend: function(jqXHR, settings) {
console.log(settings.url);
console.log(settings.data);
}
$.ajax({ type: "POST", ... }) will log
response.php
name=Smith&age=10
and type: "GET"
response.php?name=Smith&age=10
undefined

Paraimpu HTTP POST REQUEST

I am trying to make a http POST request from my Jquery mobile application(hosted on Amazon S3) to "http://paraimpu.crs4.it/data/new" to insert data into my sensor on the Paraimpu site. This is the request I'm making:
data = "Test";
valueToSend = '{"token":"c9d1cee6-da40-4e97-afc8-209045786b04","content-type":"application/json","data":' + data + '}';
$.ajax({
url: "http://paraimpu.crs4.it/data/new",
type: "POST",
data: valueToSend,
dataType: "json",
crossDomain: true,
contentType:"application/json",
success: function(){
alert('Success');
}
});
I keep getting
XMLHttpRequest cannot load http://paraimpu.crs4.it/data/new. Origin
"http://webappz.s3-website-us-east-1.amazonaws.com" is not allowed by
Access-Control-Allow-Origin.
I know this is because of the cross domain policy, but how can I get around this? The instructions on the paraimpu page are pretty vague and just says:
Push new sensor data doing an HTTP POST to:
http://paraimpu.crs4.it/data/new
with content like: {"token":"c9d1cee6-da40-4e97-afc8-209045786b04",
"content-type":"text/plain", "data":RAW DATA}
data = "Test";
valueToSend = '{"token":"c9d1cee6-da40-4e97-afc8-209045786b04","content-type":"application/json","data":' + data + '}';
$.ajax({
url: "http://paraimpu.crs4.it/data/new",
type: "POST",
data: valueToSend,
dataType: "jsonp", //set datatype to jsonp
crossDomain: true,
jsonp: false,
contentType:"application/json",
success: function(){
alert('Success');
}
});​
These are the parts that you were missing:
dataType: "jsonp": The type of data that you're expecting back from the server. "jsonp", loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
jsonp: false: Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }
More on this here: jQuery.ajax()

Jquery Ajax Problem

Hi all;
var v_name = null;
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
$.data(document.body, 'v_name', mydata);
}
});
v_name = $.data(document.body, 'OutputGrid');
alert(v_name);
first alert undefined before alert work why ?
In addition to the other answers, also keep in mind that by default .ajax GET requests are cached, so depending on your browser, it may look like all of your requests are returning the same response. Workarounds include (but are not limited to): using POST instead of GET, adding a random querystring to your url for each request, or adding 'cache: false' to either your ajax call or to the global ajaxSetup.
To make it work, you have to place the alert() in the success function:
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});
AJAX calls are asynchronous, and therefore JavaScript would evaluate alert(v_name); before the server responds to the AJAX call, and therefore before the success function is called.
Your AJAX applications must be designed in such a way to be driven by the AJAX response. Therefore anything you plan to do with mydata should be invoked from the success function. As a rule of the thumb, imagine that the server will take very long (such as 1 minute) to respond to the AJAX request. Your program logic should work around this concept of asynchrony.
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});

Categories

Resources