如何通过AJAX检查数据库字段

时间:2016-06-09 05:24:33

标签: javascript php jquery ajax forms

我创建了一个表单,它通过ajax将数据提交到数据库。这样可以正常工作。我可以阻止进入网站名称已经在数据库中可用。如果已经在数据库中,它应该给出错误信息。

控制器

public function user_add()
    {

        $data_save = array(
            "Mnumber" => $this->input->post("Mnumber"),
            "email" => $this->input->post("email"),
            "fname" => $this->input->post("fname"),
            "address" =>$this->input->post("address"),
            "sitename" =>$this->input->post("sitename"),
           /* "reqnum" => $this->input->post("reqnum"),*/
            "title" => $this->input->post("title"),
            "descr" => $this->input->post("descr"),
            /*"payment" => $this->input->post("payment"),*/
            "uniquekey" => $this->input->post("uniquekey")
            /*"subscription" => $this->input->post("subscription"),
            "email_sent" => $this->input->post("email_sent"),*/
        );

        if ($this->user_mod->AddUser($data_save)) {
                    echo "Successfully Saved";
                }
                else {
                    echo "error";
                }

    }

视图

<script>

    function save_user_new() {

        var Mnumber = $('#Mnumber').val();
        var email = $('#email').val();
        var fname = $('#fname').val();
        var address = $('#address').val();
        var sitename = $('#sitename').val();
        /*var reqnum = $('#reqnum').val();*/
        var title = $('#title').val();
        var descr = $('#descr').val();
        var uniquekey = $('#uniquekey').val();
        /*var subscription = $('#subscription').val();
        var email_sent = $('#email_sent').val();
        var payment = $('#payment').val();*/

        if (sitename != "" && email != "") {
            $.ajax({
                type: "post",
                async: false,
                url: "<?php echo site_url('form_con/user_add'); ?>",
                data: {
                    "Mnumber": Mnumber,
                    "email": email,
                    "fname": fname,
                    "address": address,
                    "sitename": sitename,
                    /*"reqnum": reqnum,*/
                    "title": title,
                    "descr": descr,
                    "uniquekey": uniquekey
                    /*"subscription": subscription,
                    "email_sent": email_sent,
                    "payment":payment*/
                },
                dataType: "html",
                success: function (data) {
                    alert(data);
                    if (data == 'error') {
                        $('#success_msg').hide();
                        $('#error_msg1').show();
                        $('#error_msg1').html("Error : Something wrong.");

                    } else if (data == 'have') {
                        $('#success_msg').hide();
                        $('#error_msg1').show();
                        $('#error_msg1').html("Error : This Sitename is already exists.");
                    } else {
                        $('#error_msg1').hide();
                        $('#success_msg').show();
                        $('#success_msg').html("User details successfully saved.");
                        /*setTimeout(function() { location="features.php"},2000);*/
                        location.href = 'freecreate';


                    }

                }

            });
        } else {
            $('#success_msg').hide();
            $('#error_msg1').show();
            $('#error_msg1').html("Error : Please enter User Details.");
        }
    }
</script>


<form action="#" id="form_sample_1">


                    <div class="form-body">
                        <div class="col-md-6">

                            <div class="form-group">
                                <label class="control-label">Your First Name</label>
                                <input type="text" class="form-control" id="fname" name="fname" placeholder="Enter text" required="">
                            </div>


                            <div class="form-group">
                                <label class="control-label">Email Address</label>
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                                    <input type="email" class="form-control" id="email" name="email" placeholder="Email Address" required="">
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="control-label">Your Mobile Number</label>
                                <input type="text" class="form-control" id="Mnumber" name="Mnumber" placeholder="Enter text" required="">
                                <!--<span class="help-block"> A block of help text. </span>-->
                            </div>

                            <div class="form-group">
                                <label class="control-label">Your Address</label>
                                <input type="text" class="form-control" id="address" name="address" placeholder="Enter text" required="">
                            </div>
                        </div>

                        <div class="col-md-6">

                            <div class="form-group">
                                <label class="control-label">Your Site Name</label>
                                <input type="text" class="form-control" id="sitename" name="sitename"  placeholder="Enter text" required="">
                                <span class="help-block"> please enter the sitename only.if you wish to cretae site as john just type john.it will create the site automatically as john.site.mobi </span><br>
                            </div>

                            <div class="form-group">
                                <label class="control-label">Title of Your Web site</label>
                                <input type="text" class="form-control" id="title" name="title" placeholder="Enter text" required="">
                            </div>

                            <div class="form-group">
                                <label class="control-label">Description of Your Web Site</label>
                                <input type="text" class="form-control" id="descr" name="descr" placeholder="Enter text" required="">
                                <!--<input type="hidden" class="form-control" id="req_num" name="req_num" value="1" placeholder="Enter text">-->
                                <?php $uniquekey = md5(uniqid(rand(), true)); ?>
                                <input type="hidden" class="form-control" id="uniquekey" name="uniquekey" value="<?php echo $uniquekey ?>" placeholder="Enter text">
                                <!--<input type="hidden" class="form-control" id="subscription" name="subscription" value="1" placeholder="Enter text">
                                <input type="hidden" class="form-control" id="email_sent" name="email_sent" value="1" placeholder="Enter text">-->
                                <!--<input type="hidden" class="form-control" id="payment" name="payment" value="1" placeholder="Enter text">-->

                            </div>
                        </div>


                        <div class="form-actions right">
                            <!--<a class="btn green" onclick="save_user_new()">Submit</a>-->
                            <button type="submit" id="save_btn" class="btn green" onclick="save_user_new()">Submit</button>
                            <button type="button" class="btn default">Cancel</button>

                        </div>

                    </div>
                </form>

模型

public function AddUser($data_save)
    {
        if ($this->db->insert('users', $data_save)) {
            return true;
        } else {
            return false;
        }

    }

4 个答案:

答案 0 :(得分:1)

写一个实际检查文本框中空值的validate function并返回truefalse。请考虑以下示例。

function ValidateForm(form){
   var valid=true;
   $(form).find('input[type="text"]').each(function(){
           if($(this).val()=="")
                valid=false;
   });
   return valid;
}

function save_user_new() {
       //getting all the values
       //change if condition to
       var form=$("#form_sample_1");
       if(ValidateForm(form))
       {
            //continue with ajax
       }
       else
       {
           alert('Please fill all the fields'); 
           return false;
       }
}

答案 1 :(得分:0)

jQuery

中添加save_user_new function
   $("input").prop('required',true);

答案 2 :(得分:0)

有几种方法可以做到这一点。

  1. 如前所述,编写验证方法并检查数据库中是否已存在该记录。

  2. 将字段设置为“唯一”,并在运行查询时捕获错误,

  3. 如果你想节省一些时间和编码写一个帮助函数,它将加载你的所有post变量。

    例如

    function LoadPostVariables($variables = [])
    {
        $CI = & get_instance();
        $return_array = [];
        foreach($variables as $key){
            $p_val = $CI->input->post($key);
            //you could perform some basic validation here
    
            $return_array[$key]=$p_val;
        }
    }
    
    $values = LoadPostVariables(['MNumber', 'email', 'fname', 'address', 'sitename', 'title', 'descr', 'uniquekey']);
    

答案 3 :(得分:0)

public function AddUser($data_save)
{
    $check = false;
    $query = "SELECT * FROM users WHERE email='$data_save' LIMIT 1";
    $result = mysqli_query($dbc, $query);

        if($result){
            while($row = mysqli_fetch_assoc($result)){
                $check = true;
            }
        }

    if($check == false){
        // add data
    }else{
        echo 'Email already found'; exit();
    }
}