ajax重定向到操作页面,而不是在同一页面中显示错误

时间:2019-01-03 04:26:17

标签: jquery ajax codeigniter

我在这里做了一个逐步的表格,我的问题是在最后一步显示了错误,但是如果我使用e.preventDefault $ _FILES数组变为NULL,它还会将页面重定向到操作页面

下面的所有代码显示了我的成熟程度,因此将不胜感激

查看

    <?php
        $this->load->helper('form');
        echo form_open_multipart('Ad/postAdForm');
    ?>
        <div class="container">

            <!--<div class="card mt-5" style="background-color: transparent; background-color: rgb(0,0,0); background-color: rgba(0,0,0, 0.4);">
                <div class="card-body">-->

                    <!--Error message start-->
                    <div class="row justify-content-center mt-4" style="min-height: 30px;">
                        <div class="col-lg-4 col-md-6 text-center">
                            <div class="errorMessage">
                                <?php
                                    if(is_null($this->session->flashdata('message')) === FALSE) {

                                        echo '<div class="alert alert-danger" style="font-size: 13px;">'.$this->session->flashdata("message").'</div>';
                                    }
                                ?>  
                            </div>
                        </div>
                    </div>



                    <!--Ad basic details form start-->
                    <div id="adBasicDetails" style="display: ;">
                        <div class="row justify-content-center">
                            <div class="col-lg-4 col-md-6">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fa fa-envelope" aria-hidden="true"></i></div>
                                    <input type="text" name="ad_title" id="ad_title" placeholder="Ad Title" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Ad Title'" required class="single-input" value="<?php echo set_value('ad_title');?>">
                                </div>
                            </div>
                        </div>

                        <div class="row justify-content-center">
                            <div class="col-lg-4 col-md-6">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fa fa-list" aria-hidden="true"></i></div>
                                    <div class="form-select" id="default-select2">
                                        <select name="ad_category" id="ad_category">
                                            <option value="" disabled selected hidden>Category</option>
                                            <option value="1">something</option>
                                            <option value="2">something else</option>
                                            <option 
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row justify-content-center">
                            <div class="col-lg-4 col-md-6">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fa fa-male" aria-hidden="true"></i></div>
                                    <input type="number" name="adult" id="adult" placeholder="Adult" min="1" max="150" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Adult'" required class="single-input" value="<?php echo set_value('adult');?>">
                                </div>
                            </div>
                        </div>

                        <div class="row justify-content-center">
                            <div class="col-lg-4 col-md-6">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fa fa-child" aria-hidden="true"></i></div>
                                    <input type="number" name="child" id="child" placeholder="Child" min="0" max="150" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Child'" required class="single-input" value="<?php echo set_value('child');?>">
                                </div>
                            </div>
                        </div>

                        <div class="row text-center">
                            <div class="col-md-12 mt-4">
                                <button type="button" class="btn btn-warning btn-rad mx-1 my-1 px-5" id="nextBasic">Next</button>
                            </div>
                        </div>
                    </div>
                    <!--Ad basic details form end-->


                    <!--Ad location details form start-->
                    <div id="adLocationDetails" style="display: none;">
                        <div class="row justify-content-center">
                            <div class="col-lg-4 col-md-6">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fas fa-map-pin" aria-hidden="true"></i></div>
                                    <div class="form-select" id="default-select2">
                                        <select name="statelist" id="statelist">
                                            <option value="Manipur">Manipur</option>

                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row justify-content-center">
                            <div class="col-lg-4 col-md-6">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fa fa-map-marker-alt" aria-hidden="true"></i></div>
                                    <input type="text" name="city" id="city" placeholder="City" id="location" onfocus="this.placeholder = ''" onblur="this.placeholder = 'City'" required class="single-input" value="<?php echo set_value('city');?>">
                                </div>
                            </div>
                        </div>

                        <div class="row justify-content-center">
                            <div class="col-lg-4 col-md-6">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fas fa-thumbtack" aria-hidden="true"></i></div>
                                    <input type="text" name="pin" id="pin" placeholder="Pin Code" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Pin Code'" required class="single-input" value="<?php echo set_value('pin');?>">
                                </div>
                            </div>
                        </div>

                        <div class="row justify-content-center">
                            <div class="col-lg-4 col-md-6">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fas fa-thumbtack" aria-hidden="true"></i></div>
                                    <input type="text" name="address" id="address" placeholder="Address" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Address'" required class="single-input" value="<?php echo set_value('address');?>">
                                </div>
                            </div>
                        </div>

                        <div class="row justify-content-center">
                            <div class="col-lg-4 col-md-6">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fa fa-globe" aria-hidden="true"></i></div>
                                    <div class="form-select" id="default-select2">
                                        <select name="country_code" id="country_code">
                                            <option data-countryCode="IN" value="91" selected>India (+91)</option>
                                                <optgroup label="Other countries">
                                                    <option data-countryCode="DZ" value="213">Algeria (+213)</option>
                                                    <option data-countryCode="AD" value="376">Andorra (+376)</option>

                                                </optgroup>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row justify-content-center">
                            <div class="col-lg-4 col-md-6">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fa fa-mobile" aria-hidden="true"></i></div>
                                    <input type="text" name="phone" id="phone" placeholder="Phone Number" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Phone Number'" required class="single-input" value="<?php echo set_value('phone');?>">
                                </div>
                            </div>
                        </div>

                        <div class="row text-center">
                            <div class="col-md-12 mt-4">
                                <button type="button" class="btn btn-warning btn-rad mx-1 my-1 px-5" id="nextLocation">Next</button>
                            </div>
                        </div>
                    </div>
                    <!--Ad location details form end-->


                    <!--Ad description and image details form start-->
                    <div id="adDescriptionImage" style="display: none;">
                        <div class="row justify-content-center">
                            <div class="col-lg-8 col-md-12">
                                <div class="input-group-icon mt-4">
                                    <div class="icon"><i class="fas fa-scroll" aria-hidden="true"></i></div>
                                    <textarea name ="description" id="description" rows="3" cols="50" placeholder="Description about your place" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Description about your place'" required class="single-input" value="<?php echo set_value('description');?>"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="row justify-content-center">
                            <div class="col-lg-2 col-md-3">
                                <div class="avatar-upload mt-4">
                                    <div class="avatar-edit">
                                        <input type='file' id="imageUpload1" name="img1" accept=".png, .jpg, .jpeg" onchange="readURL1(this);"/>
                                        <label for="imageUpload1"></label>
                                    </div>
                                    <div class="avatar-preview">
                                        <div id="imagePreview1">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-2 col-md-3">
                                <div class="avatar-upload mt-4">
                                    <div class="avatar-edit">
                                        <input type='file' id="imageUpload2" name="img2" accept=".png, .jpg, .jpeg" onchange="readURL2(this);"/>
                                        <label for="imageUpload2"></label>
                                    </div>
                                    <div class="avatar-preview">
                                        <div id="imagePreview2">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-2 col-md-3">
                                <div class="avatar-upload mt-4">
                                    <div class="avatar-edit">
                                        <input type='file' id="imageUpload3" name="img3" accept=".png, .jpg, .jpeg" onchange="readURL3(this);"/>
                                        <label for="imageUpload3"></label>
                                    </div>
                                    <div class="avatar-preview">
                                        <div id="imagePreview3">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-2 col-md-3">
                                <div class="avatar-upload mt-4">
                                    <div class="avatar-edit">
                                        <input type='file' id="imageUpload4" name="img4" accept=".png, .jpg, .jpeg" onchange="readURL4(this);"/>
                                        <label for="imageUpload4"></label>
                                    </div>
                                    <div class="avatar-preview">
                                        <div id="imagePreview4">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row text-center">
                            <div class="col-md-12 mt-4" id="changeMe">
                                <button type="submit" class="btn btn-warning btn-rad mx-1 my-1 px-5" id="postFinal">Post</button>
                            </div>
                        </div>
                    </div>
                    <!--Ad description and image details form end-->

            <!--    </div>
            </div>-->

        </div>

    <?php echo form_close(); ?>
    <!--ad submit form end-->

JQUERY

$(document).ready(function(){


//this is to fetch the base url which is used for various purposes later don't be stupid enough to remove it
var base_url = $('#base').val();

//this is to validate the first step and if all the requirements are satisfied then hiding first step and showing second step
$("#nextBasic").on( "click", function() {

    $(".errorMessage").html('');


    var ad_title = $('#ad_title').val();
    var ad_category = $('#ad_category').val();
    var adult = $('#adult').val();
    var child = $('#child').val();

    $.ajax({
        type: "POST",
        url: base_url+"Ad/postAdForm",
        dataType: "json",
        data:{ 
            'ad_title': ad_title,
            'ad_category': ad_category,
            'adult': adult,
            'child': child,
        },

        success: function(response){
            //checking if there is any error in current step
            if(!$.isEmptyObject(response.ad_title)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.ad_title+'</div>');
            }
            else if(!$.isEmptyObject(response.ad_category)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.ad_category+'</div>');
            }
            else if(!$.isEmptyObject(response.adult)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.adult+'</div>');
            }
            else if(!$.isEmptyObject(response.child)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.child+'</div>');
            }
            else {

                //loading next step
                $("#adBasicDetails").css("display", "none");
                $("#adLocationDetails").css("display", "");
                $(".errorMessage").html('');
            }
        }

    });
});


//this is to validate the second step and if all the requirements are satisfied then hiding second step and showing third step
$("#nextLocation").on("click", function() {

    $(".errorMessage").html('');

    //prevously filled fields
    var ad_title = $('#ad_title').val();
    var ad_category = $('#ad_category').val();
    var adult = $('#adult').val();
    var child = $('#child').val();
    //fields required for this step
    var statelist = $('#statelist').val();
    var city = $('#city').val();
    var pin = $('#pin').val();
    var address = $('#address').val();
    var country_code = $('#country_code').val();
    var phone = $('#phone').val();

    $.ajax({
        type: "POST",
        url: base_url+"Ad/postAdForm",
        dataType: "json",
        data:{
            //prevously filled fields
            'ad_title': ad_title,
            'ad_category': ad_category,
            'adult': adult,
            'child': child,
            //fields required for this step
            'statelist': statelist,
            'city': city,
            'pin': pin,
            'address': address,
            'country_code': country_code,
            'phone': phone,
            },

        success: function(response){
            //checking if there is any error in current step
            if(!$.isEmptyObject(response.statelist)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.statelist+'</div>');
            }
            else if(!$.isEmptyObject(response.city)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.city+'</div>');
            }
            else if(!$.isEmptyObject(response.pin)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.pin+'</div>');
            }
            else if(!$.isEmptyObject(response.address)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.address+'</div>');
            }
            else if(!$.isEmptyObject(response.country_code)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.country_code+'</div>');
            }
            else if(!$.isEmptyObject(response.phone)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.phone+'</div>');
            }
            else {

                //loading next step
                $("#adLocationDetails").css("display", "none");
                $("#adDescriptionImage").css("display", "");
                $(".errorMessage").html('');
            }
        }

    });
});


//this is to validate the third step and here the whole data should be submitted and processed for adding into the db
$("#postFinal").on("click", function(e) {


    $(".errorMessage").html('');

    //prevously filled fields
    var ad_title = $('#ad_title').val();
    var ad_category = $('#ad_category').val();
    var adult = $('#adult').val();
    var child = $('#child').val();
    //prevously filled fields
    var statelist = $('#statelist').val();
    var city = $('#city').val();
    var pin = $('#pin').val();
    var address = $('#address').val();
    var country_code = $('#country_code').val();
    var phone = $('#phone').val();
    //fields required for this step
    var description = $('#description').val();
    var imageUpload1 = $('#imageUpload1').val();
    var imageUpload2 = $('#imageUpload2').val();
    var imageUpload3 = $('#imageUpload3').val();
    var imageUpload4 = $('#imageUpload4').val();


    $.ajax({
        type: "POST",
        url: base_url+"Ad/postAdForm",
        dataType: "json",
        data:{ 
            //prevously filled fields
            'ad_title': ad_title,
            'ad_category': ad_category,
            'adult': adult,
            'child': child,
            //prevously filled fields
            'statelist': statelist,
            'city': city,
            'pin': pin,
            'address': address,
            'country_code': country_code,
            'phone': phone,
            //fields required for this step
            'description': description,
            'img1': imageUpload1,
            'img2': imageUpload2,
            'img3': imageUpload3,
            'img4': imageUpload4,
            },


        success: function(response){
            //checking if there is any error in current step

            if(!$.isEmptyObject(response.description)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.description+'</div>');
            }
            else if(!$.isEmptyObject(response.img1)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.img1+'</div>');
            }
            else if(!$.isEmptyObject(response.img2)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.img2+'</div>');
            }
            else if(!$.isEmptyObject(response.img3)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.img3+'</div>');
            }
            else if(!$.isEmptyObject(response.img4)) {

                $(".errorMessage").html('<div class="alert alert-danger" style="font-size: 13px;">'+response.img4+'</div>');
            }
            else if(!$.isEmptyObject(response.success)){

                if(response.success == "iAmAwesome") {  

                    //showing success message
                    $(".errorMessage").html('<div class="alert alert-info" style="font-size: 13px;">Processing your Ad</div>');
                }
            }
        }
    });
    //return false;
});     

});

CONTROLLER

form_validation的某些真实部分可能不准确,因为尚未调试

public function postAdForm(){

    $this->form_validation->set_rules('ad_title','Ad title', 'required|min_length[1]|max_length[125]|callback_alpha_space',
    array(
        'required' => 'Title of the ad can\'t be empty',
        'max_length' => 'Title of the ad shouldn\'t be more than 125 character long',
        'alpha_space' => 'Please Do not use any symbol in your Ad Title'
        )
    );

    $this->form_validation->set_rules('ad_category', 'Category', 'required|max_length[2]|numeric',
    array(
        'required' => 'Select Category'
        )
    );

    $this->form_validation->set_rules('adult','Adult', 'required|numeric|min_length[1]|max_length[2]',
    array(
        'required' => 'Enter Maximum number of Adult you want to host',
        'numeric' => 'Please enter a number',
        )
    );

    $this->form_validation->set_rules('child', 'Child', 'required|numeric|max_length[2]|numeric',
    array(
        'required' => 'Enter Maximum number of child you want to host',
        'numeric' => 'Please enter a number',
        )
    );

    $this->form_validation->set_rules('statelist', 'State', 'required|max_length[27]|callback_alpha_space',
    array(
        'required' => 'Select State',
        'alpha_space' => 'Nice try'
        )
    );

    $this->form_validation->set_rules('city', 'City', 'required|max_length[300]',
    array(
        'required' => 'Enter your city name'
        )
    );

    $this->form_validation->set_rules('pin', 'Pin Code', 'required|max_length[10]|numeric',
    array(
        'required' => 'Please enter Pin Code'
        )
    );

    $this->form_validation->set_rules('address', 'Address', 'required|max_length[3000]',
    array(
        'required' => 'Please enter your address'
        )
    );

    $this->form_validation->set_rules('description', 'Description', 'required|max_length[3000]',
    array(
        'required' => 'Provide some description about your place'
        )
    );

    $this->form_validation->set_rules('country_code', 'Country code', 'required|max_length[3]|min_length[1]|numeric',
    array(
      'required' => 'Country is required'
      )
    );

    //is there any better way to do this if you know please let me know
    if (empty($_FILES['img1']))
    {
        $this->form_validation->set_rules('img1', 'image', 'required',
        array(
          'required' => 'please select 1st image'
          )
        );
    }

    if (empty($_FILES['img2']))
    {
        $this->form_validation->set_rules('img2', 'image', 'required',
        array(
          'required' => 'please select 2nd image'
          )
        );
    }

    if (empty($_FILES['img3']))
    {
        $this->form_validation->set_rules('img3', 'image', 'required',
        array(
          'required' => 'please select 3rd image'
          )
        );
    }

    if (empty($_FILES['img4']))
    {
        $this->form_validation->set_rules('img4', 'image', 'required',
        array(
          'required' => 'please select 4th image'
          )
        );
    }

    $this->form_validation->set_rules('phone', 'Phone number', 'required|exact_length[10]|numeric',
    array(
      'required' => 'Phone number is required',
      'exact_length' => 'Please enter your Phone number',
      'numeric' => 'Please enter your Phone number',
      'is_unique' => 'provided phone number already exist'
      )
    );

    if($this->form_validation->run() === FALSE) {

        $errors = $this->form_validation->error_array();
        echo json_encode($errors);
    }
    else {

        //for ajax returning success
        echo json_encode(['success'=>'iAmAwesome']);
        echo json_encode($_FILES);//if using e.preventDefault this is not showing anything other than two brackets
        //echo json_encode($_POST);

        $data = array();
        //creating the data array


        //insseting data
        if($this->AdModel->insert($data, 'ad') === FALSE) {

            //code here
        }
        else {

            //code here



            //looping through file
            for($i=0;$i<1;$i++) {

                //
                $j = $i+1;
                $img = 'img'.$j;
                echo $img;

                if(isset($_FILES[$img])) {
                // some file uplad codes will go here

                }
                else {

                    echo 'not working at all\n'.$i;
                }
            }       
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在ajax调用内的视图中,添加此行。

event.preventDefault();

示例:

<script>
function submitForms(){

      var rowcollection =  addCheckedtoArray();
      event.preventDefault();
      dataSet = {
          "rowcollection" : rowcollection,
          "funtion" : $('#operationName').val(),
          "date" : $('#From').val(),
      };

      $.ajax({
            type:"POST",
            url:"<?php echo base_url(); ?>operation",
            data:dataSet,
            success:function(data) {
                rowcollection.forEach(function(element) {
                    var label="label[for='lable_"+element+"']";
                    var tableRowlName="#td_"+element;
                    jQuery(label).html('Communicating..'); 
                    $(tableRowlName).css('background', '#FCF0DA');
                  });
                $("#requestStatusModal").modal('hide');
                //$('#var_dump').html(data);
            }
        });
        event.preventDefault();
    };
</script>