weixin_33725270 2014-04-10 12:58 采纳率: 0%
浏览 42

通过AJAX插入PHP PDO

I'm hittin' the wall for some days already, and can't seem to resolve this simple problem.

I want to make a simple insert via ajax. As i'm new to PHP, I've seen many examples, read the POST stuff for http and php, read te jquery.ajax documentation, and I'm aware of the PDO documentation aswell. Still, can't find why it's not working.

Here goes the codes, really simple:

Index

<body>
    <form id="myForm" method="post" action="" >
        Nome:
        <input type="text" name="nome" required />
        <br/>
        Tipo:
        <input type="text" name="tipo" required />
        <br/>


        <input type="submit" name="submit" value="save" id="sub"/> 


    </form>

    <script src="script/jquery-2.1.0.js" type="text/javascript"></script>
    <script src="script/ajaxInclude.js" type="text/javascript"></script>
</body>

Ajax call

$(document).ready(function(){
    $('#myForm').submit(function(){
        var data = $(this).serialize();

        $.ajax({
            url: "DAO/insert.php",
            type: "POST",
            data: data,
            success: function( data )
            {
                alert( data );
            },
            error: function(){
                alert('ERRO');
            }
        });

        return false;
    });
});

Config :

<?php

define('HOST', '127.0.0.1');
define('DB_NAME','test');
define('PORT', '3306');
define('USER','root');
define('PASS','');

$dsn = 'mysql:host='.HOST.'; port='.PORT.'; dbname='.DB_NAME;

try {
$bd = new PDO($dsn, USER, PASS);
//  $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Houve algum erro no Banco de Dados';
}

?>

Insert:

<?php
require_once('config.php');

if(isset($_POST['submit'])){

    $nome = $_POST['nome'];
    $tipo = $_POST['tipo'];

    $sql =  'INSERT INTO produto(id, nome, tipo, criado_em) ';
    $sql .= ' VALUES (NULL, :nome, :tipo, NOW())';

    try {
        $query = $bd->prepare($sql);
        $query->bindValue(':nome', $nome, PDO::PARAM_STR);
        $query->bindValue(':tipo', $tipo, PDO::PARAM_STR);

        if($query->execute()){
            echo "Dados inseridos com sucesso";
        }else{
            echo "Falha na inser��o de dados";
        }

    } catch (Exception $e) {
        echo $e->getMessage();
    }
}
?>

I've changed it a million times, and still, I can't even get the returns from the insert, I just get the alert from the sucess from ajax.

Sorry for so simple question, but I'm having some bad time with it. I'm trying to do all with the best practices I've found, and haven't found a solid example of this.

  • 写回答

2条回答 默认 最新

  • weixin_33675507 2014-04-10 13:09
    关注
    var data = $_POST['#myForm'].serialize();
    

    should probably be

    var data = $(this).serialize();
    

    Additionally, you should check for all required parameteres if they're set, submit will never be set, because your submit-input doesn't have a name attribute:

    if(isset($_POST['nome'], $_POST['tipo'])) {
        // your stuff here...
    }
    

    And leaving "php mode" in this way can result in blank lines and you have no idea where they come from later:

    ?>
    
    <?php
    
    评论

报告相同问题?