Submit form within bootstrap modal using ajax and codeigniter without page change

允我心安 提交于 2019-12-24 01:57:16

问题


I am trying to submit a form within a bootstrap modal using ajax. And my form is successfully submitted, but the success statements within ajax are not executed. The page is redirected to a blank page saying {"msg":"ok"}. I am pasting the code from controller and view. Please help.

Controller

$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);

View

    $(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>

回答1:


Instead of function you have to write jquery code like below.

Remove function submitContactForm(e){}

Add $(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', '');
                }
            }
        };
    }
});

Let me know if it not works.




回答2:


try this: in your 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
              }
          });
      });
  });  

in your controller's method:

$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';
        }

I hope I have helped



来源:https://stackoverflow.com/questions/45206267/submit-form-within-bootstrap-modal-using-ajax-and-codeigniter-without-page-chang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!