skip to Main Content

I am creating a page for blog posts and I am having some trouble with getting my ‘Like’ (Heart) function to work using AJAX.

It needs to submit when the heart is clicked which should submit a new row into my PHP database without page refresh, but the form submission is not working/posting.

This is my first time submitting form using AJAX so sorry if I’m being a noob.

My PHP table has 5 columns – id, content, userID, username & date.

$(document).ready(function() {
  $("#heart").click(function() {
    if ($("#heart").hasClass("liked")) {
      $("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
      $("#heart").removeClass("liked");
    } else {
      $("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
      $("#heart").addClass("liked");
      $("form#myform").submit(function(event) {
        event.preventDefault();
        var title = $("#title").val();
        var user = $("#user").val();
        var userID = $("#userID").val();
        var dte = $("#dte").val();

        $.ajax({
            type: "POST",
            url: "../PHP/user_functions.php",
            data: "title=" + content + "&user=" + user + "&dte=" + dte + "&userID=" + userID,
            success: function(){alert('success');}
        });
    });
    }
  });
});
.fa-heart-o {
  font-size:24px;
  color:black;
  cursor: pointer;
}

.fa-heart {
  font-size:24px;
  color: red;
  cursor: pointer;
}

.ggg{
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">




<form id="myform" action="../PHP/user_functions.php" method="post">

    <span class="" id="heart"><i class="fa fa-heart-o" aria-hidden="true"></i></span>

    <input type="hidden" id="title" value="How To Guide Title Example" name="content">
    <input type="hidden" id="user" value="TestBot" name="username">
    <input type="hidden" id="userID" value="<?php echo $userID ?>" name="sessionID">
    <input type="hidden" id="dte" value="<?php echo date('Y/m/d H:i:s'); ?>" name="date">

    <input class="ggg" type="submit" id="submitButton" name="submitButton" value="Submit">

</form>

and my PHP page..

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

$username = $_POST['username'];
$userID = $_POST['userID'];
$date = $_POST['date'];
$content = $_POST['content'];

$sql = 'INSERT INTO `likes-blog` (username, userID, date, content) VALUES (:username, :userID, :date, :content)';
$stmt = $dbh->prepare($sql);
                                                              
$stmt->execute(['username' => $username, 'userID' => $userID, 'date' => $date, 'content' => $content]);

?>
<?php
}
?>

2

Answers


  1. Try this

    <script>
    $(document).ready(function() {
      $("#heart").click(function() {
        if ($("#heart").hasClass("liked")) {
          $("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
          $("#heart").removeClass("liked");
        } else {
          $("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
          $("#heart").addClass("liked");
            let title = $("#title").val();
            let user = $("#user").val();
            let userID = $("#userID").val();
            let dte = $("#dte").val();
        //Ajax
                    $.ajax({
                    url: "../backend.php", //This your backend file PHP
                    data: {
                        "title": title,
                        "user" : user,
                        "userID" : userID,
                        "dte" : dte
                    },
                    dataType: "JSON",
                    type: "POST",
                    beforeSend: function() {
                     //Function for sweetalert like loading or any
                    },
                    success: function(data) {
                      //if succes
                      console.log(data);
                    },
                    complete: function() {
                       //Function while ajax complete
                    },
                    error: function(data) {
                       //if error
                        console.log("ERROR");
                        console.log(data);
                    }
                }); 
        }
      });
    });
    </script>
    Login or Signup to reply.
  2. In your backend/PHP file, treat it as if the POST data is always getting passed into it.

    Think about this: You’re only going to run the code that’s controlling the data to be sent to your database when $_POST[‘submitButton’] is passed to the page. When you’re sending your data to your PHP file, it does nothing because you’re telling it to only run that code if $_POST[‘submitButton’] is set (has a value).

    Secondly, I want to mention that in your ajax, it’s much easier to structure the POST data like this, and also cleaning up the success function to look a little better; you can also pass through a response like I’ve shown here, that the PHP file will send back in case of an error or you can have your PHP file send back a custom string with a success message:

    $.ajax({
        type: "POST",
        url: "../PHP/user_functions.php",
        data: {
            title: content,
            user: user,
            dte: dte,
            userID: userID
        },
        success: function(response) {
            alert(response);
        }
    })
    

    I would also definitely look into MySQLi prepared statements and looking at how to better protect against SQL injection.

    Take a look at these PHP functions and how to use them, I’ve written up a very basic example of something you could use, but you can also change it to fit your needs, just make sure you use the functions properly:

    // Data:
    $dataOne = 5; // <-- integer
    $dataTwo = "Hello, world" // <-- string
    // in the ...bind_param() function, where "is" is located, in order, you'd use i for integer and s for string, there are others but these are the basic ones, you can find more documentation online for this.
    // For example if you passed through the $dataTwo variable and then the $dataOne variable, it would be "si" because the variable with string content gets passed first and the variable with an integer passed second.
    // For the ? marks in the $sql string, those directly relate to how many values you're going to pass through. In the computer, ? will be translated to each value passed through in the ...bind_param() function, in order, and insert them into the selected table/columns, in order. Basically, the code below will insert $dataOne into the "column1Name" column and will insert $dataTwo into the "column2Name" column in the "tableName" table.
    
    $sql = "INSERT INTO "tableName" ("column1Name", "column2Name") VALUES (?, ?);";
    $stmt = mysqli_stmt_init($conn)
        or die("Could not initiate a connection.");
    mysqli_stmt_prepare($stmt, $sql)
        or die("Could not prepare SQL statement.");
    mysqli_stmt_bind_param($stmt, "is", $dataOne, $dataTwo)
        or die("Could not bind SQL parameters.");
    mysqli_stmt_execute($stmt)
        or die("Could not execute SQL sequence.");
    mysqli_stmt_close($stmt)
        or die("Could not close SQL connection.");
    

    Seems complicated and there is more to learn, but instead of being like everyone else on here that just expects you to figure it out yourself, I figured I’d give you an example. I’d also recommend learning how to wash your POST data once your AJAX sends it to your PHP file. You can also use the above method for securely deleting and updating rows/columns/values in your database. (If you’re not actually inserting data, for example if you’re using a delete statement, you can simply not use the …bind_param() function since it would serve no purpose there.

    Also, I believe part of your issue is that you’re also submitting the form itself and I don’t think even executing the Ajax code. Part of the reason why ajax is useful is because it allows you to submit POST and GET data to an external handler file (your PHP/backend code/file) without having to have the page reload, which has many other benefits, there are only some cases where you’d actually HAVE to submit the form like would be done by default without ajax. Technically, you don’t even need to use a form if you’re using ajax, in most cases. (but not all). For example you could get rid of the tags altogether, and just have your inputs stay as normal; you can use JS to grab the values. Set your submit button to type="button" (if it’s set to submit, the page will reload, which kind of defeats the purpose; type="button" will not reload the page).

    So, here’s a rough example of what I’m talking about:

    HTML:

    <input type="text" id="firstName" name="firstName" placeholder="What's your first name?"/>
    <input type="text" id="lastName" name="lastName" placeholder="What's your last name?"/>
    <button type="button" id="submit">Submit</button>
    

    And your JavaScript w/ ajax:

    $("#submit").on("click", () => {
        // Get the current value of the input textbox:
        let first = document.querySelector("#firstName").value;
        let last = document.querySelector("#lastName").value;
    
        if (firstName !== null) {
            // Send data to PHP file:
            // Keep in mind when only sending single data values, you can do it like shown here:
            $.ajax({
                type: "POST",
                url: "path to php file here",
                data: {
                    firstName: first,
                    lastName: last
                }
                success: function(response) {
                    // The following is an example of something you can use to error handle. Have the PHP file handle all the errors and simply make the PHP code respond with 1/true if the code was executed correctly, or if there was an issue, have it respond with false/0:
                    if (response == 1) {
                        alert("You've successfully submitted the form.");
                    } else if (response == 0) {
                        alert("Sorry, there was an error submitting the form.");
                    }
                }
            })
        }
    })
    

    PHP example:

    <?php
    require("path_to_database_connect_file"); // I never recommend creating a connection inside another file, so do something like this instead. Have a separate PHP file where its sole purpose is creating and starting a connection with your database. I used the connection variable as $conn, it seems in your original question you were using $dbh. The variable name doesn't really matter I just prefer $conn.
    
    $data = array_filter($_POST);
    $first = $data['firstName'];
    $last = $data['lastName'];
    
    $sql = "INSERT INTO names (firstName, lastName) VALUES (?, ?);";
    $stmt = mysqli_stmt_init($conn)
        or exit(false);
    
    mysqli_stmt_prepare($stmt, $sql)
        or exit(false);
    
    mysqli_stmt_bind_param($stmt, "ss", $first, $last)
        or exit(false); // Both $first and $last have type "string", so the passthrough right after $stmt in this function is "ss" for string-string. If $last was an integer, it would be "si" for string-integer, in that order. Though, if you don't mind everything in your database being string types, which is usually fine for basic stuff, you can still just use "s" for everything. So if you're passing 5 variables into 5 different table columns, you could just do "sssss" there.
    
    mysqli_stmt_execute($stmt)
        or exit(false);
    
    mysqli_stmt_close($stmt)
        or exit(false);
    
    echo true; // If any of the above code fails, it will return false back to ajax in the response callback and exit the script, ajax will see the returned value of "response" as "0" and you will receive the alert message of "Sorry, there was an error submitting the form.". If everything works smoothly with no errors, this script will echo or "return" true back to ajax, and ajax will read "true" as "1", therefore in the success method as shown above, you should get the alert message: "You've successfully submitted the form."
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search