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
Try this
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:
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:
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:
And your JavaScript w/ ajax:
PHP example: