dongtuo3370 2015-02-03 02:36
浏览 57
已采纳

Ajax请求不向php页面发送数据,但登录控制台正常

I cannot figure out why the data is not getting inserted to my mysql database when it is being logged to the console properly.

My form as follows:

<form id="insertForm" type="post">
name: <input type="text" id="name" name="name">
activity: <input type="text" id="activity" name="activity">
level: <input type="number" id="level" name="level">
<input type="button" name="add" id="add" value="add">
</form>

My ajax call:

<script type="text/javascript">
$(document).ready(function() {
 $("#add").click(function(e){
var Data = $("#insertForm").serializeArray();
 console.log(Data);
 $.ajax({
 url : "insert.php",
 type: "POST",
 data : Data,
 success:function(data, textStatus, jqXHR)
 {
$('#msg').html(data);
 }
 });
 $("#msg").slideDown("slow");
 e.preventDefault();
});
});
</script>

My PHP insert:

<?php
if (!empty($_POST))
{
$dbhost = 'localhost';
$dbuser = 'lot_root';
$dbpass = '';
$con = mysql_connect($dbhost, $dbuser, $dbpass);

$name = mysql_real_escape_string($_POST['name']);
$activity = mysql_real_escape_string($_POST['activity']);
$level = $_POST['level'];

$sql = "INSERT INTO lottt ".
       "(name, activity, level) ".
       "VALUES('$name','$activity', '$level')";
mysql_select_db('lot');
mysql_close($con);
}
?>

When i insert the data via the input fields it gets logged to the js console fine like so [Object, Object, Object]0: Objectname: "character_name"value: "aSD"__proto__: Object1: Object2: Objectlength: 3__proto__: Array[0] but nothing is inserted into the mysql database after a quick check.

  • 写回答

1条回答 默认 最新

  • dongyue9864 2015-02-03 02:45
    关注

    You need to run the query to save it. I'll answer it to the mysql_* library, even though it is deprecated.

    This is how the flow is supposed to go:

    $con = mysql_connect(....) or die();
    mysql_select_db('database');
    
    $name = mysql_real_escape_string($_POST['name']);
    $activity = mysql_real_escape_string($_POST['activity']);
    $level = $_POST['level'];
    $sql = "INSERT INTO lottt ".
           "(name, activity, level) ".
           "VALUES('$name','$activity', '$level')";
    
    if(!mysql_query($sql)) {
        die('Error: ' . mysql_error());
    } else {
        echo 'saved';
    }
    

    You should stop using mysql_* functions. The library is deprecated.

    You should look into using PDO or MySQLi as they are more modern libraries and while you might have to overcome a hurdle to learn it, being competent in those libraries will do you the world of good!

    Resources:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路