weixin_33694620 2016-12-10 01:01 采纳率: 0%
浏览 30

在AJAX中发送帖子

I have this submitHandler after a validation:

submitHandler: function(form){
    var data = $(form).toArray();
    var file_data = $('#firma').prop('files')[0];
    data.append('firma', file_data);
    $.ajax({
        url: form.action,
        cache: false,
        contentType: false,
        processData: false,
        type: form.method,
        data: data,
        success: function(response) {
            $(".modal-body").html(response)
            $("#modalDialog").modal();        
        }
    });
}

This code works perfectly but my problem is that it is redirecting to the controller that handle the function to insert the form data to the Database.

I was using this code to get the same result:

submitHandler: function(form){
    var data = new FormData();
    var file_data = $('#firma').prop('files')[0];
    data.append('firma', file_data);
    $.ajax({                
        url: form.action,
        cache: false,
        contentType: false,
        processData: false,
        type: form.method,
        data: data,
        success: function(response,e) {
            $(".modal-body").html(response)
            $("#modalDialog").modal();        
        }
    });
}

As you can see, instead of using the toArray() function I was using new FormData(). This code does not redirect to the controller, instead it just shows the modal with the added HTML in the body, but it is just sending the file_data variable.

I tried replacing:

var data = new FormData();

with:

var data = new FormData($(this)[0]);

And this works fine but I'm still redirected to the controller

This is my controller:

 public function enviarSolicitud(){

    //REVISAR SI EL ARCHIVO ES UNA IMAGEN DE CON EXTENSION VALIDA

    $allowed = array('gif', 'png', 'jepg', 'jpg');
    $filename = $_FILES['firma']['name'];
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    if (!in_array($ext, $allowed)) {
        echo "El archivo no es válido, ingresa solamente imágenes";
    }else{

        //ERROR EN CASO QUE NO SE HAYA SUBIDO O NO SE DETECTE UN ARCHIVO

        $path = "admin/assets/global/img/stylos/firmas/";
        if (0 < $_FILES['firma']['error']){
            echo 'Error: ' . $_FILES['firma']['error'] . '<br>';
        }else{
            move_uploaded_file($_FILES['firma']['tmp_name'], $path . $_FILES['firma']['name']);

            //INSERTAR LA INFORMACION DEL CLIENTE NUEVO EN LA BASE DE DATOS

            $data = array(
                'nombre' => $this->input->post('nombre'),
                'sexo' => $this->input->post('sexo'),
                'apellido_paterno' => $this->input->post('apellido_paterno'),
                'apellido_materno' => $this->input->post('apellido_materno'),
                'calle' => $this->input->post('calle'),
                'numero_ext' => $this->input->post('num_exterior'),
                'numero_int' => $this->input->post('num_interior'),
                'colonia' => $this->input->post('colonia'),
                'estado' => $this->input->post('estado'),
                'ciudad' => $this->input->post('ciudad'),
                'CP' => $this->input->post('c_postal'),
                'firma' => $path.$_FILES['firma']['name'],
                'tel_casa' => $this->input->post('tel'),
                'tel_celular' => $this->input->post('cel'),
                'created_at' => date('Y-m-d'),
            );

            //OBTENER EL NUMERO DE CLIENTE PARA INSERTARLO EN LA TABLA DE AUTORIZACIONES

            $num_cliente = $this->CreditosModel->guardarSolicitud($data);

            $data = array(
                'num_cliente' => $num_cliente,
                'tipo' => 'Autorizar Crédito',
                'estatus' => 'P',
                'fecha_solicitud' => date('Y-m-d h:m:s')
            );
            $solicitud = $this->CreditosModel->solicitarAutorizacion($data);

            echo "La solicitud se ha procesado satisfactoriamente, favor de indicar al cliente que nos pondremos en contacto a la brevedad # de solicitud: <strong>".$solicitud."</strong>";

        }
    }        
}

I want to avoid the redirection and just show a modal with the echo string.

  • 写回答

1条回答 默认 最新

  • weixin_33727510 2016-12-10 01:35
    关注

    Probably you have error in your script. Try

    submitHandler: function(form){
        var data = new FormData(form);
        var file_data = $('#firma')[0].files[0];
        data.append('firma', file_data);
        $.ajax({
    
            url: form.action,
            cache: false,
            contentType: false,
            processData: false,
            type: form.method,
            data: data,
            success: function(response) {
                $(".modal-body").html(response)
                $("#modalDialog").modal();        
            }
        });
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行