0

I'm trying to add some additional data to a form in my laravel blade using js and ajax post, but I can't get the form to submit. I've stripped everything else out to try to find what's wrong, but I'm mystified. Can anyone help? My blade looks like this;

@extends('layouts.app')

@section('content')
 <div class="container">
  <div class="row justify-content-center">
   <div class="col-12 col-md-6 mt-5 mb-2">

    <div class="card">
     <div class="card-body">
      <form id="payment-form">

       <button id="card-button" class="btn btn-lg btn-block btn-success">
        <span id="button-text"><i class="fas fa-credit-card mr-1"></i>{{ __('Add Payment Method') }}</span>
       </button>

      </form>
     </div>
    </div>

   </div>
  </div>
 </div>
@endsection

@section('javascript')

<script>

 const cardButton = document.getElementById('card-button');

 var form = document.getElementById('payment-form');

 cardButton.addEventListener('click', function(event) {
  // event.preventDefault();
  console.log('On click check');

  var payment = '1234';
  $.ajax({
   type: "POST",
   url: "/payment-post",
   data: {
    payment: payment,
    '_token': $('meta[name="csrf-token"]').attr('content'),
   },

  });
 });

</script>
@endsection
Dan E
  • 167
  • 1
  • 11
  • Just curious -- any reason you're doing JS event handling and not just using a standard form and let the browser do the default things? – Chase Jun 07 '20 at 18:56
  • There will be a Stripe API call in the middle of it, that needs to wait for a response, but the form was just submitting and skipping the preventDefault, so I’ve pulled everything else out to simplify it. – Dan E Jun 07 '20 at 19:15
  • Do you receive any response in your browser's network tab when you click on your button? – ettdro Jun 07 '20 at 19:40
  • It looks like the whole event listener block is not triggering for some reason. I've removed event.preventDefault(); as I don't think I need this and have added console.log('On click check'); directly after the click event, but it never shows. – Dan E Jun 08 '20 at 09:47
  • [Checking this URL, hopefully it is useful for you](https://stackoverflow.com/questions/37608965/how-to-call-asp-net-web-api-base-on-ajax-with-get-post-and-token-key/37608966#37608966) – Willie Cheng Jun 08 '20 at 10:25

2 Answers2

0

You have to use like this

var payment    = '1234';
var CSRF_TOKEN =  $('meta[name="csrf-token"]').attr('content');

$.ajax({
    type: "POST",
    url: "{{url('')}}/payment-post",
    dataType: "text",
    data: {
        payment: payment,
        _token:  CSRF_TOKEN
    },
    success: function (response) {
        //Do something
    }

});
A.A Noman
  • 5,244
  • 9
  • 24
  • 46
0

In the end I tracked this down to 'defer' being present in the script tag in the header, which was stopping all the event listeners from working. Once I changed it to this

<script src="{{ asset('js/app.js') }}"></script>

everything working fine.

Dan E
  • 167
  • 1
  • 11