简体   繁体   English

使用AJAX将表单数据发送到php脚本(无需jQuery)

[英]Using AJAX to send form data to php script (without jQuery)

I am trying to do a basic AJAX implementation to send some form data to a php script and db. 我正在尝试做一个基本的AJAX实现,以将一些表单数据发送到php脚本和db。 I'm just doing this for learning purposes, and have taken it as far as I could. 我只是出于学习目的而这样做,并且已尽我所能。 When I hit the "Create Profile" button, nothing is happening. 当我点击“创建配置文件”按钮时,什么都没有发生。 From my code below, does anything obvious jump out at anyone in my syntax/structure? 从下面的代码中,我的语法/结构中的任何内容都有明显的突兀之处吗?

Note* I've yet to implement the code to retrieve the data using AJAX, will do this later once I get the send working. 注意*我尚未实现使用AJAX检索数据的代码,待发送正常后再执行。

EDIT*** I made some slight changes to the sendFunction(), and have seen some success. 编辑***我对sendFunction()进行了一些细微更改,并且看到了一些成功。 Values are now being added to my database, but they values are blank, instead of the values in the form data. 现在将值添加到我的数据库中,但是它们的值为空,而不是表单数据中的值。

Thank you for all help/suggestions ahead of time! 感谢您提前提供所有帮助/建议!

HTML doc: HTML文档:

<!DOCTYPE HTML>
<html>
<head>
    <title>Ajax Form</title>

    <script language="javascript" type="text/javascript">
    function sendFunction() {                           // Create a function to handle the Ajax
        var xmlhttpCreate;                              // Variable to hold the xmlhttpRequest object
        if (window.XMLHttPRequest) {                     // Checks for browser compatibilities 
            xmlhttpCreate = new XMLHttpRequest();
        }
        else {
            xmlhttpCreate = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttpCreate.onreadystatechange = function() {                 
            if (xmlhttpCreate.readyState == 4) {        // If server has processed request and is ready to respond
                document.getElementById("createSuccess").innerHTML = xmlhttpCreate.responseText;  // Display a success message that the data was sent and processed by the php script & database
            }
        }

        var fName = document.getElementById('firstName').value;         // Dump user firstName into a variable
        var lName = document.getElementById('lastName').value;         // Dump user lastName into a variable
        var queryString = "?fName=" + fName + "&lName=" + lName;       // A query string that will be sent to the php script, which will then send the values to the db
        xmlhttpCreate.open("GET", "ajax_create.php" + queryString, true);  // Open the request
        xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlhttpCreate.send();                                            // Send the request

    }
    </script>
</head>

<body>

    <h3>Create Profile</h3><br>
    <form name="form">
        First Name: <input type="text" id ="firstName"/><br><br>
        Last Name: <input type="text" id="lastName"/><br><br>
        <input type="button" onclick="sendFunction()" value="Create Profile">
    </form><br>
    <div id="createSuccess"></div><br>

    <h3>Search for Profile</h3><br>
    <form name="searchForm">
        First Name: <input type="text" id="searchFirstName"/><br><br>
        <input type="button" onclick="sendFunction()" value="Search for Profile"/>
    </form><br><br>

    <div id="resultFN"></div><br>
    <div id="resultLN"></div><br>

</body>
</html>

And here is my PHP script: 这是我的PHP脚本:

<?php

    // Connect to the database
    $con = mysqli_connect('localhost', 'root', 'intell', 'ajax_profile');

    // GET variables from xmlhttpCreate
    $fName = $_POST['fName'];
    $lName = $_POST['lName'];

    // Escape the user input to help prevent SQL injection
    $fName = mysqli_real_escape_string($fName);
    $lName = mysqli_real_escape_string($lName);

    // Build the query
    $query = "INSERT INTO users (firstName, lastName) VALUES ('$fName', '$lName')";
    mysqli_query($con, $query);
    mysqli_close($con);

    $success = "Profile added to the database";
    echo $success;
?>

you are sending data with method GET and you want to get the date in your php file with POST ... now you have two solutions . 您正在使用GET方法发送数据,并且想通过POST获取php文件中的日期,现在有两种解决方案。 you can change the javascript code to send with GET like this : 您可以将javascript代码更改为使用GET发送,如下所示:

var queryString = "fName=" + fName + "&lName=" + lName;       // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("POST", "ajax_create.php", true);  // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(queryString);  

or you can change the way you get the data on your php file like this: 或者您可以更改在php文件中获取数据的方式,如下所示:

$fName = $_GET['fName'];
$lName = $_GET['lName'];

don't do both things , only one, change either javascript function or php file. 不要同时做两件事,只需更改javascript函数或php文件即可。

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

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