Skip to main content
5 de 5
se añadieron 4443 caracteres en el cuerpo
Charlie
  • 226
  • 4
  • 21

Form Submit con Ajax no hace lo que debería

Tengo un código en Ajax para añadir nuevos editoriales pero no me funciona como quiero que funcione.

Este sería el código Ajax:

$("#addeditorials").on("submit", function(e){
    e.preventDefault();
    e.stopPropagation();
    toastr.success("Please, wait a moment...", "Creating new Editorial");
    var btn = $(this);
    var form = $(this).closest('form');
    form.validate({
        rules: {
            name: {
                required: true
            }
        }
    });
    if (!form.valid()) {
        return;
    }
    btn.addClass('kt-spinner kt-spinner--right kt-spinner--sm kt-spinner--light').attr('disabled', true);
    form.ajaxSubmit({
        type: 'POST',
        url: './index.php?action=editorial-add',
        cache: 'false',
        success: function(response, status, xhr, $form) {
          setTimeout(function() {
              location.reload();
          }, 2000);
            
        }
    });
});

Y este el form con el submit:

<div class="modal fade" id="addEditorialModal" tabindex="-1" role="dialog" aria-labelledby="Add Editorial" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
          <form class="kt-form" role="form" method="post" action="./index.php?action=editorial-add" id="addeditorials">
          <div class="modal-header">
              <h5 class="modal-title w-100 text-center">New Editorial</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              </button>
          </div>
          <div class="modal-body">
              <div class="kt-section kt-section--first">
                    <div class="form-group row">
                        <label for="inputEmail1" class="col-form-label col-lg-4 col-sm-12 text-right">Name:</label>
                        <div class="col-lg-6 col-md-8 col-sm-12">
                        <input type="text" name="nombre"  required class="form-control" id="inputEmail1" placeholder="">
                        </div>
                    </div>
              </div>
              <div class="kt-form__actions">
                  <?php printButtons("addSubmit","","Add editorial") ?>
              </div>
          </div>
          </form>
      </div>
  </div>
</div>

Los problemas serían:

  • Permite enviar varios submit, no funciona el preventDefault();
  • No se añaden las clases al botón de submit para ponerle el spinner y el disabled.
  • Quiero que me generé el Toastr mientras este añadiendo el nuevo editorial pero solo he conseguido ponerle un timer de 2 segundos para la notificación y que luego se actualice.

También me gustaría saber como añadir un toastr si da error y cuando este completado antes de recargar la página.

Más código:

el editorial-add del php

<?php
// print_r($_SESSION);
if(count($_POST)>0){
    $a = new SQLMan();
    $a->tablename = "editorial";
    $a->nombre = $a->is_string(ucwords(mb_strtolower($_POST["nombre"])));
    $a->creator_id = $_SESSION["admin_id"];
    list($rs,$lastid)=$a->add();
    echo $lastid;
    Core::redir("./editorials");
}

?>

La función printButtons():

function printButtons($type, $href, $text) {
    
    if ($href != "") {$href = $href;} else {$href = "";}
    if ($text != "") {$text = $text;} else {$text = "";}
    if (isset($_GET["id"])) {$url="../";} else {$url="";}
    
    switch($type) {
        case "add":
            echo "<a href='" . $url . $href . "' class='btn btn-success btn-elevate btn-icon-sm btn-square'><i class='fas fa-plus'></i>" . $text . "</a>";
            break;
        case "addModal":
            echo "<button type='submit' class='btn btn-success btn-square' data-toggle='modal' data-target='#".$href."'><i class='fas fa-plus'></i> " . $text . "</button>";
            break;
        case "addSubmit":
            echo "<button type='submit' class='btn btn-success btn-square'><i class='fas fa-plus'></i> " . $text . "</button>";
            break;
        case "edit":
            echo "<a href='" . $url . $href . "' class='btn btn-warning btn-elevate btn-icon-sm btn-square'><i class='fas fa-edit'></i>" . $text . "</a>";
            break;
        case "editSubmit":
            echo "<button type='submit' class='btn btn-success btn-square'><i class='fas fa-edit'></i> " . $text . "</button>";
            break;
        case "back":
            echo "<a href='" . $url . $href . "' class='btn btn-warning btn-elevate btn-icon-sm pull-left btn-square'><i class='fas fa-chevron-left'></i>" . $text . "</a>";
            break;
        case "return":
            echo "<button type='submit' class='btn btn-success btn-square'><i class='far fa-calendar-check'></i> " . $text . "</button>";
            break;
        default:
            echo "<a href='javascript:(void)' class='btn btn-default btn-elevate btn-icon-sm btn-square'>Button not found</a>";
            break;
    }
}

El ajax del Login que si me funciona correctamente:

var handleSignInFormSubmit = function() {
    $('#kt_login_signin_submit').click(function(e) {
        e.preventDefault();
        var btn = $(this);
        var form = $(this).closest('form');

        form.validate({
            rules: {
                email: {
                    required: true,
                    email: true
                },
                password: {
                    required: true
                }
            }
        });

        if (!form.valid()) {
            return;
        }

        btn.addClass('kt-spinner kt-spinner--right kt-spinner--sm kt-spinner--light').attr('disabled', true);

        form.ajaxSubmit({
            type: 'POST',
            url: 'login.php',
            cache: 'false',
            success: function(response, status, xhr, $form) {
                if(response) {
                    setTimeout(function() {
                        btn.removeClass('kt-spinner kt-spinner--right kt-spinner--sm kt-spinner--light').attr('disabled', false);
                        location.reload();
                    }, 2000);
                } else {
                    // similate 2s delay
                    setTimeout(function() {
                        btn.removeClass('kt-spinner kt-spinner--right kt-spinner--sm kt-spinner--light').attr('disabled', false);
                        showErrorMsg(form, 'danger', 'Incorrect username or password. Please try again.');
                    }, 2000);
                }
            }
        });
    });
}

Spinner:

.kt-spinner {
  position: relative; }
  .kt-spinner:before {
    content: '';
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: absolute;
    top: 50%;
    left: 0;
    border-radius: 50%; }
  .kt-spinner.kt-spinner--sm:before {
    width: 16px;
    height: 16px;
    margin-top: -8px; }
  .kt-spinner.kt-spinner--sm.kt-spinner--center:before {
    left: 50%;
    margin-left: -8px; }
  .kt-spinner.kt-spinner--sm.kt-spinner--left:before {
    left: 0;
    right: auto; }
  .kt-spinner.kt-spinner--sm.kt-spinner--right:before {
    left: auto;
    right: 0; }
  .kt-spinner:before {
    width: 20px;
    height: 20px;
    margin-top: -10px; }
  .kt-spinner.kt-spinner--center:before {
    left: 50%;
    margin-left: -10px; }
  .kt-spinner.kt-spinner--left:before {
    left: 0;
    right: auto; }
  .kt-spinner.kt-spinner--right:before {
    left: auto;
    right: 0; }
  .kt-spinner.kt-spinner--lg:before {
    width: 24px;
    height: 24px;
    margin-top: -12px; }
  .kt-spinner.kt-spinner--lg.kt-spinner--center:before {
    left: 50%;
    margin-left: -12px; }
  .kt-spinner.kt-spinner--lg.kt-spinner--left:before {
    left: 0;
    right: auto; }
  .kt-spinner.kt-spinner--lg.kt-spinner--right:before {
    left: auto;
    right: 0; }
  .kt-spinner:before {
    -webkit-animation: kt-spinner .5s linear infinite;
    animation: kt-spinner .5s linear infinite; }
  .kt-spinner.kt-spinner--brand:before {
    border: 2px solid #5d78ff;
    border-right: 2px solid transparent; }
  .kt-spinner.kt-spinner--light:before {
    border: 2px solid #ffffff;
    border-right: 2px solid transparent; }
  .kt-spinner.kt-spinner--dark:before {
    border: 2px solid #282a3c;
    border-right: 2px solid transparent; }
  .kt-spinner.kt-spinner--primary:before {
    border: 2px solid #5867dd;
    border-right: 2px solid transparent; }
  .kt-spinner.kt-spinner--success:before {
    border: 2px solid #1dc9b7;
    border-right: 2px solid transparent; }
  .kt-spinner.kt-spinner--info:before {
    border: 2px solid #5578eb;
    border-right: 2px solid transparent; }
  .kt-spinner.kt-spinner--warning:before {
    border: 2px solid #ffb822;
    border-right: 2px solid transparent; }
  .kt-spinner.kt-spinner--danger:before {
    border: 2px solid #fd397a;
    border-right: 2px solid transparent; }
  .kt-spinner.kt-spinner--input.kt-spinner--right:before {
    left: auto;
    right: 1rem; }
  .kt-spinner.kt-spinner--input.kt-spinner--left:before {
    right: auto;
    left: 1rem; }
  .kt-spinner.kt-spinner--v2:before {
    -webkit-animation: kt-spinner .5s linear infinite;
    animation: kt-spinner .5s linear infinite; }
  .kt-spinner.kt-spinner--v2.kt-spinner--brand:before {
    border: 2px solid #f6f8ff;
    border-top-color: #4e6bff; }
  .kt-spinner.kt-spinner--v2.kt-spinner--light:before {
    border: 2px solid white;
    border-top-color: #f7f7f7; }
  .kt-spinner.kt-spinner--v2.kt-spinner--dark:before {
    border: 2px solid #656a98;
    border-top-color: #222433; }
  .kt-spinner.kt-spinner--v2.kt-spinner--primary:before {
    border: 2px solid #d7dbf7;
    border-top-color: #4b5bda; }
  .kt-spinner.kt-spinner--v2.kt-spinner--success:before {
    border: 2px solid #90efe5;
    border-top-color: #1bbcab; }
  .kt-spinner.kt-spinner--v2.kt-spinner--info:before {
    border: 2px solid #dee5fb;
    border-top-color: #476de9; }
  .kt-spinner.kt-spinner--v2.kt-spinner--warning:before {
    border: 2px solid #ffe9bb;
    border-top-color: #ffb313; }
  .kt-spinner.kt-spinner--v2.kt-spinner--danger:before {
    border: 2px solid #ffd0e0;
    border-top-color: #fd2a70; }

@-webkit-keyframes kt-spinner {
  to {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg); } }

@keyframes kt-spinner {
  to {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg); } }
Charlie
  • 226
  • 4
  • 21