Home > database >  Form with AJAX always returns 0
Form with AJAX always returns 0

Time:11-30

So I'm trying to send information from an AJAX call in a form to a table in SQL. This is the form:

        <form name="likedGames"  method="post" id="likeForm" action="like.php">
          <input type="text" name="liked" id="likeInput" value="123"/><button type="submit" id="likeButton"><i id="like" ></i></button>
        </form>

This is the AJAX call:

$(document).ready(function () {
  $("#likeForm").submit(function (event) {
    var liked = $("#likeInput").val();
    $.ajax({
      type: "POST",
      url: "like.php",
      data: liked,
    }).done(function (data) {
      console.log(data);
    });
    event.preventDefault();
  });
});

And this is like.php:

<?php

    $started = session_start();
        $conn = new mysqli('localhost','root','password','mydb');
    if(!$conn){
        die("Connection Failed: ".mysqli_connect_error());
    }

    $userId = $_SESSION['userId'];
    // $like = $_POST['liked'];
    $like = isset($_POST["liked"] ) ? $_POST["liked"]: '';

        $stmt = $conn->prepare("INSERT INTO likes(user_id, gameId) VALUES (?,?)");
        $stmt->bind_param("ss", $userId, $like);
        $execval = $stmt->execute();
        $stmt->close();
        $conn->close();

?>

As you might see, there is a commented line in like.php, because that was my first attempt to retrieve the info from the liked input, but it didn't work.

What happens right now when a user clicks into the submit button is that the database gets indeed updated, but the gameId column always gets 0 as the value. Shouldn't it get 123 (or whatever the user types in the input)? I'm quite lost at the moment, so any help will be highly appreciated. Also, if there is anything I can do to improve the post, just let me know. Thank you!

CodePudding user response:

I guess, your ajax-call should look like this:

$.ajax({
  type: "POST",
  url: "like.php",
  data: {liked : liked},
}).done(...)

See: https://api.jquery.com/jquery.ajax/

  • Related