Change SQL using Javascript (with buttons) - javascript

I have a table displaying data from a database, buttons with javascript that update the sql and display the result on the table, till here all good, my problem is I want to put more buttons with different SQL queries, this only check the value="" of the button and use it as $var on the final SQL
Note that I mark the buttons id as btn_01, btn_02..
function load_data(query) {
$.ajax({
url:"fetch",
method:"POST",
data:{query:query},
success:function(data) {
$('#result').html(data);
}
});
}
var names = new Array('Italy','Denmark','France','UK');
$(".btn").bind("click",function(e) {
var btn = this.id.split('_');
var data=( show_mssg(btn[1]) );
load_data(data);
});
function show_mssg(id) {
return names[id];
}
here is the "fetch" file, is a php file to conned to db
$connect = mysqli_connect("dbhost","dbname","user","pass");
$output = '';
if(isset($_POST["query"])) {
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "SELECT * FROM `Developers` WHERE `country` LIKE '%".$search."%' ";
}
$result = mysqli_query($connect, $query);
if ($result) {
$output='<table></table>';
}
echo "$output";
and the html buttons
<span id='btn_0' class="btn" value='Italy'>Italy</span>
<span id='btn_1' class="btn" value='Denmark'>Denmark</span>
<span id='btn_2' class="btn" value='France'>France</span>
<span id='btn_3' class="btn" value='UK'>UK</span>
finally to display the result
<div id="result"></div>
I tried to make similar function with a different array for different buttons but seems like is not working, also i tried with
if(isset($_POST["query"]))
to not necessary make another function and later try to bind the click on different buttons and just change the sql.

Related

Button for Updating a Database single entry with PHP AJAX Call

For Future Readers, this was my first question and the answer has been found (read comments and replies below):
First of all, i've searched in Stackoverflow and i didn't found an answer for a similar problem.
i would like to link a html Button (among many buttons) with a JQuery function. The function shall execute AJAX method like so :
HTML Code in a separated file index.php:
<button id="submitbtn" type="button" class="btn btn-success">UPDATE</button>
JQuery Function :
$('#submitbtn').on('click', function(){
var id = $(this).data('id');
$.ajax({
url: 'includes/updatequery.php',
type: 'POST',
data: {id:id},
success: function(data){
if (data) {
console.log("updated");
} else {
$('#error').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown){
$('#error').html("oops" + errorThrown);
}
});
});
Here is the PHP file that should be called by AJAX Method :
<?php
include("src/db.php");
$query = "UPDATE mytable SET job='completed' WHERE id=id";
mysqli_query($conn, $query);
?>
The problem is that i CANNOT link the ID of the clicked button (because there are many buttons) to the ID of the Database Entry in order to update the Data in the Database according to this specific button.
Now i would like to have the results updated LIVE after updating the Database.
This is the PHP code that output menu items (items stored in the same Database table as before) and in front of every menu item, a badge should be displayed (with a value within it : "completed" or "not completed") :
<?php
foreach($data as $d) {
$id = $d['id'];
$mystatus = $d['status'];
?>
<li class="nav-item">
<a class="nav-link clickable blueMenuItem" id="nav-location" data-id="<?php echo $d['id']; ?>">
<i class="nav-icon fas <?php echo $d['icon']; ?>"></i>
<p><?php
echo $d["title"];
if ($d['type'] == "job") { ?>
<span id="updatedicon" class="right badge <?php if($mystatus == "completed"){echo "badge-success";} else {echo "badge-danger";}?>"><?php setJob($con, $id)?></span><?php
} ?>
</p>
</a>
</li><?php
}
?>
Here is the PHP file where the setJob method is defined :
<?php
function setJob($con, $idd) {
$sql = "SELECT status FROM mytable WHERE id=$id";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $row => $value) {
echo $value;
}
}
}
?>
Any suggestions?
Thanks
Use the data-id attribute to add the id:
<button id="submitbtn" data-id="<id>" type="button" class="btn btn-success">UPDATE</button>
https://www.w3schools.com/tags/att_global_data.asp
By default, jQuery ajax uses a Content-Type of application/x-www-form-urlencoded; charset=UTF-8. This means in PHP the POST values can be accessed using $_POST. If using a Content-Type of application/json, you will need to do this.
include("src/db.php");
$id = $_POST['id']; // make sure to sanitize this value
$query = "UPDATE mytable SET job='completed' WHERE id=$id";
mysqli_query($conn, $query);
The above example only demonstrates how to reference the id value from the POST. However, this is not secure as-is. Make sure to sanitize the value as well as protect yourself from SQL Injection using prepared statements. Prepared Statements allow you to bind variables to SQL queries which are sent separately to the database server and can not interfere with the query itself.
Updated HTML - added data-id="" to button and replace with id
<button id="submitbtn" data-id="<id>" type="button" class="btn btn-success">UPDATE</button>
Updated jQuery - use attr to get the id of row/record by using data-id attribute
$('#submitbtn').on('click', function(){
var id = $(this).attr('data-id');
$.ajax({
url: 'includes/updatequery.php',
type: 'POST',
data: {id:id},
success: function(data){
if (data) {
console.log("updated");
} else {
$('#error').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown){
$('#error').html("oops" + errorThrown);
}
});
});

How to make like button stay as liked state when refresh the page

I'm working on a Like button. It's working just fine unless user refresh the page. When page is not refreshed the like button itself change the style and add 1 to the like count if user click on it. But when the page is refreshed the like button remain the like count and the previous style then add 1 to the like count and change to the new style if user click on it. That's the problem.
The like button looks like this:
Here is the Javascript code:
function addLikes(id,action) {
$.ajax({
url: "like.php",
data:'post_id='+id+'&action='+action,
type: "POST",
success: function(data){
var likes = parseInt($('#likes-'+id).val());
switch(action) {
case "like":
$('#like_area'+id).html('<i id="like'+id+'" class="fas fa-thumbs-up react"></i> Thích');
$('#like_area'+id).attr("onclick", "addLikes("+id+",'unlike')");
likes = likes+1;
$('#like_area'+id).addClass("liked");
break;
case "unlike":
$('#like_area'+id).html('<i id="like'+id+'" class="far fa-thumbs-up react"></i> Thích');
$('#like_area'+id).attr("onclick", "addLikes("+id+",'like')");
$('#like_area'+id).removeClass("liked");
likes = likes-1;
break;
}
$('#likes-'+id).val(likes);
if(likes>0) {
$('#people_liked'+id).html(kFormatter(likes));
$('#user_liked'+id).attr("style", "display:block;");
} else {
$('#user_liked'+id).attr("style", "display:none;");
}
}
});
}
Here is the PHP code in like.php:
<?php
session_start();
require $_SERVER['DOCUMENT_ROOT'] . '/require/serverconnect.php';
$username = $_SESSION['username'];
$post_id = $_POST['post_id'];
$action = $_POST['action'];
if(!empty($post_id)) {
switch ($action) {
case 'like':
$query = "INSERT IGNORE INTO tintuc_post_likes (username_of_like, liked_post_id) VALUES ('$username','$post_id')";
$result = mysqli_query($con, $query);
break;
case 'unlike':
$query = "DELETE FROM tintuc_post_likes WHERE username_of_like = '$username' AND liked_post_id = '$post_id'";
$result = mysqli_query($con, $query);
break;
}
}
?>
PHP Select code in index.php:
<?php
$sql = "SELECT tintuc_posts.id, tintuc_posts.author, tintuc_posts.content, tintuc_posts.timeofpost, tintuc_posts.has_comment, tintuc_posts.avatar, tintuc_posts.has_image, tintuc_posts.image, tintuc_posts.username, tintuc_posts.c4id, COUNT(tintuc_post_likes.like_id) as likes, GROUP_CONCAT(accounts.name separator '|') as liked_by
FROM tintuc_posts
LEFT JOIN tintuc_post_likes
ON tintuc_posts.id = tintuc_post_likes.liked_post_id
LEFT JOIN accounts
ON tintuc_post_likes.username_of_like = accounts.username
GROUP BY tintuc_posts.id
ORDER BY tintuc_posts.id DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
?>
Here is the tables:
As this is probably your answer:
In your screenshot, you have the yellow thumb in the tool bar, is this what you want to be selected/highlighted when they page refresh? To show they have already liked it?
Assuming this is the case, when you run the code to draw that button, you need to get a list of users who have like it, and compare to the current user, and then if current user is in that list, add the "selected" class (or whatever you do on click initially) so the button looks selected.
I am not a PHP developer, but in pseudo code would be something like:
var hasLiked = ListOfUserLinks.IndexOf(currentuserId) >= 0;
<button name="like" class="button <%hasLiked ? 'likedState' : ''%>" />
You can see you just adjust the classes based on whether the user has liked it, but it is done at page load time, as this is the initial state of the page.

During click of load more button, some divs become unclickable

I have undercome a problem when implementing a "Show more button"
The page will initially display 5 rows of data, then on click the button will make a call to a php function through ajax and load more results, ultimately displaying them on the page. It does this very well.
The problem is that each of the divs are clickable in their own right to allow for user interaction. Before clicking the button the first 5 are clickable and work correctly, however after loading the first 10, the first 5 become unclickable and the rest work as expected.
See my code here:
HTML:
<div class="col-sm-12 col-xs-12 text-center pushDown">
<div id="initDisplay">
<?php
// Display all subjects
echo displaySubjects($limit);
?>
</div>
<div id="show_result"></div>
<button id="show_more" class="text-center pushDown btn btn-success">Show More</button>
</div>
On click of the button the following is happening:
JQuery:
<script>
$("#show_more").on("click", function() {
$("#initDisplay").fadeOut();
});
/* This bit is irrelevant for this question
$("#addBtn").on("click", function(){
addSubject();
});
*/
var stag = 5;
$("#show_more").on("click", function(){
stag+=5;
console.log(stag);
$.ajax({
dataType: "HTML",
type: "GET",
url: "../ajax/admin/loadSubjects.php?show="+stag,
success: function(result){
$("#show_result").html(result);
$("#show_result").slideDown();
}
});
var totalUsers = "<?php echo $total; ?>";
if(stag > totalUsers) {
$("#show_more").fadeOut();
}
});
</script>
My PHP page and functions are here:
<?php
include_once '../../functions/linkAll.inc.php';
$limit = filter_input(INPUT_GET, "show");
if (isset($limit)) {
echo displayUsers($limit);
} else {
header("Location: ../../dashboard");
}
function displaySubjects($limit) {
$connect = db();
$stmt = $connect->prepare("SELECT * FROM Courses LIMIT $limit");
$result = "";
if ($stmt->execute()) {
$results = $stmt->get_result();
while($row = $results->fetch_assoc()){
$id = $row['ID'];
$name = $row['Name'];
$image = $row['image'];
if($image === ""){
$image = "subjectPlaceholder.png"; // fail safe for older accounts with no images
}
$result .=
"
<div class='img-container' id='editSubject-$id'>
<img class='miniProfileImage' src='../images/subjects/$image'>
<div class='middle' id='editSubject-$id'><p class='middleText'>$name</p></div>
</div>
";
$result .= "<script>editSubjectRequest($id)</script>";
}
}
$stmt->close();
return $result;
}
The script being called through this is:
function editSubjectRequest(id) {
$("#editSubject-"+id).click(function(e) {
e.preventDefault(); // Prevent HREF
console.log("You clicked on " + id);
$("#spinner").show(); // Show spinner
$(".dashContent").html(""); // Empty content container
setTimeout(function() {
$.ajax({ // Perform Ajax function
url: "../ajax/admin/editSubjects.php?subjectID="+id,
dataType: "HTML",
type: "POST",
success: function (result) {
$("#spinner").hide();
$(".dashContent").html(result);
}
});
}, 1500); // Delay this for 1.5secs
});
}
This will then take the user to a specific page depending on the subject which they clicked on.
Your problem is duplicate ids. First five items are present on the page always. But when you load more, you are loading not new items, but all, including first five. As they are already present on the page, their duplicates are not clickable. The original items are however clickable, but they are hidden.
Here is what you need:
$("#show_more").on("click", function(){
$("#initDisplay").html("");
});
Don't just fadeOut make sure to actually delete that content.
This is the easiest way to solve your issue with minimum changes. But better option would be to rewrite your php, so it would load only new items (using WHERE id > $idOfLastItem condition).
Also you don't need that script to be attached to every div. Use common handler for all divs at once.
$("body").on("click", "div.img-container", function() {
var id = $(this).attr("id").split("-")[1];
});
When you are updating a DOM dynamically you need to bind the click event on dynamically added elements. To achieve this change your script from
$("#editSubject-"+id).click(function(e) {
To
$(document).on("click","#editSubject-"+id,function(e) {
This will bind click event on each and every div including dynamically added div.

Jquery Post not working correctly?

I have been working on Like and Unlike feature with jquery, ajax and php. My problem is little bit difficult to understand. Lets try to understand it first.
I have 2 php pages, viewProfile.php and LikeMail.php. LikeMail.php is being called by ajax function in viewProfile.php.
Here is Section of viewProfile.php page's description
-----------------
| Like/Unlike |
-----------------
Here is button which actually comes from LikeMail.php by this ajax function
function like()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState==4 && req.status==200)
{
document.getElementById('Like').innerHTML=req.responseText;
}
}
req.open('POST','LikeMail.php','true');
req.send();
}
setInterval(function(){like()},1000);
HTML:
<div id="Like"></div>
Output is being shown here in this div. Button above may be Like or Unlike depends on the condition in LikeMail.php which will be described below in LikeMail.php description section.
When one of them (buttons) Like or Unlike is clicked. It then calls respective jquery click function which sends post request to LikeMail.php.I have mentioned Indirect page in title because Like or Unlike buttons actually exists in LikeMail.php page. But due to ajax call these buttons are being shown in viewProfile.php page. So I then send post requests through viewProfile.php to actual page LikeMail.phpIt is jquery post for Unlike button
$(document).ready(function(){
$('#Unlike').unbind().click(function(){
$.post("LikeMail.php",
{Unlike: this.id},
function(data){
$('#response').html(data);
}
);
});
});
It is jquery post or Like button
$(document).ready(function(){
$('#Like').unbind().click(function(){
$.post("LikeMail.php",
{Like: this.id},
function(data){
$('#response').html(data);
}
);
});
});
End of description section of viewProfile.php page
Here is Section of LikeMail.php page's description
Like or Unlike button is shown in viewProfile.php page depends upon this code:
$check_for_likes = mysqli_query($conn, "SELECT * FROM liked WHERE user1='$user1' AND user2='$user2'");
$numrows_likes = mysqli_num_rows($check_for_likes);
if (false == $numrows_likes) {
echo mysqli_error($conn);
}
if ($numrows_likes >= 1) {
echo '<input type="submit" name="Unlike" value="Unlike" id="Unlike" class="btn btn-lg btn-info edit">';
}
elseif ($numrows_likes == 0) {
echo '<input type="submit" name="Like" value="Like" id="Like" class="btn btn-lg btn-info edit">';
}
Button depends upon these two above conditions.
Now when Like button is clicked, post request from viewProfile.php comes here
if(isset($_POST['Like'])) //When Like button in viewProfile.php is clicked then this peace of code inside if condition should run and insert some record in database
{
$total_likes = $total_likes+1;
$like = mysqli_query($conn, "UPDATE user SET user_Likes = '$total_likes' WHERE user_id = '$user2'");
$user_likes = mysqli_query($conn, "INSERT INTO liked (user1,user2) VALUES ('$user1','$user2')");
$query3 = "INSERT INTO notification (user1, user2, alert, notificationType) VALUE ('$user1','$user2','unchecked','like')";
if (mysqli_query($conn, $query3)) {
echo "Like";
} else {
echo mysqli_error($conn);
}
}
Similarly when Unlike button is clicked. This peace of code should run.
if(isset($_POST['Unlike'])) //This is the condition for Unlike button. It should delete record from databse
{
$total_likes = $total_likes-2;
$like = mysqli_query($conn, "UPDATE user SET user_Likes='$total_likes' WHERE user_id='$user2'");
$remove_user = mysqli_query($conn, "DELETE FROM liked WHERE user1='$user1' AND user2='$user2'");
$query3 = "DELETE FROM notification WHERE user1='$user1' AND user2='$user2' AND notificationType='like'";
$check = mysqli_query($conn, $query3);
if ($check) {
echo "Unlike";
} else {
echo mysqli_error($conn);
}
}
Problem:
Main problem which I faced is that when I click Like or Unlike both executes the condition of Like button code. Both inserts the data into database as Unlike condition should delete data from database but it also inserts data as condition for Like button do. Kindly can you please help me that how to tackle this problem. Thanks in advance!
Update:When I delete all the respective code for Like button. The condition for Unlike button starts working correctly.
I think there's a duplicated ID somewhere, perhaps the DIV. Take a look at this.
<div id="Like_2"></div>
<input type="submit" name="Unlike" value="Unlike" id="Unlike" class="btn btn-lg btn-info edit">
<input type="submit" name="Like" value="Like" id="Like" class="btn btn-lg btn-info edit">
<div id="response"></div>
$(document).ready(function(){
$(document).on('click','#Unlike', function(){
$('#response').html(this.id);
//ajax call
});
$(document).on('click','#Like', function(){
$('#response').html(this.id);
//ajax call
});
});
And the javascript function:
function like()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState==4 && req.status==200)
{
document.getElementById('Like_2').innerHTML=req.responseText;
}
}
req.open('POST','LikeMail.php','true');
req.send();
}
setInterval(function(){like()},1000);
https://jsfiddle.net/wx38rz5L/2103/

How to call a PHP function within a page using AJAX

I wrote a php function which does the job perfectly if it is called standalone by PHP page. but I want to integrate this function in a program and want to call it when a button is clicked.
My PHP function is
function adddata($mobile){
// outside of this function, another database is already selected to perform different
//tasks with program's original database, These constants are defined only within this
//this function to communicate another database present at the same host
define ("HOSTNAME","localhost");
define ("USERNAME","root");
define ("PWD","");
define ("DBNAME","budgetbot");
// link to mysql server
if (!mysql_connect(HOSTNAME,USERNAME,PWD)) {
die ("Cannot connect to mysql server" . mysql_error() );
}
// selecting the database
if (!mysql_select_db(DBNAME)) {
die ("Cannot select database" . mysql_error() );
}
//inserting phone number into database
$query = "INSERT INTO `verify_bot` (phone_number) values('".$mobile."')";
if(!mysql_query($query)){
die( mysql_error() );
}
// wait for 2 seconds after adding the data into the database
sleep(2);
$query = "SELECT * FROM `verify_bot` WHERE phone_number = ".$mobile;
$result = mysql_query($query) or die( mysql_error() );
// if more than one records found for the same phone number
if(mysql_num_rows($result) > 1){
while($row = mysql_fetch_assoc($result)){
$data[] = $row['response'];
}
// return an array of names for the same phone numbers
return $data;
}else{
// if only one record found
$row = mysql_fetch_assoc($result);
$response = $row['response'];
return $response;
}
// end of function
}
HTML Code is written as
<form action="self_page_address_here" method="post" accept-charset="utf-8" class="line_item_form" autocomplete="off">
<input type="text" name="mobile_number" value="" placeholder="(000) 000-0000" class="serial_item" size="20" id="serialnumber_1" maxlength="10" />
<button id="verify" class="btn btn-primary">Verify</button>
<button id="cname" class="btn btn-primary"><!-- I want to print return value of the php function here --></button>
</form>
I want to call this function and assign the return value to a javascript variable by ajax/jquery.
My code to do this is...
<script type="text/javascript" language="javascript">
$('#verify').click(function(){
var value = $( ".serial_item" ).val();
//I have some knowledge about php but I am beginner at ajax/jquery so don't know what is happening below. but I got this code by different search but doesn't work
$.ajax({
url : "add_data.php&f="+value,
type : "GET"
success: function(data){
document.getElementById("cname").innerHTML = data;
}
});
});
</script>
I would like to share that the above javascript code is placed outside of documnet.ready(){}
scope
Any help would be much appreciated.
Thanks
Because your <button> elements have no type="button" attribute, they're supposed to submit the form using normal POST request.
You should either use type="button" attribute on your buttons, or prevent default form submission using event.preventDefault():
$('#verify').click(function(event){
event.preventDefault();
var value = $( ".serial_item" ).val();
$.ajax({
// there's a typo, should use '?' instead of '&':
url : "add_data.php?f="+value,
type : "GET",
success: function(data){
$("#cname").html(data);
}
});
});
[EDIT] Then in add_data.php (if you call AJAX to the same page, place this code at the top, so that no HTML is rendered before this):
if(isset($_GET['f'])){
// call your function:
$result = adddata(trim($_GET['f']));
// if returned value is an array, implode it:
echo is_array($result) ? implode(', ', $result) : $result;
// if this is on the same page use exit instead of echo:
// exit(is_array($result) ? implode(', ', $result) : $result);
}
Make sure you escape the value on $query.

Categories

Resources