Jack022
Jack022

Reputation: 1257

Jquery button doesn't submit a request

I have the following code:

<script>
$(document).ready(function() {
  $('#manage').click(function() {
      swal({
          title: 'Choose your settings',
          type: 'info',
          html:"<form method='post' id='set'>{% csrf_token %}<input type='text' class='set-pref' placeholder='Enter your preference' name='input_val' id='settings'><button name='button' class='btn btn-danger btn-sm f-14 mr-1' type='button'>Set</button></form>",
          showCloseButton: false,
          showCancelButton: false,
          focusConfirm: false,
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Go forward',
      });
    });
});
</script>

<button name="button" id="manage" type="submit" class="btn btn-danger btn-sm f-14 mr-1">manage</button>

When the button is hit, a panel shows. The problem is that the form inside the panel is not being submitted by the button. When i fill the input field and hit the button, nothing happens. Changing the button to type='submit' won't work either, because it will just refresh the page without submitting anything. I'm sure the problem is inside my previous block of code, but here is how i'm sending the request anyway:

<script>
$(document).ready(function () {
  $("#set").submit(function (event) {

      callAJAX(viewsurl,
       {"X-CSRFToken": getCookie("csrftoken") },
       parameters={'settings': $('#settings').val()},

      'post',
       function(data){


       }, null, null );
  return false; 
  });

});

</script>

Upvotes: 2

Views: 54

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206048

Your problem seems that you're dynamically creating a FORM that is still not existent on the page via Laravel's Swal html:.

My suggestion is to dynamically assign your handler using the .on() method:

jQuery(function ($) { // DOM ready and $ alias in scope

  $(document).on('submit', '#set', function (event) {
    event.preventDefault(); // Prevent browser submit form

    callAJAX(
       viewsurl,
       {"X-CSRFToken": getCookie("csrftoken")},
       parameters={'settings': $('#settings').val()},
       'post',
       function(data){
         // joy joy
       },
       null,
       null
     );
  });

});

and make sure to use

....type='submit'>Set</butt....

Upvotes: 1

Related Questions