$ P $从提交一个空值数据库中删除它使用jQuery和AJAX后pvent一个空的表单输入 [英] Prevent an empty form input from submitting an empty value to database after removing it using a jquery and ajax

查看:120
本文介绍了$ P $从提交一个空值数据库中删除它使用jQuery和AJAX后pvent一个空的表单输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我一直读了所有可能的问题和答案在这里这个网站的所有日子里,我知道即时几乎得到正确的答案,但似乎一些建议,在这里不工作对我来说。 我有一个动态表单,用户可以添加和删除文本字段,并提交通过AJAX和PHP请求。该表格​​包含两个必需的文本字段和按钮的添加和(从两个必填字段除外)删除其它领域。用户甚至可以不使用其它额外字段提交表单。

Good day, ive been reading all the possible questions and answers here in this site all day, i know im almost getting the right answer but it seems some of the suggestions here doesnt work for me. I have a dynamic form where the user can add and remove text fields and submit the request through ajax and php. The form consist of two required text field and buttons to add and remove another field(aside from the two required fields). The user can submit the form even not using another extra field.

我的问题是,如果我preSS的添加按钮,后来决定将其删除,我即使在$ P $获得的相应表中的0值数据库pssing删除按钮。

My problem is if I press the add button and later on decide to remove it, I am getting a '0' value in corresponding table in database even after pressing the remove button.

下面是我的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柜台

my Jquery counter

    $(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和即时得到同样的结果。如果我不preSS Add按钮可言,即时没有得到任何问题。它只是在pressing它,甚至取出后在阿贾克斯的变量似乎携带一个空的数据资料库。

i used !empty in my php and im getting same result. If i dont press the add button at all, im not getting any issue. Its just about when pressing it and even after removing it the variable in ajax seems to carry an empty data to database.

推荐答案

我觉得你的问题,问题是,在你的PHP,你叫 $ studid =(爆炸(,$ _ POST [ studid'])); 您检查之前,如果该值设置

I think your issue issue is that, in your PHP, you call $studid = (explode(",", $_POST['studid'])); before you check if the value is set.

从文档的爆炸()

如果分隔符是一个空字符串(),爆炸()将返回FALSE。如果定界符包含用于未包含在字符串和负极限值,那么一个空数组将被退回,,否则包含数组字符串将返回

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

实际上,要调用爆炸()上一个空字符串,并取回您的空字符串。

Effectively, you are calling explode() on an empty string and getting back your empty string.

在你的 PHP ,尝试移动爆炸() if语句里面,你检查后,如果它被设置这样的:

In your PHP, try moving explode() inside the if statement, after you check if it is set like:

<?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,更改:

Also, in your jquery, change:

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;

这篇关于$ P $从提交一个空值数据库中删除它使用jQuery和AJAX后pvent一个空的表单输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆