简体   繁体   中英

How do I update my database with mysqli and javascript

I have a website which basically is an audioplayer and an integrated lyricviewer on screen, which the user should be able to sync with the music they hear playing. I only have one problem, and that is; How on earth do I, from a javascript function, call a mysqli update statement? When the user clicks a save button, content gets thrown into a div, which I want the PHP after the JavaScript has been run to take that content and put it into a database.

What is the best way to do that?

Why doesn't this work?

        function saveinPHP() {
        //alert("Came here");
        //var superstr = $( "#savelyric" ).text();
        var superstr = 'lol';
        $.ajax({
        type: "POST",
        url: "includes/sendlyrics.php",
        data: superstr,
        cache: false,
        contentType: false,
        processData: false,
        success:  function(data){
            alert("---"+data);
            alert("Settings has been updated successfully." + data + "~~~" + superstr);
            //window.location.reload(true);
        }
    });
    }

And then the PHP:

    <?php 
include ('db_connect.php');

$data = $_POST['data'];

    $query = "UPDATE song SET time=". $data ." WHERE id='1'";
    mysqli_query($query);
?>

Write PHP in a totally separate dedicated file that takes POST variables, constructs an SQL query, and inserts them into a database. Then have your JavaScript function send the data to this PHP file using a POST request.

JavaScript in the browser cannot interact with the database. It can only send GET/POST requests to the server which can catch those requests and put the attached data into the database.

First , when you specify a string as data , jQuery will send it as is.

The string you are using "lol" is not formatted in either of the standard formats for POST data that are understood by PHP.

$_POST , therefore, has no data in it.

Pass jQuery an object instead:

data: { data: superstr }

Second , false is not a content-type of either of the standard formats mentioned above. jQuery will use an appropriate content-type by default. Remove this override:

contentType: false,

Third , processData: false, will break the conversion of the object into form encoded data. Remove it.

Fourth , strings in SQL must be quoted. You aren't quoting data .

 $query = "UPDATE song SET time='$data' WHERE id='1'";

Note this is still vulnerable to SQL injection and you should fix that .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM