【问题标题】:Submit form within bootstrap modal using ajax and codeigniter without page change使用 ajax 和 codeigniter 在引导模式中提交表单,无需更改页面
【发布时间】:2017-07-20 05:56:29
【问题描述】:

我正在尝试使用 ajax 在引导模式中提交表单。而且我的表单提交成功了,但是ajax里面的成功语句没有执行。该页面被重定向到一个空白页面,上面写着 {"msg":"ok"}。 我正在从控制器和视图中粘贴代码。请帮忙。

控制器

$update_profile_details = $this->userp_m->edit_profile_m($uname,$uemail,$data1,$new_email);

            if($update_profile_details == true)
            {
                $status['msg'] = 'ok';
            }
            else
            {
                $status['msg'] = 'err';
            }

            echo json_encode ($status);

查看

    $(document).ready(function()
{   

$("#myForm").submit(function(e) 
{   
    e.preventDefault();
    var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    var name = $('#inputName').val();
    var email = $('#inputEmail').val();

    if (name.trim() == '') {
        alert('Please enter your name.');
        $('#inputName').focus();
        return false;
    } else if (email.trim() == '') {
        alert('Please enter your email.');
        $('#inputEmail').focus();
        return false;
    } else if (email.trim() != '' && !reg.test(email)) {
        alert('Please enter valid email.');
        $('#inputEmail').focus();
        return false;
    } else {
        var fd = new FormData(this);

        $.ajax({
            type: 'POST',
            url: $('#myForm').attr('action'),
            dataType: "json",
            data: $('#myform').serialize(), fd,
            contentType: false,  
            cache: false,   
            processData:false,
            beforeSend: function() 
            {
                $('.submitBtn').attr("disabled", "disabled");
                $('.modal-body').css('opacity', '.5');
            },
            success: function(status) 
            {
                alert(status);

                if (status.msg == 'ok') {
                    $('#inputName').val('');
                    $('#inputEmail').val('');
                    $('.statusMsg').html('<span style="color:green;">Changes have been saved successfully.</p>');
                } else 
                {
                    $('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
                }

                $('.submitBtn').removeAttr("disabled");
                $('.modal-body').css('opacity', '');
            },
            error: function(status) 
            {
                alert("Some error, please try again");

            }
        });
    }

});

HTML

 <form id="myform" method="post" enctype="multipart/form-data" action="<?php echo site_url('User/user_index_c/edit_profile_c'); ?>">
    <label>Full Name : </label>
    <input class="name_styling" type="text" placeholder="Enter name" id="inputName" name="uname">

    <label>Email Id : </label>
    <input class="email_styling" type="email"  placeholder="Enter email" id="inputEmail" name="new_email">

    <div class="controls">
    <label>Profile Photo : </label>
    <input name="file1" type="file"  id="image_file" />
    <img id="blah" class="logoupload" src="#" alt="your image" />
    <span class="filename"></span>
    </div>

    <center><input class="submitBtn" id="submit" type="submit" value="Save Changes" name="submit" ></center>

</form>

【问题讨论】:

    标签: ajax twitter-bootstrap codeigniter


    【解决方案1】:

    您必须编写如下的 jquery 代码,而不是函数。

    删除 function submitContactForm(e){}

    添加 $(document).on('submit', '#myform', function(e) { })

    $(document).on('submit', '#myform', function(e) {
        e.preventDefault();
        var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
        var name = $('#inputName').val();
        var email = $('#inputEmail').val();
        if (name.trim() == '') {
            alert('Please enter your name.');
            $('#inputName').focus();
            return false;
        } else if (email.trim() == '') {
            alert('Please enter your email.');
            $('#inputEmail').focus();
            return false;
        } else if (email.trim() != '' && !reg.test(email)) {
            alert('Please enter valid email.');
            $('#inputEmail').focus();
            return false;
        } else {
            $('.submitBtn').prop("disabled", true);
            $('.modal-body').css('opacity', '.5');
            var myFormData = new FormData();
            e.preventDefault();
            var inputs = $('#myForm input[type="file"]');
            $.each(inputs, function(obj, v) {
                var file = v.files[0];
                var filename = $(v).attr("data-filename");
                var name = $(v).attr("name");
                myFormData.append(name, file, filename);
            });
            var inputs = $('#myForm input[type="text"],input[type="email"]');
            $.each(inputs, function(obj, v) {
                var name = $(v).attr("name");
                var value = $(v).val();
                myFormData.append(name, value);
            });
            var xhr = new XMLHttpRequest;
            xhr.open('POST', '<?php echo base_url(); ?>index.php/User/user_index_c/edit_profile_c/', true);
            xhr.send(myFormData);
            xhr.onload = function() {
                if (xhr.readyState === xhr.DONE) {
                    if (xhr.status === 200) {
                        $('#inputName').val('');
                        $('#inputEmail').val('');
                        $('.statusMsg').html('<span style="color:green;">Changes have been saved successfully.</p>');
                        $('.submitBtn').removeAttr("disabled");
                        $('.modal-body').css('opacity', '');
                    }
                }
            };
        }
    });
    

    如果它不起作用,请告诉我。

    【讨论】:

    • 图片上传停止,如果我使用上述方法
    • 控制台没有报错,ajax的报错函数被执行了
    • 嘿,在页面继续加载的警报之后,然后在新页面上再次显示 {"msg":"ok"}。是不是因为没有写e.preventDefault()?
    • 是的,如果你使用e.PreventDefault(),那么 jquery 将使所有默认方法无效。
    • 没有 e.preventDefault() ,代码不起作用。 html有什么问题吗?
    【解决方案2】:

    试试这个:在你的 file.js 中:

    $(document).ready(function () {
        $('#submit').click(function () {
             var name= $("#inputName").val();
             var mail = $("#inputEmail").val();
             var img = $("#image_file").val();
             $.post("User/user_index_c/edit_profile_c", {send_name:name,send_mail:mail, send_igm:img},
             function (data) {
                 if (data.trim() != "ok") {
                    alert('error');
                  }
                  else{
                      //action for "success" exemple: alert("send with success!"); and insert a code for clean fields
                  }
              });
          });
      });  
    

    在控制器的方法中:

    $uname = $this->input->post("send_name");
    $uemail = $this->input->post("send_mail");
    $new_email = $this->input->post("send_igm");
    
    $update_profile_details =    $this->userp_m->edit_profile_m($uname,$uemail,$data1,$new_email);
    
    if($update_profile_details == true){
        echo 'ok';
            }
            else
            {
                echo 'err';
            }
    

    希望对你有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2013-07-08
      相关资源
      最近更新 更多