Form to Ajax to PHP for Insert into SQL

2019-07-24 07:39发布

问题:

I have tried very hard to get a simple working model of this to function. My actual Site is larger, but I've dumbed down the scripting to make things simple (and troubleshoot).

I keep getting "500" errors when I click to send the Form through, and I've been unable to figure out what I've been doing wrong. (I've set up a simple database to capture just this one item).

(The PHP file is named "sample2.php" within the same directory as html is in.)

A screenshot of my database:

My HTML File:

<html>
    <head>
        <meta charset="utf-8">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    </head>
    <body>
        <div name="maindiv" id="maindiv">
            <span>sample1:</span> <input id="sample1" name="sample1" width="300px" type="text" value="sample1text" /><br />
        </div>

        <input type="button" name="sendit" value="Do it" id="sendit"/> 

        <script language="javascript" type="text/javascript">
        $(document).ready(function(){

            $("#sendit").on("click", function() {
                var fieldvalue = [];

                $('#maindiv input').each(function() { 
                    fieldvalue.push([this.id, $(this).val()]); 
                });

                console.log(fieldvalue);

                $.ajax({
                    url: "sample2.php",
                    type: "POST",
                    dataType: "json",
                    data: JSON.stringify(fieldvalue),
                    success: function() {
                        alert("worked");
                    }
                });
            });     
        });
        </script>
    </body>
</html>

and my PHP file:

<?
    $pdo = new PDO("mysql:dbname=trialdb;host=extoleducation.ipagemysql.com","username","password");

    $id = $_POST['sample1'];

    $query->bindValue(':sample1', $sample1, PDO::PARAM_STR);
    $sql = "INSERT INTO sampletable (sampleline) VALUES (:sample1);";

    $query = $pdo->prepare($sql);

    if($statment = $pdo->prepare($sql)) {
        $statment->execute();
        $statment->closeCursor();
        exit();
    }
?>

回答1:

Your PHP seems to be mixed up. For simplicity, try just doing this:

<?php
$pdo = new PDO("mysql:host=extoleducation.ipagemysql.com;dbname=trialdb","username","password");

if(isset($_POST['sample1'])) {
    $sql = "INSERT INTO `sampletable` (`sampleline`) VALUES (:sample1)";
    $query = $pdo->prepare($sql);
    # I find binding values much easier just doing the array into the execute
    # If you get it working like this and really want to go back and try
    # bindValue(), you can
    $query->execute(array(':sample1'=>$_POST['sample1']));
}

This is as basic as it gets. If you can get this to work, then you just kind of build off of it. You may want to try/catch PDOExceptions if you want to troubleshoot any unforeseen sql errors.

For testing pursposes, I would be tempted to not send json, that way you can more-easily troubleshoot your php from the console.log():

$(document).ready(function(){
    $("#sendit").on("click", function() {
        // If you are not serializing, I would do an object, not array
        var fieldvalue = {"action":"submit"};
        // Loop through and save names and values
        $('#maindiv input').each(function(k,v) { 
            fieldvalue[$(v).attr('name')] = $(v).val();
        });

        $.ajax({
            url: "sample2.php",
            type: "POST",
            // Try just sending object here instead of json string
            data: fieldvalue,
            // On the success, add the response so you can see
            // what you get back from the page
            success: function(response) {
                // Do a check to see if you get any errors back
                console.log(response);
                // This has minimal value because it is only telling you
                // that the ajax worked. It's not telling you anything from the
                // response of the page
                alert("worked");
            }
        });
    });     
});