skip to Main Content

This is the js

<script>
$(document).ready(function()
{
    $("#create-admin").submit(function(e)
    {
        var forms = document.getElementsByClassName('needs-validation');
        if(forms == null)
        {
                $.ajax({
                type: "POST",
                url: "crud_admin.php",
                dataType: "html",
                data: $("#create-admin").serialize()

            }).done(function(data){
                toastr.success(data, 'Success Alert', {timeOut: 5000});
            })
        }
        /**/
    })
})

this is the form

<form id="create-admin" class="needs-validation" autocomplete="off" action="crud_admin.php" method="POST" novalidate> ... </form>

this is the crud_admin.php
vars and db stuff
……………… the response

 if($db_connection->query($sql_add)){

        echo "success";
    }else {
        echo "fail";}

When i click on submit the form all data goes to db, and it redirect me to the page crud_admin.php
enter image description here

2

Answers


  1. Try add a line of code using function preventDefault. It should place before var forms = ……

    https://www.w3schools.com/jsref/event_preventdefault.asp

    Hope it can help.

    Login or Signup to reply.
  2. You can do it this way, how @msg says, try to use preventDefault() method to prevent common behavior of the form. Try this:

    $(document).on('submit', "#create-admin", function(e)
        {
            e.preventDefault();
            if($(this).hasClass('needs-validation'))
            {
               //Make validation before the ajax request
               $.ajax({
                  type: "post",
                  url: "crud_admin.php",
                  data: $(this).serialize()
               }).done(function(data){
                    toastr.success(data, 'Success Alert', {timeOut: 5000});
               })
            }
            /**/
        })
    

    Hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search