错误意外的令牌<在json的回应

时间:2016-01-19 12:42:37

标签: javascript php json html5

Iam尝试通过javaScript文件将用户信息输入数据库,方法是将其链接到.php文件,抛出“意外令牌<”但是当我直接给出动作为.php它的工作正常我觉得问题是.js文件是请帮我解决这个问题。如果错的话请抓住.. !!

html的

                             <form id="form" name = "form" method = "POST" action="form_banking1.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
                                <!--<h1>Please fill the below details</h1>-->
                                <fieldset>
                                    <!--<h2>Account Information</h2>-->
                                    <div class="row">

                                            <div class="col-sm-12 form-group">
                                                <input type="text" placeholder="Current address" class="form-control required" id="ca" name="ca" required="">
                                            </div>

                                            <div class="col-sm-4 form-group">
                                                <input type="text" placeholder="House no" class="form-control required" id="hno" name="hno" required="">
                                            </div>  
                                            <div class="col-sm-4 form-group">
                                                <input type="text" placeholder="Road no" class="form-control required" id="rno" name="rno" required="">
                                            </div>  
                                            <div class="col-sm-4 form-group">
                                                <input type="text" placeholder="Location" class="form-control required" id="location" name="location" required="">
                                            </div>

                                        <div class="col-sm-3 form-group">
                                            <select type="text" class="form-control required" name="country" required="">
                                            <option value="">Country</option>
                                            <option value="1">India</option>

                                            </select>
                                        </div>  
                                        <div class="col-sm-3 form-group">
                                        <select type="text" class="form-control required" id="state" name="state" required="">
                                            <option value="">State</option>
                                            <option value="1">Karnataka</option>

.                                            </select>
                                        </div>  
                                        <div class="col-sm-3 form-group">
                                            <select type="text" class="form-control required" id="city" name="city" required="">
                                            <option value="">City</option>
                                            <option value="1">Bengaluru</option>

                                            </select>
                                        </div>

                                        <div class="col-sm-3 form-group">
                                            <input type="text" placeholder="Pin no" class="form-control required"  id="pin" name="pin" required="">
                                        </div>

                                        <div class="col-sm-12 form-group">
                                            <select type="text" class="form-control required" id="doctitle" name="doctitle" required="">
                                            <option value="">Document Title</option>
                                            <option value="1">Aadhar Card</option>
                                            <option value="2">Pan Card</option>
                                            <option value="3">Ration Card</option>
                                            <option value="4">Green Card</option>
                                            <option value="5">Social Security Card</option>
                                            <option value="6">Voter ID</option>
                                            <option value="7">Driving License</option>
                                            <option value="8">Add New</option>
                                            </select>
                                        </div>

                                        <div class="col-sm-4 form-group">
                                                <input type="text" placeholder="Document no" class="form-control required"  id="docno" name="docno" required="">
                                        </div>  

                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Issued Authority" class="form-control required"  id="ia" name="ia" required="">
                                        </div>

                                        <div class="col-sm-4 form-group">
                                           <input type="text" placeholder="Date of Expiry" class="form-control required"  id="doe" name="doe" required="">
                                        </div>

                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Passport no" class="form-control required" id="pno" name="pno" required="">
                                        </div>  
                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Issued Authority" class="form-control required"  id="pissuedby" name="pissuedby" required="">
                                        </div>  
                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Date of Expiry" class="form-control required" id="pdoe" name="pdoe" required="">
                                        </div>
                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Visa no" class="form-control required" id="vno" name="vno" required="">
                                        </div>  
                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Issued Authority" class="form-control required"  id="vissuedby" name="vissuedby" required="">
                                        </div>  
                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Date of Expiry" class="form-control required" id="vdoe" name="vdoe" required="">
                                        </div>
                                            <div class="col-sm-4 form-group">
                                            <input class="form-control " type="file" name = "doc" id = "doc" required="">
                                        </div>

                                            <div class="col-sm-4 form-group">
                                                <input style="width:100%" type="submit" name = "submit" id = "submit" value = "Save"  class="btn btn-success">
                                            </div><!--==== End col-sm-4 form-group==--> 

                                        </div>
                                        <div class="col-lg-4">
                                            <div class="text-center">
                                                <div style="margin-top: 20px">
                                                    <i class="" style="font-size: 180px;color: #e5e5e5 "></i>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                </fieldset>

                                </form>

    </body>

    </html>

的.js

        $(document).ready(function(){
    $("#submit").click(function(e){
        e.preventDefault();

        var status = $('form')[0].checkValidity();
        if(status){
            var formData = new FormData($('form')[0]);

            $.ajax({
                url: "form_citizenship.php",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                dataType: "JSON",   

                success: function(json){
                    if(json.error){
                        alert(json.error_msg);
                    }else{
                        alert(json.docno);
                    }
                },

                error: function(jqXHR, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });
        }

    });
});

.PHP

       <?php
session_start();
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','miisky');

$response = array();

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

if(!mysqli_connect_errno()){

    $error_flag = false;
    /*foreach($_POST as $value){
        if(empty($value)){
            $error_flag = true;
            break;
        }
    }*/

    if(!$error_flag){

        //receiving post parameters
        $ca =$_POST['ca'];
        $hno = trim($_POST['hno']);
        $rno = trim($_POST['rno']);
        $location = trim($_POST['location']);
        $country = trim($_POST['country']);
        $state = trim($_POST['state']);
        $city = trim($_POST['city']);
        $pin = trim($_POST['pin']);
        $doctitle = trim($_POST['doctitle']);
        $docno = trim($_POST['docno']);
        $ia = trim($_POST['ia']);
        $doe = trim($_POST['doe']);
        $pno = trim($_POST['pno']);
        $pissuedby = trim($_POST['pissuedby']);
        $pdoe = trim($_POST['pdoe']);
        $vno = trim($_POST['vno']);
        $vissuedby = trim($_POST['vissuedby']);
        $vdoe = trim($_POST['vdoe']);

        if(isset($_FILES["doc"]["name"]) && !empty($_FILES["doc"]["name"])){

            //image insertion
            $target_dir = 'doc_uploads/';
            $target_file = $target_dir . basename($_FILES["doc"]["name"]);

            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

            $check = getimagesize($_FILES["doc"]["tmp_name"]);
            if($check !== false){

                if (!file_exists($target_file)){

                    if($_FILES["doc"]["size"] <= 2097152){

                        $permissible_images = array('jpg', 'png', 'jpeg', 'gif');
                        if(in_array($imageFileType, $permissible_images)){

                            if (move_uploaded_file($_FILES["doc"]["tmp_name"], $target_file)){

                                // create a new user profile
                                $sql = "INSERT INTO citizen_info(ca, hno, rno, location, country, state, city, pin, doctitle, docno, ia, doe, pno, pissuedby, pdoe, vno, vissuedby, vdoe, doc, created_at) VALUES ('$ca', '$hno', '$rno', '$location', '$country', '$state', '$city', '$pin', '$doctitle', '$docno', '$ia', '$doe', '$pno', '$pissuedby', '$pdoe', '$vno', '$vissuedby', '$vdoe', '$target_file', NOW())";
                                if(mysqli_query($con,$sql)){
                                    $response["error"] = false;
                                    $response['docno'] = $docno;
                                    echo json_encode($response);

                                }else{
                                    $response["error"] = true;
                                    $response["error_msg"] = "INSERT operation failed";
                                    echo json_encode($response);
                                }
                            }else{
                                // Throw Error Here
                                $response["error"] = true;
                                $response["error_msg"] = "File could not be uploaded";
                                echo json_encode($response);
                            }

                        }else{
                            $response["error"] = true;
                            $response["error_msg"] = "Only jpg, png and gif images are allowed";
                            echo json_encode($response);
                        }

                    }else{
                        $response["error"] = true;
                        $response["error_msg"] = "file size is above 2MB";
                        echo json_encode($response);
                    }

                }else{
                    $response["error"] = true;
                    $response["error_msg"] = "file already exists";
                    echo json_encode($response);
                }

            }else{
                $response["error"] = true;
                $response["error_msg"] = "invalid image format";
                echo json_encode($response);
            }

        }else{
            $response["error"] = true;
            $response["error_msg"] = "Empty file";
            echo json_encode($response);
        }

    }else{
        $response["error"] = true;
        $response["error_msg"] = "Few fields are missing";
        echo json_encode($response);
    }

}else{
    $response["error"] = true;
    $response["error_msg"] = "Database connection failed";
    echo json_encode($response);
}
 ?>

2 个答案:

答案 0 :(得分:1)

这主要是由于javascript期望json响应,服务器抛出'<html></html>'附带的错误。

检查chrome检查器内是否ajax响应正确。 Headsup:

Chrome内部> F12 >网络> XHR。

按如下方式检查答案。

              $.ajax({
                url: "form_citizenship.php",
                type: "POST",
                //form serialization of the all parameters
                data: $("#form").serialize(),
                async: false,
                //data passed in json
                dataType: "JSON",
                /*Give out the alert box
                to display the results*/                
                success: function (json){
                    console.log(json); // <<< you can view in the console the response.
                    .......
                },
                //through out error from back-end if exist
                error: function(jqXHR, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });

答案 1 :(得分:1)

我想指出几件事。

  • 您的表单验证var status = $('form')[0].checkValidity();将无效,因为您的required元素中未包含<input ...>属性。像这样包括他们:

    <input type="text" placeholder="Current address" class="form-control required" id="ca" name="ca" required>
    
  • 使用e.preventDefault();来阻止您首先提交表单。
  • 如果您是通过AJAX上传文件,请使用FormData对象。但请记住,旧浏览器不支持FormData对象。 FormData支持从以下桌面浏览器版本开始:IE 10 +,Firefox 4.0 +,Chrome 7 +,Safari 5 +,Opera 12 +。
  • 在AJAX请求中设置以下选项processData: falsecontentType: false。请参考the documentation了解这些操作。
  • 最后,在form_citizenship.php页面上对表单输入进行适当的验证,因为现在它已经完全混乱了。

所以你的jQuery应该是这样的:

$(document).ready(function(){
    $("#submit").click(function(e){
        e.preventDefault();

        var status = $('form')[0].checkValidity();
        if(status){
            var formData = new FormData($('form')[0]);

            $.ajax({
                url: "form_citizenship.php",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                dataType: "JSON",   

                success: function(json){
                    if(json.error){
                        alert(json.error_msg);
                    }else{
                        alert(json.docno);
                    }
                },

                error: function(jqXHR, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });
        }

    });
});

按照以下方式处理您的AJAX请求:

<?php
    session_start();
    define('HOST','localhost');
    define('USER','root');
    define('PASS','');
    define('DB','miisky');

    $response = array();

    $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

    if(!mysqli_connect_errno()){

        $error_flag = false;
        foreach($_POST as $value){
            if(empty($value)){
                $error_flag = true;
                break;
            }
        }

        if(!$error_flag){

            //receiving post parameters
            $ca =$_POST['ca'];
            $hno = trim($_POST['hno']);
            $rno = trim($_POST['rno']);
            $location = trim($_POST['location']);
            $country = trim($_POST['country']);
            $state = trim($_POST['state']);
            $city = trim($_POST['city']);
            $pin = trim($_POST['pin']);
            $doctitle = trim($_POST['doctitle']);
            $docno = trim($_POST['docno']);
            $ia = trim($_POST['ia']);
            $doe = trim($_POST['doe']);
            $pno = trim($_POST['pno']);
            $pissuedby = trim($_POST['pissuedby']);
            $pdoe = trim($_POST['pdoe']);
            $vno = trim($_POST['vno']);
            $vissuedby = trim($_POST['vissuedby']);
            $vdoe = trim($_POST['vdoe']);

            if(isset($_FILES["doc"]["name"]) && !empty($_FILES["doc"]["name"])){

                //image insertion
                $target_dir = 'doc_uploads/';
                $target_file = $target_dir . basename($_FILES["doc"]["name"]);

                $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

                $check = getimagesize($_FILES["doc"]["tmp_name"]);
                if($check !== false){

                    if (!file_exists($target_file)){

                        if($_FILES["doc"]["size"] <= 2097152){

                            $permissible_images = array('jpg', 'png', 'jpeg', 'gif');
                            if(in_array($imageFileType, $permissible_images)){

                                if (move_uploaded_file($_FILES["doc"]["tmp_name"], $target_file)){

                                    // create a new user profile
                                    $sql = "INSERT INTO citizen_info(ca, hno, rno, location, country, state, city, pin, doctitle, docno, ia, doe, pno, pissuedby, pdoe, vno, vissuedby, vdoe, doc, created_at) VALUES ('$ca', '$hno', '$rno', '$location', '$country', '$state', '$city', '$pin', '$doctitle', '$docno', '$ia', '$doe', '$pno', '$pissuedby', '$pdoe', '$vno', '$vissuedby', '$vdoe', '$target_file', NOW())";
                                    if(mysqli_query($con,$sql)){
                                        $response["error"] = false;
                                        $response['docno'] = $docno;
                                        echo json_encode($response);

                                    }else{
                                        $response["error"] = true;
                                        $response["error_msg"] = "INSERT operation failed";
                                        echo json_encode($response);
                                    }
                                }else{
                                    // Throw Error Here
                                    $response["error"] = true;
                                    $response["error_msg"] = "File could not be uploaded";
                                    echo json_encode($response);
                                }

                            }else{
                                $response["error"] = true;
                                $response["error_msg"] = "Only jpg, png and gif images are allowed";
                                echo json_encode($response);
                            }

                        }else{
                            $response["error"] = true;
                            $response["error_msg"] = "file size is above 2MB";
                            echo json_encode($response);
                        }

                    }else{
                        $response["error"] = true;
                        $response["error_msg"] = "file already exists";
                        echo json_encode($response);
                    }

                }else{
                    $response["error"] = true;
                    $response["error_msg"] = "invalid image format";
                    echo json_encode($response);
                }

            }else{
                $response["error"] = true;
                $response["error_msg"] = "Empty file";
                echo json_encode($response);
            }

        }else{
            $response["error"] = true;
            $response["error_msg"] = "Few fields are missing";
            echo json_encode($response);
        }

    }else{
        $response["error"] = true;
        $response["error_msg"] = "Database connection failed";
        echo json_encode($response);
    }
?>