使用jquery和ajax删除空表单输入后,阻止空表单输入向数据库提交

时间:2015-02-23 02:11:22

标签: php jquery ajax

美好的一天,我一直在这个网站上阅读所有可能的问题和答案,我知道我几乎得到了正确的答案,但似乎这里的一些建议对我不起作用。 我有一个动态表单,用户可以添加和删除文本字段,并通过ajax和php提交请求。该表单包含两个必需的文本字段和按钮,用于添加和删除另一个字段(除了两个必填字段)。即使不使用其他额外字段,用户也可以提交表单。

我的问题是,如果我按下添加按钮,稍后决定将其删除,我会得到一个' 0' 0即使在按下删除按钮后,数据库中相应表中的值也是如此。

这是我的HTML:

   <form method="POST">
    <span class="text-label">Subject:</span>
    <input type="text" name="subject" id="subject-field" placeholder="Subject name here" maxlength="10" class="record-input-forms" /> <span class="text-label">Section:</span>
    <input type="text" name="section" id="section-field" placeholder="Subject section here" maxlength="3" class="record-input-forms" /> <a href="#" class="add-field" title="Add student field">+</a> <a class="remove-field" href="#" title="Remove student field">&#215;</a> <a href="#" id="save-button" title="Save">&#8594;</a>
    <div id="student-box-wrap"></div> <span id="status-message"></span> </form>

这是我的AJAX

 $(document).ready(function() {
    $("#save-button").click(function() {
        var subject = $("input#subject-field").val();
        if (subject == "") {
            $('#status-message').css({
                "color": "#ec3f8c"
            });
            $('#status-message').html('Please fill the subject fields');
            return false;
        }
        var section = $("input#section-field").val();
        if (section == "") {
            $('#status-message').css({
                "color": "#ec3f8c"
            });
            $('#status-message').html('Please fill the section fields');
            return false;
        }
        var studid = [];
        $('input[name="studid[]"]').map(function() {
            studid.push($(this).val());
        });
        var dataString = 'subject=' + subject + '&section=' + section + '&studid=' + studid;
        $.ajax({
            type: "POST",
            url: 'save.php',
            data: dataString,
            dataType: "html",
            success: function(data) {
                $("input#subject-field").val('');
                $("input#section-field").val('');
                $("input#field-wrap").remove();
                $("#status-message").css({
                    "color": "#39b1c6"
                });
                $("#status-message").html('Save successfully');
                $("#status-message").fadeOut(2000);
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError);
            }
        });
        return false;
    });
});

我的Jquery计数器

    $(document).ready(function() {
    var counter = 0;
    $(".add-field").click(function() {
        counter += 1;
        $("#student-box-wrap").append('<div class="field-wrap-' + counter + '"><span id="number-' + counter + '">' + counter + '.</span> Student ID: <input type="text" name="studid[]" class="record-input-forms" /></div>');
    });

    $(".remove-field").click(function() {
        if (counter == 0) {
            alert("Nothing to remove!");
        } else {
            $(".field-wrap-" + counter + "").remove();
            counter--;
        }
    });
});

我的PHP

    <?php
require 'connection.php';
session_start();
$studid  = (explode(",", $_POST['studid']));
$subject = mysql_real_escape_string(strtoupper($_POST['subject']));
$section = mysql_real_escape_string(strtoupper($_POST['section']));
$adminid = $_SESSION['AdminID'];
mysqli_query($con, "INSERT INTO tbl_subjects(SubjectName, SubjectSection, AdminID) VALUES ('$subject', '$section', '$adminid')");
if (!empty($studid) && !empty($name)) {
    foreach ($studid as $new) {
        $sql_1 = "INSERT INTO tbl_student(StudentID, SubjectID) VALUES ('$new', LAST_INSERT_ID())";
        mysqli_query($con, $sql_1);
    }
}
if (!mysqli_query($con, $sql)) {
    die('Error: ' . mysqli_error($con));
}
?>

我用过!在我的php中空,我得到相同的结果。如果我根本不按添加按钮,我没有任何问题。它只是在按下它时,甚至在删除之后,ajax中的变量似乎携带一个空数据到数据库。

1 个答案:

答案 0 :(得分:0)

我认为您的问题是,在您的PHP中,在检查值是否已设置之前,请调用$studid = (explode(",", $_POST['studid']));

From the docs for explode()


如果分隔符是空字符串(“”),则explode()将返回FALSE。如果分隔符包含未包含在字符串中的值并且使用了负限制,则将返回空数组,否则将返回包含字符串的数组


实际上,您在空字符串上调用explode()并返回空字符串。

PHP中,尝试在if语句中移动explode(),然后检查它是否设置为:

<?php
require 'connection.php';
session_start();
$subject = mysql_real_escape_string(strtoupper($_POST['subject']));
$section = mysql_real_escape_string(strtoupper($_POST['section']));
$adminid = $_SESSION['AdminID'];
mysqli_query($con, "INSERT INTO tbl_subjects(SubjectName, SubjectSection, AdminID) VALUES ('$subject', '$section', '$adminid')");
if ( isset( $_POST['studid'] )) {  
    $studid  = (explode(",", $_POST['studid']));
    foreach ($studid as $new) {
        $sql_1 = "INSERT INTO tbl_student(StudentID, SubjectID) VALUES ('$new', LAST_INSERT_ID())";
        mysqli_query($con, $sql_1);
    }
}
if (!mysqli_query($con, $sql)) {
    die('Error: ' . mysqli_error($con));
}
?>

另外,在你的jquery中,改变:

var dataString = 'subject=' + subject + '&section=' + section + '&section=' + section;

要:

// only add  `studid` if there is one or more present
var studidStr = studid != '' ? '&studid=' + studid : '';
var dataString = 'subject=' + subject + '&section=' + section + studidStr;