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.

    评论

报告相同问题?