Sam M
Sam M

Reputation: 660

Rails 5 load JS with turbolink

I am having a hard time getting javascript to work without reloading a page. I believe the problem has to do with turbo links.

I am setting an onsubmit listener to a form like this

<%= form_for @cart, url: cart_path, html: {onsubmit: "addCart(event, #{@product.id})"} do |c| %>

I am then submitting the form via ajax like this

function addCart(event, id){
   event.preventDefault();
   var quantity = $("#"+id+'_product_quantity').val()
   $.post('/cart/add', {
     product_id: id,
     quantity: quantity
   }, function(data, status, xhr){
     if(xhr.status !== 200){
       alert("There was an error. Please try again")
     }else {
       $("#"+id+'_product_submit').val("Added");
     }
   })
}

Everything works perfectly when I reload the page but when I go to the page via a link the javascript does not get called. The weird thing is that the event.preventDefault() is working. When I remove the javascript completely the form will submit like a normal html form. I am a pretty new to jquery and cannot figure out how to get the javascript to load.

Upvotes: 1

Views: 633

Answers (2)

Sam M
Sam M

Reputation: 660

So this had to do with turbolinks. I couldn't figure out how to make it work with turbo links so I removed the //= require turbolinks line from assets/javascripts/application.js file.

Upvotes: 0

Mark
Mark

Reputation: 11028

This could be a turbolinks issue. In your javascript file, surround your javascript code with

$(document).on('turbolinks:load', function() {
  // your code
});

Upvotes: 2

Related Questions