繁体   English   中英

ajax 成功 function 不工作,数据类型为 json

[英]ajax Success function not working, with dataType as json

我正在尝试使用 Bootstrap 模式为一组学生(一个教室)添加出勤记录。

以下是我的引导程序模式的代码(我在其中使用了表格)

<div id = "add_attendance_modal" class = "modal fade">
    <div class="modal-dialog mw-100 w-75">
        <form action="post" id = "add_attendance_form">
            <div class = "modal-content">
                <div class = "modal-header">
                    <h4 class = "modal-title">Add Attendance Record</h4>
                    <button type = "button" class = "close" data-dismiss="modal">&times;</button>
                </div>
                <div class = "modal-body">
                    <div class ="form-group">
                        <div class = "row">
                            <label class = "col-md-4 text-right">Attendance Date</label>
                            <div class = "col-md-8">
                                <input type="date" name = "attendance_date" id = "attendance_date" class = "form-control" />
                            </div>
                        </div>
                    </div>
                    <div class = "form-group" id = "student_details">
                        <div class = "table-responsive">
                            <table class = "table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th>Roll Number</th>
                                        <th>Student Name</th>
                                        <th>Present</th>
                                        <th>Leave</th>
                                        <th>Absent</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                        foreach($students as $student)
                        {
                            ?>
                            <tr>
                                <td><?php echo $student['username']; ?></td>
                                <td><?php echo $student['name']; ?>
                                    <input type="hidden" name = "student_id[]" value = "<?php echo $student["id"] ?>">
                                </td>
                                <td><input type="radio" name = "attendance_status<?php echo $student['id']; ?>" checked value = "Present" /></td>
                                <td><input type="radio" name = "attendance_status<?php echo $student['id']; ?>" value = "Absent" /></td>
                                <td><input type="radio" name = "attendance_status<?php echo $student['id']; ?>" value = "Leave" /></td>
                            </tr>
                        <?php  }
                     ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div class = "modal-footer">
                    <input type="submit" name = "add_attendance_submit" id = "add_attendance_submit" class = "btn btn-success" value = "Add Attendance" />
                    <button type = "button" class = "btn btn-danger" data-dismiss="modal">Close</button>
                </div>
            </div>
        </form>
    </div>
</div>

$students是特定 class.. 的所有学生的数组。

以下是我正在尝试使用的 Javascript 中的 Ajax 代码,

$("#add_attendance_form").on('submit', function(event){
    event.preventDefault(); 
    $.ajax({
        url:"attendance_action.php", 
        method: "POST", 
        data: $(this).serialize() + "&action = add_attendance", 
        dataType: 'json', 
        beforeSend: function()
        {
            $("#add_attendance_submit").val("Validating...."); 
            $("#add_attendance_submit").attr('disabled', true); 
        },
        success:function(data)
        {
            
            $("#add_attendance_submit").val("Add Attendance"); 
            $("#add_attendance_submit").attr('disabled', false);
            if (data.success)
            {
                $('message_operation').html('<div class = "alert alert-success">'+data.success+'</div>');
                $('#add_attendance_modal').modal('hide');
                dataTable.ajax.reload();  
            } 
            if (data.error)
            {
                if (data.error_attendance_date != '')
                    $("#error_attendance_date").text(data.error_attendance_date);
                else 
                    $("#error_attendance_date").text('');
            }
            
        },
        error: function(e)
            {
                console.log(e); 
                alert("error"); 
            }
    });
});

这是 attendance_action.php 中的 PHP 代码

if (isset($_POST['action']) && $_POST['action'] == "add_attendance")
{
    $attendance_date = '';  
    $error_attendance_date = ''; 
    $output = ''; 
    $error = 0; 
    if ($_POST['attendance_date'] == '')
    {
        $error_attendance_date = "Attendance Date is Required..."; 
        $error++; 
    }
    else 
    {
        $attendance_date = $_POST['attendance_date'];
    }
    if ($error > 0)
    {
        $output = array(
                    "error"                 => true, 
                    "error_attendance_date" => $error_attendance_date
        );
    }
    else 
    {
        $student_id = $_POST['student_id'];
        $results = check_attendance_records($student_id[0], $attendance_date);
        if ($results->rowCount() > 0)
        {
            $output = array(
                        'error'             => true, 
                        'error_attendance_date' => 'Attendance data already exists on this data'
            );
        }
        else 
        {
            for ($count = 0; $count < count($student_id); $count++)
            {
                $data = array(

                    ':student_id'               => $student_id[$count],
                    ':attendance_status'        => $_POST["attendance_status".$student_id[$count].""],
                    ':attendace_date'           => $attendance_date
                    );
                $db->insert_to_attendance_table($data, $id); // Where $id is teacher id

            }
            $output = array(
                'success'               => 'Data Added Successfully'
            );
        }
    }
    echo json_encode($output); 
}

最后,这里是attendance_action.php中使用的数据库 function(以防万一有人需要看一下)...它们在数据库 class 中定义,其中 $db 是一个 object。

 public function check_attendance_records($student_id, $date)
    {
      $data = array();
      $sql = "select * from junc_attendance where student_id = :student_id AND date = :date";

      $stmt = $this->conn->prepare($sql); 
      $data['classroom_id'] = $classroom_id; 
  $stmt->execute($data);
      $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
      return $result; 
    }
    public function insert_to_attendance_table($data, $teacher_id)
    {
      $class_data = get_classroom_details($teacher_id);
      $classroom_id = $class_data['id'];
      $sql = "INSERT INTO jnc_attendance(classroom_id, date, student_id, status) VALUES (:attendance_date, :classroom_id, :student_id, :attendance_status)";
      $stmt = $this->conn->prepare($sql);
      $stmt->execute(['classroom_id' => $classroom_id], $data);
      return true;
    }

我需要 json 形式的数据,因此我将数据类型用作 json。

我使用了三种不同的条件,第一个检查出勤日期是否为空......第二个检查出勤日期是否已被使用,第三个是成功条件,如果一切顺利。 但是 ajax function 在所有条件下都给出错误,并且总是调用错误function 而不是成功function。

谁能帮我指出错误? 我会非常感激。 我尝试在错误字段中使用 console.log(e) 命令,但我根本无法理解任何内容。

我还从工具中检查了Netwrok ,发送到服务器的数据看起来很完美,但是我从未在网络中收到服务器的任何响应,我应该以 json 的形式获得。

发送到 attendance_action.php 的数据(从工具中的网络可以看出)我没有 select 任何日期,因此 attendance_date 在这里是空的。

attendance_date: 
student_id[]: 2
attendance_status2: Present
student_id[]: 3
attendance_status3: Present
student_id[]: 4
attendance_status4: Present
action :  add_attendance

从 console.log(e) 中,这就是我得到的(这是一个很长的响应,但是我根本不理解它:/)

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort: ƒ (e)
always: ƒ ()
catch: ƒ (e)
done: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ (e)
overrideMimeType: ƒ (e)
pipe: ƒ ()
progress: ƒ ()
promise: ƒ (e)
readyState: 4
responseText: ""
setRequestHeader: ƒ (e,t)
state: ƒ ()
status: 200
statusCode: ƒ (e)
statusText: "OK"
then: ƒ (t,r,i)
__proto__: Object

我可以打开其中任何一个以及所有 go 进入proto上的永无止境循环。 但是不明白为什么......试图搜索这个错误,发现我需要做的是以 json 形式返回我的数据,但我已经在这样做了。

*这就是我得到的,打开“完成”一点点......这可以进一步打开但类似的字段仍然出现*

done: ƒ ()
arguments: (...)
caller: (...)
length: 0
name: "add"
prototype:
constructor: ƒ ()
__proto__:
constructor: ƒ Object()
arguments: (...)
assign: ƒ assign()
arguments: (...)
caller: (...)
length: 2
name: "assign"
__proto__: ƒ ()
apply: ƒ apply()
arguments: (...)
bind: ƒ bind()
call: ƒ call()
caller: (...)
constructor: ƒ Function()
length: 0
name: ""
toString: ƒ toString()
Symbol(Symbol.hasInstance): ƒ [Symbol.hasInstance]()
get arguments: ƒ ()
set arguments: ƒ ()
get caller: ƒ ()
set caller: ƒ ()
__proto__: Object
[[FunctionLocation]]: <unknown>
[[Scopes]]: Scopes[0]
[[Scopes]]: Scopes[0]
caller: (...)
create: ƒ create()
defineProperties: ƒ defineProperties()
defineProperty: ƒ defineProperty()
entries: ƒ entries()
freeze: ƒ freeze()
fromEntries: ƒ fromEntries()
getOwnPropertyDescriptor: ƒ getOwnPropertyDescriptor()
getOwnPropertyDescriptors: ƒ getOwnPropertyDescriptors()
getOwnPropertyNames: ƒ getOwnPropertyNames()
getOwnPropertySymbols: ƒ getOwnPropertySymbols()
getPrototypeOf: ƒ getPrototypeOf()
is: ƒ is()
isExtensible: ƒ isExtensible()
isFrozen: ƒ isFrozen()
isSealed: ƒ isSealed()
keys: ƒ keys()
length: 1
name: "Object"
preventExtensions: ƒ preventExtensions()
prototype: {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
seal: ƒ seal()
setPrototypeOf: ƒ setPrototypeOf()
values: ƒ values()
__proto__: ƒ ()
[[Scopes]]: Scopes[0]
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

尝试添加 header

header('Content-Type: application/json');

if (isset($_POST['action']) && $_POST['action'] == "add_attendance") {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM