abcdefghijklmnop
abcdefghijklmnop

Reputation: 45

ajax code not updating in MySQL database

Have an ajax code which displays errors and success on the page but doesn't actually update the database when I click submit button.

The form has a select dropdown and the options are populated from the database. I know the PHP code works because without the ajax, the table gets updated so I must be missing something in the ajax but can't find?

form.php with the script

<form id="test" name="test" method="POST" action="test.php">
            <select id="updateid" name="updateid">
                <option value="">- Please Select -</option>
                <?php
                    $sql = "SELECT updateid, name FROM test";
                    $res = $con->query($sql);
                    while($row = mysqli_fetch_array($res)){
                    echo "<option value=".$row['updateid'].">".$row['name']."</option>";
                    }
                ?>
                </select>
<input type="submit" value="Submit" name="submit" id="submitbut" />
</form>



 $(document).ready(function(){
$('#submitbut').click(function(e){

        var updateid = $("#updateid").val();

            if(updateid.length == 0){
            $("#success").text("make a selection.");
            $("updateid").focus();
        }
    else{

        var dataString = 'updateid='+ updateid

        $.ajax({
            type:'POST',
            url:'test.php',
            data: {updateid:dataString}
        }).done(function(){
            $('#success').text('success!');
        });
    }
        e.preventDefault();
        });    
});

test.php

<?php       
    if(isset($_POST['submit'])) {

        $updateid= $_POST['updateid'];

        $sql = "UPDATE `test` SET `test`='abcdegfhi' WHERE `updateid` = '$updateid'";

        if (mysqli_query($con, $sql)) {

            echo "ok";
        } else {
            echo "nope";
    }
}
?>

Upvotes: 0

Views: 603

Answers (2)

Tomasz Szuba
Tomasz Szuba

Reputation: 439

$_POST['submit'] is not set. All $_POST data comes from ajax request - not html post request ( You have used the "e.preventDefault()" ).

You can set data as follows:

{updateid:dataString, submit: true}

Upvotes: 0

Marc B
Marc B

Reputation: 360592

    var dataString = 'updateid='+ updateid
                     ^^^^^^^^^^^

        data: {updateid:dataString}
               ^^^^^^^^^

Your PHP script will be receiving:

 updateid=updateid=42
    ^--- $_POST key
          ^^^^^^^^^^^ $_POST value

which you then blindly insert into your query (enjoy your server getting totally pwn3d via your sql injection attack vulnerability):

$sql = "[..snip..]WHERE `updateid` = 'updateid=42'"
                                     ^^^^^^^^^^^^^

Upvotes: 4

Related Questions