首页 > 解决方案 > 尝试使用带有 AJAX 的按钮单击来激活 PHP 功能

问题描述

我正在尝试调用将从 HTML 表中读取数据的 PHP 脚本/文件。我想按下一个按钮,以便 PHP 脚本/文件将激活并将 HTML 表中的数据读取到使用 MySQL 的数据库中。

我的 AJAX 脚本没有激活 PHP 文件。

HTML 按钮代码:

<button type="submit" class="btn btn-md btn-primary btn-block" id="save">Save Workout</button>

AJAX 代码:

$(document).ready(function(){
        $("#save").click(function(){
            $.ajax({
                type: 'POST',
                url: 'addWorkoutTEST.php',
                success: function() {
                    alert("hello");
                }
            });
        });
});

不完整的 PHP 代码(不包含 DB 代码) - 基于https://brennanhm.ca/knowledgebase/2015/11/import-html-table-into-mysql-table/

<?php

require_once ('simple_html_dom.php');

$table = file_get_html('addWorkout.php');

$db = mysqli_connect('localhost', 'root', '', 'workoutLogger');

foreach($table ->find('tr') as $tr) {    
    $exercise = $tr->find('td', 0)->plaintext;
    $weight = $tr->find('td', 1)->plaintext;
    $sets = $tr->find('td', 2)->plaintext;
    $reps = $tr->find('td', 3)->plaintext;

    $exercise_c = mysqli_real_escape_string($db, $exercise);
    $weight_c = mysqli_real_escape_string($db, $weight);
    $sets_c = mysqli_real_escape_string($db, $sets);
    $reps_c = mysqli_real_escape_string($db, $reps);
}
?>

我无法弹出成功消息。

标签: javascriptphpajax

解决方案


要防止默认的表单提交操作,您只需添加event.preventDefault();

像这样的东西...

$(document).ready(function(){
    $("#save").click(function(event){ // must include event here to match the object in the next line. It can be called anything.
        event.preventDefault(); // Prevent Default Submit
        $.ajax({
            type: 'POST',
            url: 'addWorkoutTEST.php',
            success: function() {
                alert("hello");
            },
            error: function (request, status, error) {
                alert("ERROR: " + request.responseText);
            }
        });
    });
});

如果由于某种原因禁用了 javascript,您需要决定采取什么措施。到目前为止,您通过添加操作对表单的回答中所拥有的内容,这将是这种情况下的后备。这是你需要思考和决定的事情。


推荐阅读