jQuery序列化数据未插入数据库

I have three things going on.

I am sending information to jQuery using the following HTML form.

        <div id="note_add_container">
            <form id="note_add" method="post">
                <input type="text" name="name" placeholder="name" />
                <input type="text" name="location" placeholder="location" />
                <button id="submit_note">Add note!</button>
            </form>
        </div>

This is the jQuery script that I am using to post such serialized information into the database.

   $('button').click(function () {  
        $.ajax ({
            type: "POST",
            url: "post.php",
            data: $('#note_add').serialize(), 
            success: function(){
                  alert("Done"); 
            }
        });    
    });

This is the PHP that inserts the information into the database.

$name = $_POST['name'];
$location = $_POST['location'];

$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
    die('Error: ' . mysqli_error($link));
}

This does not work. I click the button and nothing happens. The alert does not fire. Can anyone lead me the right direction as to why my code is not working?

This does not work. I click the button and nothing happens. The alert does not fire

Are you totally sure that click handler works? You must ensure that it works firstly, like,

   $('button').click(function () {  
      alert('It works');
   });

If it works, then you can move on. Otherwise check if its inside DOMReady $(function(){ ... }) and that jquery.js is loaded.

Assuming that it works,

How do you know what your PHP script returns? You simply assume that it "should work", here:

 success: function(){
  alert("Done"); 
 }

success() method actually holds a variable that is response that comes from the server side. It should be rewritten as,

 success: function(serverResponse){
  alert(serverResponse); 
 }

As for PHP script,

if (!mysqli_query($connection, $sql)) {
    die('Error: ' . mysqli_error($link));
}

You only handling failure by 'echoing' error messages. You do not handle a situation when mysqli_query() returns TRUE. You should send something like 1 that indicates success.

And finally your code should look like this,

   $('#submit_note').click(function() {  
        $.ajax ({
            type: "POST",
            url: "post.php",
            data: $('#note_add').serialize(), 
            success: function(serverResponse) {
                  if (serverResponse == "1") {
                    alert('Added. Thank you');
                  } else {
                     // A response wasn't "1", then its an error
                     alert('Server returned an error ' + serverResponse);
                  }
            }
        });    
    });

PHP:

$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";

if (!mysqli_query($connection, $sql)) {
    die(mysqli_error($connection));
} else {
    die("1"); // That means success
}

/**
 * Was it $connection or $link?! Jeez, you were using both.
 * 
 */

The callback function that you specified in your $.ajax call will only fire when a response is received from the server. Since you never send anything back to the client from the server after the data is inserted into the database, the client never calls alert("Done");. Add a line to your PHP file that sends a response to the client after a successful SQL insertion. The response can be as simple as a JSON object that says {'status': 'success'}.

Add the following lines to your php file to send the response back:

HttpResponse::setCache(true);
HttpResponse::setContentType('text/html');       
HttpResponse::setData("<html>Success</html>");
HttpResponse::send();
flush();

change the ajax call as follows to see the result:

  $('#submit_note').click(function () {  
        $.ajax ({
            type: "POST",
            url: "post.php",
            data: $('#note_add').serialize(), 
            success: function(respData) {
                  console.log('Response:', respData)
                  alert("Done"); 
            }
        });    
  });

You should apply a better way to handle your form. The serialize() helps, but it is better to work the data into a JSON string. When using JSO you will also need to set the dataType in the ajax call.

$('#note_add').submit(function (event) {
    event.preventDefault();

    var formdata = $('#note_add').serializeArray();
    var formobject = {};

    $(formdata).each(function (event) {
        formobject[formdata[event].name] = formdata[event].value;
    });

    var data = {
        action: "formsend",
        json: JSON.stringify(formobject)
    };

    //* * send with ajax * *

    function sendajax(data) {
        var deferred = $.ajax({
            method: "post",
            url: "ajax.php",
            dataType: "json",
            data: data
        });
        return deferred.promise();
    }

    sendajax(formdata).done(function (response) {
        console.log(response);
        if (response.success == true) {
            alert("Done!");
        }
    })
});

catch with PHP

if(isset($_POST['action']) && $_POST['action'] == 'formsend') {

  $data = json_decode($_POST['json'];

// here you can now access the $data with the fieldnames

  $name = $data->name;
  $location = $data->location;

 // Write to the database
$sql = "INSERT INTO get (name, location) VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
    die('Error: '.mysqli_error($link));
}

if (mysqli_affected_rows($connection) > 0) {
    echo json_encode(array("success" = > true, "message" = > "data is submitted"));
} else {
    echo json_encode(array("success" = > false, "message" = > "an error occurred"));
}
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<title></title>
</head>
<body>
<div id="note_add_container">
  <form id="note_add" method="post">
    <input type="text" name="name" placeholder="name" />
    <input type="text" name="location" placeholder="location" />
    <button id="submit_note">Add note!</button>
  </form>
</div>
<div id="response"> </div>
</body>
<script type="text/javascript">
        $("#submit_note").click(function() {
            var url = "post.php"; // the script where you handle the form input.
            $.ajax({
                   type: "POST",
                   url: url,
                   data: $("#note_add").serialize(), // serializes the form's elements.
                   success: function(data)
                   {
                       $('#response').empty();
                       $('#response').append(data); // show response from the php script.
                   }
                 });

        return false; // avoid to execute the actual submit of the form.
    });
   </script>
</html>

post.php

// Insert here your connection path

<?php
if((isset($_REQUEST['name']) && trim($_REQUEST['name']) !='') && (isset($_REQUEST['location']) && trim($_REQUEST['location'])!=''))
{           
    $name = addslashes(trim($_REQUEST['name']));
    $location = addslashes(trim($_REQUEST['location']));    

    $sql = "INSERT INTO get (name, location) VALUES ('".$name."', '".$location."')";
    if (!mysqli_query($connection, $sql)) {
    die('Error: ' . mysqli_error($link));
    }

    echo "1 record added";
}
?>