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

使用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.

Javascript

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

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

        $.ajax({
               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.

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

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

?>

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.

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.