AJAX and PHP making like button - javascript

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.

Related

Last chance at jQuery AJAX Toggle

I posted this question ealier today, however I recieved a fix (thank you) that works great against my RequestBin endpoint for testing, however when submitting to my AJAX script, its a different story.
Problem: I cant submit my jQuery toggle values to my PHP AJAX script because there is no form name associated with the POST request (so db never updates). I proven this by making a HTML form with the field names and the database updated right away. However this is not the case with this JS toggle method.
jQuery code
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: {
value: $this.hasClass("switchOn") ? 'pagination' : 'infinite'
},
success: function(data) {
console.log(data);
}
});
});
});
HTML
<div class="wrapper-toggle" align="center">
<label>
<div class="switch"></div>
<div class="switch-label">Use <b>Paged</b> results instead (Current: <b>Infinite</b>)</div>
</label>
</div>
PHP AJAX script
if (array_key_exists('pagination', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'pagination' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
} else if (array_key_exists('infinite', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'infinite' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
}
I cant figure out how to assign a field name to this, as it is not a traditional post form. This is driving me nuts. So the previous solution was applying hasClass() and calling var $this outside of $ajax(), great (and RequestBin receives both requests), but when submitting to PHP its a dead end (no form names).
Given the code above fixed and revised twice, where do I even start without a form ??
We need:
name="pagination"
name="infinite"
But this toggle JS doesn't allow for this. prop() has been removed to get toggle submitting values over (just not my AJAX script).
Any solution appreciated. Thank you again.
You can set your values as Form Data. So the PHP Function will get it just like a traditional form submission:
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
var formdata = new FormData();
$this.hasClass("switchOn") ? formdata.append('pagination', 'name') : formdata.append('infinite', 'name');
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: formdata,
success: function(data) {
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
More info on JS Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData

How to refresh specific div using Javascript/Jquery with the variables on it

I have a variable $salary which is dynamic. How can I refresh specific div every 5seconds.
index.html
<html>
<body>
<img src="<?php echo $filename.'.jpg'; ?>" />
<p id="salary"><?php echo $salary; ?></p>
</body>
</html>
Is there any javascript/jquery way to refresh #salary only. Please help..
You can execute an ajax call:
function ajaxCall() {
$.ajax({
method: 'POST',
url: 'path/to/asyncHalndler.php',
data: { ... },
success: function (data) {
if (data) {
$('#salary').html(data);
}
}
});
}
// Execute ajax call every 5 seconds
setInterval(function() {
ajaxCall();
},5000);
var salary = document.getElementById('salary');
Now, the value of your variable salary will be the DOM node where you would like to change the value. When you get new data, you can refresh text inside your p tag with salary id by adding salary.innerText = yourNewValue;
This is pure JavaScript way of updating that element with id.
It's better to use ajax way. But if u are looking for a very simple solution then jQuery .load will be the best
setInterval($("#salary").load("<url to get the value>"), 1000);
You will need an jquery ajax call for that.
first you should create php file get_salary.php where you send id from jquery ajax if you want to update the salary for unique id:
in get_salary.php you need to get salary from database so the code in this php file will be like that
$id = $_POST['ID']
$query = mysql_query("SELECT * FROM sallaries WHERE id='$id'") or die("Can't connect");
$fetch = mysql_fetch_array($query)
$salary = $fetch['salary']
echo $salary
after that you will need javascript file(e.g script.js) from where you will send the request and id to the get_salary.php and grab the data from it, after that you will be able to update salary in html, so code in javascript file will be like that:
function updateSalary(){}
var id=25;
$.ajax({
url: "get_salary.php",
type: 'POST',
//sending id
data:'id='+id,
success: function(result){
//updating html
$("#salary").html(result);
}
});
}
//setting interval to update in every second
setInterval(updateSalary, 1000)
so it will update your salary in the 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.

PHP change button text and update database accordingly

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.

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.

Categories