1

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.

2
  • Are you using jQuery's document.ready( ... ) callback? Commented Mar 7, 2017 at 1:12
  • No I am not. I was under the impression that was only necessary when attaching listeners via the $("#id").submit() syntax. Commented Mar 7, 2017 at 1:16

2 Answers 2

2

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

$(document).on('turbolinks:load', function() {
  // your code
});
Sign up to request clarification or add additional context in comments.

2 Comments

That event is triggering but it still is not working. I think the problem has to do with how I'm attaching the listener
No. There wasn't anything
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.