Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Have you tried</p> <pre><code>$.ajax({ url: this.hostName + url, type: 'POST', headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') } data: { param : 'something' }, dataType: 'json' }); </code></pre> <p>And then in your controller params[:param] will give you 'something'.</p> <p>If you are interested to know why you need all that X-CSRF-Token stuff, <a href="http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf" rel="nofollow">this</a> is a good read. Basically, Rails automatically includes that token in your page to keep your application safe. If you inspect any page of your site, you'll see in the head of your HTML document something like this:</p> <pre><code>&lt;meta content="guma1QdmO9Tn9SB4yV4DonkY4xf4Sy6lIvrFyHIaR1U=" name="csrf-token"&gt; </code></pre> <p>This is created by the line <code>&lt;%= csrf_meta_tags %&gt;</code> included in your <code>application.html.erb</code> file.</p> <p>Rails automatically includes this token in regular non-GET requests to keep them safe. But with javascript and ajax, you have to do this manually by searching the DOM for the token with the jQuery function <code>$('meta[name="csrf-token"]'</code>.</p> <p>Now, this isn't very efficient because you are searching for that token every time you are making a request. So what you should do, is use ajaxSetup, like this:</p> <pre><code>$.ajaxSetup({ type: 'POST', headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') } dataType: 'json' }); </code></pre> <p>And now, whenever you want to send a request, all you need is this:</p> <pre><code>$.ajax({ url: this.hostName + url, data: { param : 'something' } }); </code></pre> <p>EDIT: Ah, I see. What do you get when you do <code>alert(this.hostName + url)</code>? And how are you declaring your routes? Because if I remember correctly, you can use relative urls instead of absolute urls, you don't need the root part. Here's an example:</p> <pre><code># routes.rb post "relative_url" =&gt; 'controller#action' # file.js $.ajax({ url: "relative_url", data: { param : 'something' } }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload