weixin_33690367 2017-09-29 11:31 采纳率: 0%
浏览 7

使用Ajax发布数据

I've been trying to post data using AJAX that will update a field in my database however I am having trouble doing so. Everything seems like it should run fine and I get no errors in the console but I've no idea why my db won't update.

Can someone help me out here please?

AJAX:

function ajaxUpdate() {
        var arr = {var1: name, var2: age};
            $.ajax({
                url: 'ajax/confirm.php',
                type: 'POST',
                data: JSON.stringify(arr),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(data) {
                    console.log("success");
                }
            });
        }

Confirm.php:

$name=$_POST['var1'];
$age=$_POST['var2'];

if($name == "Stuart") {
    mysqli_query($connection,"UPDATE people SET age='$age'");
}
else if($name == "Peter") {
    mysqli_query($connection,"UPDATE people SET age='$age'");
}

The connection to my database is working as I have $connection setup and went to the page /ajax/confirm.php in my browser and I see "Connection successful" in my console as I defined if successful.

So I am unsure as to why this isn't updating?

Are my values not being posted correctly?

I'm new to AJAX so forgive me if this is something very simple!

Thanks

  • 写回答

2条回答 默认 最新

  • weixin_33737774 2017-09-29 11:39
    关注

    Try the following:

    function ajaxUpdate() {
        var arr = {var1: name, var2: age};
            $.ajax({
                url: 'ajax/confirm.php',
                type: 'POST',
                data: arr,
                success: function(data) {
                    console.log("success");
                }
            });
    }
    

    Instead of converting the object into json string send it as is.

    Edit: Also remove dataType and probably contentType too. Your code is at risk of SQL Injection. Look into prepared statements and escaping mysql data.

    评论

报告相同问题?

悬赏问题

  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来