2017-03-11 08:37

使用Jquery .ajax()和PHP将数据插入数据库不起作用

So I am trying to insert data from a form using JQuery .ajax method. In the developer tools I see that the request is send to my process.php file, but I can't add the data to the database.


$( document ).ready(function() {
    console.log( "ready!" );
    $("#submit").submit(function(e) {

        var url = "process.php"; // the script where you handle the form input.

               type: "POST",
               url: "process.php",
               data: $("#submit").serialize(), // serializes the form's elements.
               success: function(data){
                   alert("Data is send successifully!"); // show response from the php script.

        e.preventDefault(); // avoid to execute the actual submit of the form.

Now I use my custom classes and methods.

This is the insert() method from my db.class.php

  public function insert($fName, $lName, $nickname){
    $query = "INSERT INTO users (first_name, last_name, nickname)
              VALUES ($fName, $lName, $nickname)";

    return $this->_conn->query($query);

now I have user.class.php with add() method

  public function add($fName, $lName, $nickname){
    $db = new db();
    $db->insert($fName, $lName, $nickname);  

Finally a process.php file. I'm sending my request there.

require_once 'classes/user.php';
require_once 'classes/db.php';

$user = new user();
$user->add($_POST['fName'], $_POST['lName'], $_POST['nickname']);

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dshun123456 dshun123456 4年前

    Your values need to be interpreted as Strings in the SQL-Query, otherwise MySQL will think those are columns and will come up empty. Here is how you could do that:

    public function insert($fName, $lName, $nickname){
      $query = "INSERT INTO users (first_name, last_name, nickname)
              VALUES ('$fName', '$lName', '$nickname')";
      return $this->_conn->query($query);

    It is generally recommended to use prepared statements to avoid SQL-Injection attacks though.

    点赞 评论 复制链接分享
  • duankangzi766767 duankangzi766767 4年前

    Try to debug what is in $_POST and make sure that required vars parse to insert query are not empty. Try to var_dump($_POST) in process.php and console.log(data) in success statement in java script.

    点赞 评论 复制链接分享