如果字段为空,如何杀死其余的PHP代码

时间:2014-04-17 11:28:04

标签: php jquery ajax

我有一个由ajax函数调用的php页面,它将我的表单插入到数据库中。但我现在要做的是设置一些条件来说明如果任何字段为空,则终止进程并向ajax返回一条错误消息,它没有工作,请填写所有字段"。

我已经在这里开始了,但我不知道如何把它... PHP代码:

    $name1 = $_POST['name'];
$artist1 = $_POST['artist'];
$url1 = $_POST['url'];
$lyrics1 = $_POST['lyrics'];

if (empty($name1){
        echo 'Please fill all the fields.';
    };
if (empty($artist1){
        echo 'Please fill all the fields.';
    };
if (empty($url1){
        echo 'Please fill all the fields.';
    };


$stmt = $mysqli->prepare("INSERT INTO song VALUES (?)");
$stmt->bind_param('ssssi', $name, $artist, $url, $lyrics, $_SESSION['user_id']);   // bind $sample to the parameter

// escape the POST data for added protection
$name = isset($_POST['name'])
          ? $mysqli->real_escape_string($_POST['name'])
          : '';
$artist = isset($_POST['artist'])
          ? $mysqli->real_escape_string($_POST['artist'])
          : '';
$url = isset($_POST['url'])
          ? $mysqli->real_escape_string($_POST['url'])
          : '';
$lyrics = isset($_POST['lyrics'])
          ? $mysqli->real_escape_string($_POST['lyrics'])
          : '';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

// this is the id of the form
                        $("#add_form").submit(function() {

                            var url = "includes/addtrack.php"; // the script where you handle the form input.

                            $.ajax({
                                   type: "POST",
                                   url: url,
                                   data: $("#add_form").serialize(), // serializes the form's elements.
                                   success: function(data)
                                   {
                                       //alert(data); // show response from the php script.
                                       $.ajax({ //Get the name of the artist 
                                          url: "includes/getsongs.php",
                                         type: "POST",
                                          data: {id: <?php echo $_SESSION["user_id"]; ?>},
                                          success: function(data) {
                                            //called when successful
                                            console.log("The data is:");
                                            console.log(data);
                                            $(".yoursongs").html(data); //Update
                                          },
                                          error: function(e) {
                                            //called when there is an error
                                            console.log(e.message);
                                          }
                                        });
                                   } error: function(e) {
                                            //called when there is an error
                                            console.log(e.message);
                                          }
                                 });

                            return false; // avoid to execute the actual submit of the form.
                        });

3 个答案:

答案 0 :(得分:1)

您可以使用exitdie

终止该脚本
$name1   = $_POST['name'];
$artist1 = $_POST['artist'];
$url1    = $_POST['url'];
$lyrics1 = $_POST['lyrics'];

if ( empty($name1) || empty($artist1) || empty($url1) ){
    die('Please fill all the fields.');
}

答案 1 :(得分:1)

我认为最好的方法是使用json并在结果数组上添加状态类型,如下所示:         

if (empty($name1)){
    $result['error'][] = 'Please fill all the fields.';
};
if (empty($artist1)){
    $result['error'][] = 'Please fill all the fields.';
};
if (empty($url1)){
    $result['error'][] = 'Please fill all the fields.';
};
if(!empty($result['error']))
    die(json_decode($result));

$stmt = $mysqli->prepare("INSERT INTO song VALUES (?)");
$stmt->bind_param('ssssi', $name, $artist, $url, $lyrics, $_SESSION['user_id']);   // bind $sample to the parameter

// escape the POST data for added protection
$name = isset($_POST['name'])
    ? $mysqli->real_escape_string($_POST['name'])
    : '';
$artist = isset($_POST['artist'])
    ? $mysqli->real_escape_string($_POST['artist'])
    : '';
$url = isset($_POST['url'])
    ? $mysqli->real_escape_string($_POST['url'])
    : '';
$lyrics = isset($_POST['lyrics'])
    ? $mysqli->real_escape_string($_POST['lyrics'])
    : '';

/* execute prepared statement */
$stmt->execute();

$result['success'] = sprintf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();
die(json_decode($result));
?>
// this is the id of the form
                        $("#add_form").submit(function() {

                            var url = "includes/addtrack.php"; // the script where you handle the form input.

                            $.ajax({
                                   type: "POST",
                                   url: url,
                                   dataType: 'json',
                                   data: $("#add_form").serialize(), // serializes the form's elements.
                                   success: function(data)
                                   {
if(data.success){
                                       //alert(data); // show response from the php script.
                                       $.ajax({ //Get the name of the artist 
                                          url: "includes/getsongs.php",
                                         type: "POST",
                                          data: {id: <?php echo $_SESSION["user_id"]; ?>},
                                          success: function(data) {
                                            //called when successful
                                            console.log("The data is:");
                                            console.log(data);
                                            $(".yoursongs").html(data); //Update
                                          },
                                          error: function(e) {
                                            //called when there is an error
                                            console.log(e.message);
                                          }
                                        });
} else {
//called when there is an error
console.log(data.error);
}
                                   } error: function(e) {
                                            //called when there is an error
                                            console.log(e.message);
                                          }
                                 });

                            return false; // avoid to execute the actual submit of the form.
                        });

答案 2 :(得分:0)

执行此操作的最佳做​​法之一是使PHP脚本输出带有相应标头的JSON。并使您的Javascript检查响应。

PHP脚本

创建一个返回JSON对象和HTTP标头的函数,而不是使用echo或print:

function json_response($data, $http_status=200) {
    header('Content-Type: application/json');
    http_response_code($http_status);
    print json_encode($data);
}
// [...]
if (empty($name1)) json_response(array(
    'message' => 'Please fill all the fields'
), 400);
// [...]

Javascript脚本

在JavaScript方面,当HTTP状态不是200时,会调用错误回调:

// [...]
error: function(xhr) { {
    console.log(xhr.responseJSON.message);
}
// [...]