AJAX无法发布到PHP文件

FIXED! See bottom for solution.

I am having an incredibly hard time with this. I've been at it for weeks now. I am trying to use AJAX to add a new record into mysql. The PHP file works 100% but I can't seem to be able to make AJAX to work with my form which has a POST method of sending data. This is my first time here on StackOverflow btw so take it easy on me. Here is the code:

HTML code:

<form name='addform' method='POST' >
    <td></td>
    <td><input type='text' id='cname'></td>
    <td>
        <select id='fuel'>
            <option value='Petrol'>Petrol</option>
            <option value='Diesel'>Diesel</option>
            <option value='Hybrid'>Hybrid</option>
            <option value='LPG'>LPG</option>
        </select>
    </td>
    <td>
        <select id='trans'>
            <option value='Automatic'>Automatic</option>
            <option value='Manual'>Manual</option>
            <option value='Semi-Auto'>Semi-Auto</option>
        </select>
    </td>
    <td><input type='text' id='engine'></td>
    <td><input type='text' id='doors'></td>
    <td><input type='text' id='total'></td>
</tr>
<tr>
    <td><input type='submit' value='Add Car' onclick='addRecord()'></td>
...

I have an external .js file to handle Javascript:

function addRecord(){
    if (
        document.addform.cname.value == "" 
        || document.addform.fuel.value == "" 
        || >document.addform.trans.value == "" 
        || document.addform.engine.value == "" 
        || document.addform.doors.value == "" 
        || document.addform.total.value == ""
    ) 
    { 
        alert ("Empty >field(s) - Cannot create record"); 
        return;
    }

    var mydata = null;
    // Mozilla/Safari
    if (window.XMLHttpRequest) 
    {
        xmlHttpReq2 = new XMLHttpRequest ();
    }
    // IE
    else if (window.ActiveXObject) 
    {
        xmlHttpReq2 = new ActiveXObject ("Microsoft.XMLHTTP");
    }

    var cname = document.getElementById('cname').value;
    var fuel = document.getElementById('fuel').value;
    var trans = document.getElementById('trans').value;
    var engine = document.getElementById('engine').value;
    var doors = document.getElementById('doors').value;
    var total = document.getElementById('total').value;

    mydata = '?cname='+cname+'&fuel='+fuel+'&trans'+trans+'&engine'+engine+'&doors'+doors+'&total'+total;          

    alert ("To Server (Add New Record):

add.php" + mydata);

    xmlHttpReq2.open('POST', "add.php" +mydata, true);
    xmlHttpReq2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttpReq2.send(null);
    xmlHttpReq2.onreadystatechange = addRecordCallback;
}

The PHP code:

<?php

$link = mysql_connect ("194.81.104.27", "www", "www");
mysql_select_db ("xyz") or die(mysql_error());

$tot=$_POST[total];
$door=$_POST[doors];
$query = "INSERT INTO tbl 
    (ID, CARNAME, FUELTYPE, TRANSMISSION, ENGINESIZE, DOORS, TOTAL, AVAILABLE)
    VALUES ('$_POST[cname]','$_POST[cname]', '$_POST[fuel]', '$_POST[trans]','$_POST[engine]', $door, $tot, $tot)";
    $result = mysql_query($query);
    mysql_close ($link);
?>

What happens is I put the info into the form, click the button and the alert tells me that it does indeed get the data from the form. But after that nothing happens. I think that the data is not being sent in the right format to the PHP file for some reason.

Thanks!

Solution was:

I managed to get it working! Part of the fault was that like @adeneo said I did not have the onclick='addRecord(); return false;' in there! Another thing I did was to remove the id of the form, not sure if that did anything at all. I have also attached "mydata" to the .send like so: xmlHttpReq2.send(mydata); and finally I had to remove a "?" which was in front of cname in the mydata variable gathering thing. So it was mydata = '?cname='+cname+... and I had to remove the ?. Thanks everyone for all the help!

Your complicating your live since you already use jquery use it for AJAX too.

$.AJAX({ url: "path to php", type: "post", data: $("#formID").serialize(), });

Send this as data and you will be fine.

Sorry for has spelling, sensed from phone. Greetings

Ezeky

There are quite a few things wrong.

You are not using the name attribute on the input/select elements. They need to have a name in order for them to be sent with the POST request. The id attribute has nothing to do with forms (except when using labels; the for attribute points to them)

<form action="/path/to/php/file.php" method="post" id="addform">
    <div>
        <label for="carname">CName</label>
        <input type="text" name="carname" id="carname">
    </div>
    <div>
        <label for="fuel">Fuel</label>
        <select id="fuel" name="fuel">
            <option value="Petrol">Petrol</option>
            <option value="Diesel">Diesel</option>
            <option value="Hybrid">Hybrid</option>
            <option value="LPG">LPG</option>
        </select>
    </div>
    <div>
        <label for="transmission">Transmission</label>
        <select id="transmission" name="transmission">
            <option value="Automatic">Automatic</option>
            <option value="Manual">Manual</option>
            <option value="Semi-Auto">Semi-Auto</option>
        </select>
    </div>
    <div>
        <label for="engine">Engine</label>
        <input type="text" id="engine" name="engine">
    </div>
    <div>
        <label for="doors">Doors</label>
        <input type="text" id="doors" name="doors">
    </div>
    <div>
        <label for="total">Total</label>
        <input type="text" id="total" name="total">
    </div>
    <div>
        <label for="submit">Engine</label>
        <input type="submit" id="submit" value="Add Car" onclick="addRecord()">
    </div>
</form>

As for the javascript, it is much easier to use jQuery (or a similar library). It abstracts away all the nitty-gritty details and browser differences, and makes your life much easier.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
// When the page is done loading...
$(function () {
    // When the form is submitted
    $("form#addform").on("submit", function () {
        // Get the form data and serialize it
        var data = $(this).serialize();
        // Create a POST request
        var post = $.post("/path/to/php/file.php", data);
        // When the request is done show a message
        post.done(function () {
            alert("Form submitted!");
        });
        // If the request fails show another message
        post.fail(function () {
            alert("Error! Form not submitted.");
        });
        // Returning false prevents the form's normal
        // behaviour, i.e. its submission
        return false;
    });
});
</script>

Looking at your PHP code it looks like you have just learnt PHP: You are using a deprecated extension (mysql); you just use POST variables without bothering with security; and your SQL code looks a little iffy (e.g. what is AVAILABLE and why is it set to $total?); and finally, string array indices should be quoted.

// Database handle
$db = new MySQLi('194.81.104.27', 'www', 'www', 'xyz');

// SQL query with placeholders
$sql = "INSERT INTO tbl (CARNAME,FUELTYPE,TRANSMISSION,ENGINESIZE,DOORS,TOTAL) VALUES (?,?,?,?,?,?)";

// Create a statement object
$stmt = $db->prepare($sql);

// Fill in the placeholders
$stmt->bind_param('ssssii', $carname, $fuel, $transmission, $engine, $doors, $total);

// Set the values
$carname      = filter_input(INPUT_POST, 'cname', FILTER_SANITIZE_STRING);
$fuel         = filter_input(INPUT_POST, 'fuel', FILTER_SANITIZE_STRING);
$transmission = filter_input(INPUT_POST, 'transmission', FILTER_SANITIZE_STRING);
$engine       = filter_input(INPUT_POST, 'engine', FILTER_SANITIZE_STRING);
$doors        = filter_input(INPUT_POST, 'doors', FILTER_SANITIZE_NUMBER_INT);
$total        = filter_input(INPUT_POST, 'total', FILTER_SANITIZE_NUMBER_INT);

// If the statement was not executed then there was an error
if ($stmt->execute() === false) {
    header('HTTP/1.0 404 Not Found', true, 404);
}
// Done

Note: I never tested any of the examples. I just wrote them down in my text editor, as needed, so you will probably need to adapt them.

I think part of the issue is that you're pasting data "mydata = '?cname='+cname+'&fuel..." onto the back of the URL like you would if using GET as your transmittal method, but you define POST as the transmittal method, so doing this is unnecessary.

The POST method encapsulates the data for you.Try removing the +mydata from this line

xmlHttpReq2.open('POST', "add.php" +mydata, true);

Also, two more lines down, you're calling a function that's not listed here

xmlHttpReq2.onreadystatechange = addRecordCallback;

Seeing what that function does would be helpful.