ajax拒绝提交数据以便处理到php

时间:2018-05-10 21:14:49

标签: javascript php ajax

虽然,我是ajax的新手,我正在尝试使用php提交数据进行处理和插入到数据库中,但它无法正常工作,我不知道为什么这些是迄今为止采取的步骤。 1.单独使用php,我可以将数据插入到数据库中,这就是php代码。

<?php
        try {
            $linkas = 2;
            require_once 'db/DBConnect.php';
            $errors = [];
            $good = true;
            if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['testimony'])):
                $testimony = filter_input(INPUT_POST, 'testimony', FILTER_SANITIZE_STRING);

                if (strlen($testimony) < 20):
                    //report error and do not go
                    $errors[] = 'It has to be more than 20 characters' . '<br>';
                    $good = false;
                else:
                    $good = true;
                    if ($good):
                        $insertTestimony = 'INSERT INTO testimony(content, j_member_id, time_send) ';
                        $insertTestimony .= 'VALUES (:testimony, :user_id, NOW())';
                        $insert = $conn1->prepare($insertTestimony);
                        $insert->bindValue(':testimony', $testimony, PDO::PARAM_STR);
                        $insert->bindValue(':user_id', $linkas, PDO::PARAM_INT);
                        $insert->execute();
                        if ($insert->rowCount() == 1):
                            //success message
                            $_SESSION['msg'] = 'Thanks for the testimony';
                            header('Location: index.php');
                            exit();
                        else:
                            //fail message
                            echo 'Something is wrong, please resubmit';
                        endif;
                    endif;
                endif;
            endif;
        } catch (Exception $e) {
            echo 'Database error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine();
        }
        ?>

在测试了php并看到它有效之后,我继续创建了

下面的html页面
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <section class="">
            <article>
                <div id="testifyForm">
                    <form action="" method="post" id="testimony" accept-charset="utf-8">
                        <fieldset>
                            <legend>Your testimony</legend>
                            <label for="testimony"></label>
                            <textarea id="testimony" name="testimony" maxlength="300"></textarea>
                        </fieldset>
                        <input type="submit" name="testify" id="testify" value="Testify">
                    </form>
                </div>
            </article>
        </section>
        <script src="js/ajax.js"></script>
        <script src="js/testify.js"></script>
    </body>
</html>

最后,我创建了ajax.js脚本和testify.js脚本并将它们放在js文件夹中,并将它们链接到您可以在上面看到的html。

这是作证脚本

function validateForm() {
    'use strict';
    var testimony = document.getElementById('testimony');
    if ((testimony.value.length > 20)) {
        var ajax = getXMLHttpRequestObject();

        ajax.onreadystatechange = function () {
            if (ajax.readyState == 4) {
                if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 300)) {
                    //return ajax.responseText
                    document.getElementById('testifyForm').innerHTML = ajax.responseText;
                } else {
                    document.getElementById('theForm').submit();
                    //return ajax.statusText
                }//End of status
                ajax = null;
            }//End of readyState
        };//End of onreadystatechange
        //return true;
        ajax.open('POST', 'empty.php', true);
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        var data = 'testimony=' + encodeURIComponent(testimony.value);
        ajax.send(data);
        return false;
    } else {
        document.getElementById('error').innerHTML = 'Characters must be more than 20 words';
        return false;
    }//End of testimony
}

function init() {
    'use strict';
    if (document && document.getElementById) {
        var testifyForm = document.getElementById('testifyForm');
        testifyForm.onsubmit = validateForm;
    }
}

window.onload = init;

这是ajax脚本

function getXMLHttpRequestObject() {
    var ajax = null;
    if (window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // Older IE.
        ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
    }
    return ajax;
}

现在的问题是ajax拒绝提交这些数据进行处理和保存(我相信PHP应该处理)。 我也尝试调试它,如果有任何错误,通过在chrome上使用ctrl + shift + j检查控制台(这是迄今为止关于重新布局的唯一步骤)

P.S。这是纯JavaScript和ajax而不是jquery

0 个答案:

没有答案