dongyukang7006 2018-01-20 12:54
浏览 47

如果else语句与Ajax无法正常工作

I am on admin area, I have a form to create admins, with user (unique id on MySQL), name and password, the form:

<div class="box">
    <div class="box-header with-border">
        <h3 class="box-title">Crear Administrador</h3>
    </div>
    <div class="box-body">
            <form role="form" name="crear-admin" id="crear-admin" method="post" action="insertar-admin.php">
              <div class="box-body">

                    <div class="form-group">
                          <label for="usuario">Usuario</label>
                          <input type="text" class="form-control" id="usuario" name="usuario" placeholder="Usuario">
                    </div>

                    <div class="form-group">
                          <label for="nombew">Nombre</label>
                          <input type="text" class="form-control" id="nombew" name="nombre" placeholder="Tu nombre">
                    </div>

                    <div class="form-group">
                          <label for="contraseña">Contraseña</label>
                          <input type="password" class="form-control" id="contraseña" name="contraseña" placeholder="Contraseña para iniciar sesión">
                    </div>

              </div>
              <!-- /.box-body -->

              <div class="box-footer">
                <input type="hidden" name="agregar-admin" value="1">
                <button type="submit" class="btn btn-primary">Añadir</button>
              </div>
            </form>
    </div>
    <!-- /.box-body -->
</div>

I use insertar-admin.php to insert into db and get a JSON, if statement inserted, respuesta = 'exito', if not, respuesta = 'error', here's the first problem, when insert into db is correct, it works, but when not, I cant get else message, tried with other options, affected_rows, $result = $stmt->execute(); for true or false bool, but I cant get false, here's the code:

<?php

if (isset($_POST['agregar-admin'])) {

    $nombre = $_POST['nombre'];
    $usuario = $_POST['usuario'];
    $password = $_POST['contraseña'];

    $opciones = array(
        'cost' => 12
    );
    $password_hashed = password_hash($password, PASSWORD_BCRYPT, $opciones);


    try {
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        include_once 'funciones/funciones.php';
        $stmt = $conn->prepare("INSERT INTO admins (nombre, usuario, password) VALUES (?,?,?)");
        $stmt->bind_param("sss", $nombre, $usuario, $password_hashed);
        $stmt->execute();
        $id_registro = $stmt->insert_id;
        if ($id_registro > 0) {
            $respuesta = array(
                'respuesta' => 'exito',
                'id_admin' => $id_registro
            );
        } else {
            $respuesta = array(
                'respuesta' => 'error',
            );
        }
        $stmt->close();
        $conn->close();
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
}

And this sends to admin-ajax.js to generate a visual response for the user using SweetAlert2, here's the code:

$(document).ready(function() {
    $('#crear-admin').on('submit', function(e) {
        e.preventDefault();

        var datos = $(this).serializeArray();

        $.ajax({
            type: $(this).attr('method'),
            data: datos,
            url: $(this).attr('action'),
            dataType: 'json',
            success: function(data) {
                var resultado = data;
                if (resultado.respuesta == 'exito') {
                    swal(
                          'Correcto!',
                          'El administrador se creó correctamente!',
                          'success'
                        )
                } else {
                    swal(
                          'Error',
                          'Hubo un error!',
                          'error'
                        )
                }
            }
        })

    });
});

With correct insertion it's OK, I get the Correct message and insert, but when error, I don't get nothing, how can I fix?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
    • ¥15 基于卷积神经网络的声纹识别
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 一直显示正在等待HID—ISP