I’m new to ajax/jquery. I want to use sweetalert on my website, i set it up as in tutorial, but when i open modal form and click send
button, it goes to another page, page send.php
.
Here my form:
<form id="contactForm1" action="send.php" method="post"> <div class="field-block"> <label for="text">Message1</label> <textarea id="message1" class="field" required name="message1" rows="4" placeholder=""></textarea> </div> <div class="field-block"> <label for="text">Message2</label> <textarea id="message2" class="field" required name="message2" rows="4" placeholder=""></textarea> </div> <div class="field-block"> <label for="text">Message3</label> <textarea id="message3" class="field" required name="message3" rows="4" placeholder=""></textarea> </div> <button id="button" class="button" type="submit">Отправить</button> <div class="result"> <span id="answer"></span> <span id="loader"><img src="images/loader.gif" alt=""></span> </div> </form>
inside this form sweetalert doesn’t work, but outside of form it’s working.
Here sweetalert jquery and ajax request:
<script> $("#contactForm1").on('submit',function(event) { event.preventDefault(); // to prevent default page reloading var dataString = $(this).serialize(); // to get the form data $.ajax({ type: "POST", url: "send.php", data: dataString, success: function(data){ $('#contactForm1')[0].reset(); // to reset form data } }).done(function(data){ setTimeout(function () { Swal.fire( 'Thank you!', 'Your request has been accepted!', ) }, 2000); }); }); </script>
what could be the problem? Please help
Advertisement
Answer
The problem is you’re not sending request with AJAX.
Solution:
First remove action="send.php"
from your form
then add this to your script.
<script> $('.button').click(function(){ swal({ title:"Red Stapler", text: "Are You Sure?", buttons: { cancel: true, confirm: "Submit" } }).then((value) => { <!-- When the user click submit send Ajax request --> $.ajax({ url: "send.php", method: "POST", data:{ message1: $(#message1).val(), message2: $(#message2).val(), message3: $(#message3).val() }, success: function(data) { // some actions } }); }); }); </script>