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

问题描述:

I am trying to do a basic AJAX implementation to send some form data to a php script and 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.

EDIT*** I made some slight changes to the sendFunction(), and have seen some success. 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:

<!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

    // 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 . you can change the javascript code to send with GET like this :

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:

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

don't do both things , only one, change either javascript function or php file.