PHP change button text and update database accordingly - javascript

How my function works:
There are 2 buttons 'Accept' and 'Decline'. When user clicks on Accept, the text will change to 'Accepted' and both buttons will be disabled. Colour of text changes too. After this process, i need to update the database table column accordingly.
My current situation:
I'm showing more than one entry with this function.
Currently my codes only work when i have one entry and it doesn't stays the way it should be when I pressed on it after I refresh the page. When there are more than one entry, the button i clicked on the second entry somehow detects the first entry and changes the button in the first entry. And i have no clue on how to update the database accordingly.
Thank You so much in advance.
My Script:
<script>
function accept() {
document.getElementById("accept").disabled = true;
document.getElementById("decline").disabled = true;
document.getElementById("accept").innerHTML = 'Accepted';
document.getElementById("accept").style.color = "green";
}
function decline() {
document.getElementById("decline").disabled = true;
document.getElementById("accept").disabled = true;
document.getElementById("decline").innerHTML = 'Declined';
document.getElementById("decline").style.color = "red";
}
</script>
Accept Button:
<button id="accept" onclick="accept()">Accept</button>
Decline Button:
<button id="decline" onclick="decline()">Decline</button>

You need to learn how to use AJAX:
Using JQuery AJAX makes it much easier.
JS FILE:
$.ajax({
url: "/updateDatabase.php";
type: "POST";
data: {update: value},
beforeSend: function (){
//stuff you like to do before sending.
}
success: function (data){
//do something with return data
}
});
PHP FILE: updateDatabase.php
$var = $_POST["update"]; //make sure this is the same name for the data{} json string
//update database.
echo "Put return value here for JS success data var."
Remember Button state:
<?php if(databaseValue == Accepted) { ?>
<button>Format Button Disabled for accepted</button>
<?php } else { ?>
<button>Format button for enabled</button>
<?php } ?>

Why are you writing two functions if 50% of the operations of the functions are same. I suggest you to write only one function and put a conditional statement in it which checks which button was clicked. It is efficient programming!
Regarding your question can you share a screenshot here, as what exactly is displayed when the operation is performed.

Related

how to stay the color of the button when hit like and refresh page

the default color of my like button is gray and when user hit like button it will run the togglepost "like" and the color will change to red.. i use ajax to insert the data if the user hit like the button... and if the user hit the like button again when its red it will run the togglepost "dislike" and the data from my db will be removed..
button like
<div class="boxcoracao">
<span class="coracao" name="like"><br>   Love</span>
</div>
jquery function
<script>
$(".like").click(function(){
$('.boxcoracao .coracao',this).toggleClass("ativo");
var lpid = $(this).closest("div#buttons").find("#likepid").val();
var lmid = $(this).closest("div#buttons").find("#likemid").val();
if ($('.boxcoracao .coracao',this).hasClass("ativo")){
// update the text to show what the next click would be
togglePost("like", lpid, lmid); // run function
alert("succes");
} else {
// update the text to show what the next click would be
togglePost("dislike", lpid, lmid); // run function
alert("failed");
}
function togglePost(action,lpid,lmid){
$.ajax({
type: "post",
url: "../controller/like_controller.php",
data: "action="+action+"&postid="+lpid+"&postmember="+lmid,
success: function(data){
window.location.reload();
},
error: function(e){
alert("please try again...");
}
});
}
});
</script>
here is my sql query....
function UpdateLikes($postid, $postmember, $likeid, $action){
if ($action == "dislike"){
$sql = "DELETE FROM plike WHERE pl_puid = '$postid' AND pl_uid = '$likeid'";
var_dump($sql);
$result = $this->dbh->prepare($sql);
$result->execute();
return $result->rowCount() ? true : false;
} else{
// before inserting you might want to check if they alredy liked or not before adding their count again.
$query = "INSERT INTO plike SET pl_puid='$postid',pl_memid='$postmember',pl_uid='$likeid'";
$query = $this->dbh->prepare($query);
var_dump($query);
$result = ($query->execute() ? true : false);
return $result;
}
}
here is the gif button..
but my problem is when a user hit the like button and refresh the page the like button will reset to gray instead of red..any idea on how to solve this?.. when user hit like it will be red and when user refresh the page the button will still be red unless the user hit the button again to unlike?..
You'd have to do some Ajax to save the state in your database or some cache on the filesystem for example.
If you want something less robust, you could save the state in a cookie or localstorage. Or even less persistent: in a session variable, that will be gone once the Browser session is lost.
Then when the page is requested check against the presence of your state in database, cache, cookie, session or whatever and give the button the corresponding class in your HTML.
If you are using PHP, for example, it could be done like so:
<?php
$buttonClasses = ['coracao'];
$didLike = your_read_from_cache_function();
if ($didLike)
$buttonClasses[] = 'ativo';
?>
<div class="boxcoracao">
<span class="<?= implode(' ', $buttonClasses) ?>" name="like"><br>   Love</span>
</div>

Update DB based on Div clicked

So basically this little box section displays like recent uploads and a little status that is red for pending and green for uploaded. Right now I made it so when I click on the first red box it will update all the red ticks to green for completed.
How can I make it so that when I click on a single red box, it will only update that tables row to green?
Each upload has an id automatically generated in the Database.
Here is a picture of the box: https://i.gyazo.com/af895f24a2f002df588ca1863f7216fa.png
I have to manually edit the table status to green in order for it to change or I click on 1 and it updates all. I want it to only be on the specific one clicked like displayed in the photo.
Here is another example of it but using a .gif for better demonstration: https://i.gyazo.com/3e974f1a536ba37e71fcb60fc7f19c54.gif
Javascript:
$("#updateStatus").click(function(){
window.location.href = 'connections/updateStatus.php';
});
PHP:
public function redtoGreen(){
$query2 = "UPDATE uploads SET status = 'green'";
$this->conn->query($query2);
header('Location: '.'../index.php');
}
You can achieve through AJAX, sending the ID or wherever you identify your DIV, the code will be something like this:
$("#updateStatus").click(function(){
var id = $(this).attr('id');
$.ajax({
method: 'GET',
url: "connections/updateStatus.php?id="+id
});
});
and at your server side
public function redtoGreen(){
$id = $_GET['id'];
$query2 = "UPDATE uploads SET status = 'green'";
$this->conn->query($query2);
header('Location: '.'../index.php');
}
to change of color, take a look https://jsfiddle.net/k0ye49oh/
You should use AJAX for that (although it works with redirecting back and forth too...).
Do something like this instead:
$("#updateStatus").click(function(){
$.ajax({
url: "connections/updateStatus.php"
});
});
For it to update only a specific row, you have to pass on the ID of the row. Your update query will just update all rows in the table to "green". You can pass the ID on as a parameter and read it in PHP with $id = $_POST["id"] if you posted it by:
$.ajax({url: "connections/updateStatus.php", method: "POST", data: { id: 4 }});
You can read and update it in PHP like:
public function redtoGreen(){
$id = intval($_POST["id"]);
$query2 = "UPDATE uploads SET status = 'green' WHERE id = $id";
$this->conn->query($query2);
}
Another remark: consider using prepared statements for this. SQL queries like this are not good style. You'd rather want something like:
public function redtoGreen(){
$id = $_POST["id"];
$stmt = $db->prepare ("UPDATE uploads SET status = 'green' WHERE id = ?");
$stmt->execute($id);
}
You can also build on the ajax query to change the row color without reloading, doing something like:
$.ajax({
url: "connections/updateStatus.php",
method: "POST",
data: { id: rowno },
success: function (result) {
$("#myrow-" + rowno).css('background-color', 'green');
}
});
However, seeing that you only have one button (#updateStatus) to update ALL rows I think you have several issues with your approach here. If you have the buttons on each row, you have conflicting IDs.
To get both the rowno and the correct button references, you can define your buttons like this:
<button class="updateStatus" data-rowno="1"></button>
When building the table, you will have to put the row number where the 1 is.
Then you can do the javascript part like this:
$(document).ready(function () {
$(".updateStatus").click(function () {
var el = $(this);
var rowno = el.data("rowno");
$.ajax({
url: "connections/updateStatus.php",
method: "POST",
data: { id: rowno },
success: function (result) {
$(el).parent().css('background-color', 'green');
}
});
});
});
Tested and works with HTML like
<table>
<tr><td style="background-color:red;">Blah <button class="updateStatus" data-rowno="1">Update</button></td></tr>
<tr><td style="background-color:red;">Blah <button class="updateStatus" data-rowno="2">Update</button></td></tr>
<tr><td style="background-color:red;">Blah <button class="updateStatus" data-rowno="3">Update</button></td></tr>
<tr><td style="background-color:red;">Blah <button class="updateStatus" data-rowno="4">Update</button></td></tr>
<tr><td style="background-color:red;">Blah <button class="updateStatus" data-rowno="5">Update</button></td></tr>
</table>
You need to update your SQL query to something like below. The current query will set every row for status to 'green' in the uploads table.
UPDATE uploads SET status = 'green' WHERE somecolumn = somevalue
That somevalue needs to be sent from your javascript function call, something like
updatestatus.php?var=somevalue
and use the var as $_GET['var'] on the php page.
Alright, so after some thinking I figured this out.
I thought about changing the html to have divs labeled like this: Hello1 and Hello2. Here is some HTML:
<html>
<div id = "Hello1">
</div>
<div id = "Hello2">
</div>
</html>
You would put the content for each clickable box that you have.
I recommend using Jose Rojas's Javascript.
Here is some PHP to update them accordingly.
With my example, you would just using the $_GET global value instead of a $_POST
<?php
$div = $_GET['div'];
redToGreen($div);
function redToGreen($div) {
$query = "UPDATE uploads SET status = 'green' WHERE div = '{$div}'";
try {
$stmt = $this->conn->prepare($query);
$stmt->execute();
header('Location: ../index.php');
} catch (PDOException $e) {
header('Location: ../pages-500.html');
}
}
?>
If you have any questions, feel free to comment, and I will respond.

Passing JSON through AJAX Plus Button Dilema

so I am attempting to pass some information in a JSON object and have a php page insert the data into a database. However, I am running into some trouble. The "update" button exists in a popup window. The user then clicks "update" and the inputted data should be processed accordingly. However, I fear that I am not even reaching my .click function. None of my alerts seems to be triggered. Below I will point out where issues are occurring. Thank you!
<script>
function updateTable()
{
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
$('#update').click( function() {
alert("help!");
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
#.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
//data: 'popUpString = '+ popupString,
data: popupObj,
cache: false,
success: function(data) {
updateTable();
alert("testing tests");
}
});
});
</script>
<html>
<button onClick="openPopup(<?php echo $row['ID'];?>);"><?php echo $row['ID'];?></button> <!--opens a popup with input options-->
<button id="update">Update</button> <!-- this button is supposed to cause the javascript above to run when clicked, however none of my alerts seem to be reached.-->
</html>
Thank you for looking!
1)I can only guess that you're trying to use JQUERY?
Where do you include the library?
2 )#.ajax isnt valid Jquery function
try $.ajax instead

Saving changes to a dropdown box into a database in CakePHP

I am new to cake and mysql, and am trying to create a simple job tracking app. I want to have a dropdown box for each job with a list of the status' a job can be at. When a user changes the active item in the box I want to save this into the database.
Any help in how to handle this would be very much appreciated. Below is what I have tried so far:
How I create the set of forms in the view with the options taken from the enums in my database table:
<?php $id = count($jobs)-1; ?>
<?php for ($job = count($jobs)-1; $job >= 0; --$job): ?>
<tr>
<td>
<?php echo $this->Form->input('status'.(string)$id, array('type'=>'select', 'class' => 'statusSelect','label'=>'', 'options'=>$states, 'default'=>$jobs[$job]['Job']['Status'])); ?>
</td>
I am using a jquery script to set an on change listener for each dropdown and call an action in my controller:
$(".statusSelect").change(function(){
//Grab job number from the id of select box
var jobNo = parseInt($(this).attr('id').substring(6));
var value = $(this).val();
$.ajax({
type:"POST",
url:'http://localhost/projectManager/jobs',
data:{ 'id': jobNo,
'status':value},
success : function(data) {
alert(jobNo);// this alert works
},
error : function() {
//alert("false");
}
});
});
And I have this function in my controller:
public function changeState($id = null, $status = null) {
//I don't think the id and status are actually
//being placed as arguments to this function
//from my js script
}
Thank you!!!
You are POSTing to /projectManager/jobs, which corresponds to ProjectManagerController::jobs().
Your function is declared as public function changeState($id = null, $status = null). Assuming changeState(..) is a function within ProjectManagerController, this corresponds to /projectManager/changeState/$id/$status.
You need to switch the URL the AJAX is POSTing to. You can either do something like:
url:'http://localhost/projectManager/changeState/'+jobNo+'/'+value', remove the data {} and leave your function as is, or you can do
url:'http://localhost/projectManager/changeState', leave the data {}, change your function to changeState() and then use $this->request->data within changeState() to access the data.
I am guessing you have another function, jobs(), and that is why the AJAX is working properly and the alert is generating.

AJAX and PHP making like button

I have this like button code I want the like number to go up after click but there a need to refresh the page how can I do this:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('body').on( 'click' , '.votebutton' , function(){
var span = $(this).children('span');
var no = parseInt($(this).text(), 10);
$(span).text(++no);
var _id = $(this).data('vote');
$.ajax({
type: 'POST',
url: 'vote.php',
data: {
id: _id
}
});
});
});
</script>
<?php
$q = mysql_query("SELECT * FROM vote");while($row = mysql_fetch_array($q)){
$item[] = $row;
foreach($item as $i){}
echo "<button class='votebutton' data-vote='".$row[0]."'>Up vote</button><span>".$row[1]."</span>";
}
?>
It seems like you have two options. You could either A) make the post request return the new like count; or B) increment it manually with jQuery, which would be faster but not necessarily as accurate.
For the first option, you'd change your AJAX request to something like
$.ajax({
...
}).done(update_count)
where update_count is a function that takes the request as an argument and updates the count for a button. This method is is slower, but it would show an accurate like count at every instance, since the shown value is always the most current value in the database.
For the second option, you could select the span for the button and update its value with jQuery. This would be slightly faster, since it wouldn't have to wait for the AJAX query to complete, but it would only increment once, even if somebody else hit the "like" button.
Use location.reload(); to refresh the page.

Categories