javascript - Ajax 未提交给 PHP

标签 javascript php jquery ajax

我遇到 Ajax 未提交到我的 PHP 处理表单的问题。当我直接从表单提交到 PHP 文件时,它会执行预期的操作并且效果很好,但是当我尝试通过 ajax 提交时(我在处理时不想加载任何内容),它总是显示“未定义索引:”变量等

这是一个基本形式,所以不确定我做错了什么。需要用不同的眼光来看待这个问题。我尝试过不同的发布方法,我尝试过在 JS 上添加/删除数据类型和数据等。有趣的是,我确实将 PHP 上的错误消息反馈到“#formStatusMessage”,因此它是从后到前通信,但不是从前到后发送数据。

为了便于阅读,我删除了所有无关紧要的代码。非常感谢任何帮助。

下面是我的代码:

HTML:

<form id="mainUserRegFormActual" method="post" >
            <input type="text" id="uFname" name="uFname" placeholder="first name" value="ozarks">
            <input type="text" id="uLname" name="uLname" placeholder="last name" value="sucks Balls">
            <input type="text" id="uEmail" name="uEmail" placeholder="email" value="neverWatchingAgain@ever.com">
            <input type="submit">
        </form>
    </div>

JS:

$("#mainUserRegFormActual").on("submit", function(evt){
    evt.preventDefault();

    var formProcURL = "proc.php";
    var dataStringForStream = $("#mainUserRegFormActual").serialize();

    $.ajax({
        url : formProcURL,
        type: "POST",
        contentType: "application/json",
        dataType: 'json',
        data: dataStringForStream,
    }).done(function(dataPassResponse){
        $("#formStatusMssgs").text("passed data send --> " + dataPassResponse);
    }).fail(function(dataFailResponse){
        $("#formStatusMssgs").text("failed data send --> " + dataFailResponse.responseText);
    });
});

PHP:

define('DB_NAME', 'testDB');

/** MySQL database username */
define('DB_USER', 'unameHere');

/** MySQL database password */
define('DB_PASSWORD', 'passHere');

/** MySQL hostname */
define('DB_HOST', 'localhost');
$c2d = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die("Failed to connect to database" . mysqli_error($c2d));

// =============================================== ][ user info from form ]
$uFnameClean=mysqli_real_escape_string($c2d, $_POST["uFname"]);
$uLnameClean=mysqli_real_escape_string($c2d, $_POST["uLname"]);
$uEmailClean=mysqli_real_escape_string($c2d, $_POST["uEmail"]);

// =============================================== ][ db query ]
$insertData = "INSERT INTO testDB (first_name, last_name, email_addy) VALUES ('$uFnameClean', '$uLnameClean', '$uEmailClean')";

// =============================================== ][ validation ]
if(empty($uFnameClean) || empty($uLnameClean) || empty($uEmailClean)){
    http_response_code(400);
    $userMessage = "Sorry, there was an error processing your form because you forgot to enter in either your First Name, Last Name, or your Email Address. " ;

    echo $userMessage;
    die();

} elseif(!filter_var($uEmailClean, FILTER_VALIDATE_EMAIL)){
    http_response_code(400);
    $userMessage = "Sorry, there was an error processing your form because the email you entered is incorrect. " ;

    echo $userMessage;
    die();

} elseif(preg_match('#[0-9]#',$uFnameClean) || preg_match('#[0-9]#',$uLnameClean)) {
    echo "Unfortunately there was a problem saving your data. Your name has numbers";
    die();

} else {

    if($c2d){
        if(mysqli_query($c2d, $insertData)){
            http_response_code(200);
            setcookie("userRegistered", true);
            echo "Your data has been saved!";
        }else{
            http_response_code(400);
            echo "Unfortunately there was a problem saving your data. Please try again later";
        }

    }else{
        http_response_code(400);
        echo "no connection";
    }

}

最佳答案

您的ajax请求中的内容类型是错误的,您将其设置为application/json,但事实并非如此。
从ajax请求中删除内容类型参数

$.ajax({
    url : formProcURL,
    type: "POST",
    //dataType: 'json',
    data: dataStringForStream,
}).done(function(dataPassResponse){
    $("#formStatusMssgs").text("passed data send --> " + dataPassResponse);
}).fail(function(dataFailResponse){
    $("#formStatusMssgs").text("failed data send --> " + dataFailResponse.responseText);
});

$.ajax 的默认内容类型是 application/x-www-form-urlencoded 这是您从 .serialize() 获得的内容以及用于填充$_POST super 全局

<小时/>

由于您使用纯文本而不是 json 进行响应,因此 dataType: 'json', 也应该被删除。

关于javascript - Ajax 未提交给 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52748144/

相关文章:

javascript - 幸运之轮 - 最终选择与指针不匹配

javascript - 这里的数组输出类型是什么

javascript - 在 SharePoint 上使用 JQuery。脚本在两种浏览器上的 Fiddle 中都可以工作,但在 IE 的页面上不起作用

jquery - 有没有办法确保第一个 AJAX 调用在后续调用执行之前完成?

javascript - 删除一定宽度的背景图片

javascript - JS pageX和pageY取坐标加上相对位置div的margin?

javascript - 在 Jison 中制作数组

javascript - 在 highcharts 中按名称或 ID 删除系列

javascript - 不需要的页面重定向

php - 没有从 htaccess 中的 SetEnv 变量获取 $_SERVER 中的值