I'm trying to create a HTML table that lists all the rows in a database table. Then, next to each row I want to have a button so the user can delete that entry. I have created the table but I can't get the buttons to work.
I have been searching around and I found this post How to Call a PHP Function on the Click of a Button but I can't get it to work. I've never used ajax before so I might not understand the code correctly.
Here is the code:
Go through all the data from the table and create a button for each entry
<?php
for ($x = 0; $x < sizeof($data); $x++) {
?>
<input type="submit" class="tableButton" name="<?php echo $x ?>" value="<?php echo $x ?>">
<?php
}
?>
When a tableButton is clicked, send its value to ajax.php
$('.tableButton').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = { 'action': clickBtnValue };
$.post(ajaxurl, data, function (response) {
});
});
ajax.php
Get the value of the button that was pressed and do something with it
<?php
if (isset($_POST['action'])) {
$data = $_POST['action'];
echo $data;
}
?>
Currently I just have it echo the value to test it but it's displaying nothing. What I would have it do is run this query:
DELETE from myTable WHERE id = $data;
Or if someone knows a better way to do this please let me know.
Edit
After doing a lot more searching I found out why this wasn't working how I expected. As I suspected since I've never used AJAX before there was something I missed, I didn't know the echo wouldn't print directly to the screen. I just changed the echo to a delete query and tested that and it works... So the code is fine, but I think I should learn AJAX sometime. Thanks for all the responses.
I'm also aware of the sql injection that is possible here, this was just a quick mock-up, thanks.
It is hard to help you from this point of view we got.
You should do some debugging, like:
Check if the associated ajax.php is called (by checking the console with "F12" for example)
If yes, check the data being passed through your ajax POST
If not, maybe the reference link is wrong
Let me hear what you got.
You can try by this way. I think it will help you
Html File
<html>
<head>
<title>Test</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$('.tableButton').live('click', function(){
var id = $(this).val();
$.ajax({
url:'ajax.php'
,data:{id:id}
,type:'post'
,success:function(data){
if(data == 'success'){
$('#' + id).remove();
}
}
});
});
</script>
<?php
for ($x = 0; $x < 5; $x++) {
?>
<input type="submit" class="tableButton" id="<?=$x?>" name="<?php echo $x ?>"value="<?php echo $x ?>">
<?php
}
?>
</body>
</html>
ajax.php
<?php
if(isset($_POST['id'])){
$id = $_POST['id'];
//delete operation here
//if(deleted) echo 'success';
}
?>
Ok. First of all you need to create the button with row id. You can do it using mySQL and PHP loops. Create it in this following format.
<input type="submit" name="test" data-id="23" value="Remove" class="delete_row" />
<input type="submit" name="test" data-id="24" value="Remove" class="delete_row" />
<input type="submit" name="test" data-id="25" value="Remove" class="delete_row" />
<input type="submit" name="test" data-id="26" value="Remove" class="delete_row" />
Here replace the data-id in each button with the id of row you are looking to delete.( Replace 23,24 etc with database ids dynamically ).
Java script
$(document).ready(function(){
$(".delete_row").click(function(e){
e.preventDefault();
var deleteId = $(this).attr("data-id");//unique id of the raw to be deleted
var request = $.ajax({
url: "ajax.php",
type: "POST",
data: { id : deleteId },
dataType: "json"
});
request.done(function( msg ) {
if( msg.status )
alert("Deleted successfully!");
else
alert("Something gone wrong!!");
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
ajax.php
<?php
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$delete_id = $_POST["id"];
if( is_numeric( $delete_id ) ){
/*DELETE QUERT WHERE id = $delete_id (Try to use mysqli or PDO ) */
/* $affected_rows = effected_rows() */
if( $affected > 0 )
{
echo json_encode( array("status" => true ) );die;
}
}
echo json_encode( array("status" => false ) );die;
}
die("Get out of here!");
?>
I hope this will help you :)
Related
I am trying to send an $_GET['CategoryID'] trought ajax to call in the destination file getdata.php and I can't make it work, I don't find the perfect info here. I know that I am really noob, but I am trying really hard to learn.
I been trying a lot of different code and it still not working.
<button type="button" name="btn_more" data-vid="<?php echo $stockID; ?>" id="btn_more" class="btn btn-success form-control">Ver Mais</button>
<input class="form-control" id="PresentCategoryID" name="PresentCategoryID" data-cat="<?php echo $_GET['categoryID']; ?>" value="<?php echo $_GET['categoryID'];
<script>
$(document).ready(function(){
$(document).on('click', '#btn_more', function(){
var last_video_id = $(this).data("vid");
var PresentCategoryID= ('PresentCategoryID');
$('#btn_more').html("<div class=loader></div>");
$.ajax({
url:"getdata.php",
method:"POST",
data:{
last_video_id:last_video_id,
PresentCategoryID:PresentCategoryID},
dataType:"text",
success:function(data)
{
if(data != '')
{
$('#remove_row').remove();
$('#result').append(data);
}
else
{
$('#btn_more').html("No Data");
}
}
});
});
});
</script>
My objective it's to call the categoryID in the getdata.php, like this,
<?php
$output = '';
$stockID = '';
$PresentCategoryID = '';
sleep(1);
include 'includes/dbh.inc.php';
include 'includes/rating.inc.php';
$sql = "SELECT stock.stockID, stock.name, stock.marca, stock.origem, stock.categoryID, stock.thumbnail, category.name AS catname FROM stock JOIN category ON stock.categoryID=category.categoryID WHERE stock.categoryID='$PresentCategoryID' AND stockID > ".$_POST['last_video_id']." LIMIT 4";
?>
var PresentCategoryID= ('PresentCategoryID')
should be
var PresentCategoryID= $('#PresentCategoryID').val();
You need to use $ to select the element, add the # prefix to use it as an ID, and .val() to get the value of the input.
hey check this answer which will help your problem
$(document).ready(function() {
$(document).on('click', '#btn_more', function() {
var last_video_id = $(this).data("vid");
var PresentCategoryID = ('#PresentCategoryID').val();
$('#btn_more').html("<div class=loader></div>");
var data = {
last_video_id,
PresentCategoryID
};
$.get('getdata.php', JSON.stringify(data)).done(response => {
console.log(response);
if (response != '') {
$('#remove_row').remove();
$('#result').append(response);
} else {
$('#btn_more').html("No Data");
}
}).fail(() => {
console.log("Something went wrong");
});
});
});
PHP SCRIPT
<? php
include 'includes/dbh.inc.php';
include 'includes/rating.inc.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
//if you using get request
//recommended way to get the data use the mysqlconn->real_escape_string($_GET['last_video_id']);
$last_video_id = $_GET['last_video_id'];
$PresentCategoryID = $_GET['PresentCategoryID'];
sleep(1);
$sql = "SELECT stock.stockID, stock.name, stock.marca, stock.origem, stock.categoryID, stock.thumbnail, category.name AS catname FROM stock JOIN category ON stock.categoryID=category.categoryID WHERE stock.categoryID='$PresentCategoryID' AND stockID='$$last_video_id'";
" LIMIT 4";
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//if you using post request then in jquery remove $.get to just $.post
$data = json_decode(file_get_contents('php://input'),true);
$last_video_id = $data['last_video_id'];
$PresentCategoryID = $data['PresentCategoryID'];
}
you want to send via 'GET' but you use the method 'POST'.
Best regards
MrKampf
I'm trying to create a simple chat application that posts people's messages, and that gives the user an option to "reset" the chat which will delete all messages from the database so the user can start over. The messages post okay, but the reset button just sends an empty post (instead of deleting all current posts). I'm wondering what I'm doing wrong:
if ( isset($_POST['reset']) ) {
$sql = "DELETE FROM {$p}sample_chat WHERE chat = :CHA";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':CHA' => $_POST['message']));
header( 'Location: '.sessionize('index.php') ) ;
return;
}
Per a comment below, I've updated my client side code to be:
<html>
<script type="text/javascript" src="<?php echo($CFG->staticroot); ?>/static/js/jquery-1.10.2.min.js"></script>
<body>
<form id="chats" method="post">
<input type="text" size="60" name="message" />
<input type="submit" value="Chat"/>
<input type="submit" name="reset" value="Reset"/>
<a style="color:grey" href="chatlist.php" target="_blank">Launch chatlist.php</a>
</form>
<p id="messages" >
<script type="text/javascript">
function htmlentities(str) {
return $('<div/>').text(str).html();
}
function updateMsg() {
window.console && console.log("Requesting JSON");
$.ajax({
url: '<?php echo(sessionize('chatlist.php')); ?>',
cache: false,
success: function(data){
window.console && console.log("JSON Received");
window.console && console.log(data);
$("#chatcontent").empty();
for (var i = 0; i < data.length; i++) {
entry = data[i];
$("#chatcontent").append("<p>"+entry[0] +
"<br/> "+entry[1]+"</p>\n");
window.console && console.log("entry " + entry[0]);
}
setTimeout('updateMsg()', 4000);
}
});
}
window.console && console.log("Startup complete");
updateMsg();
</script>
</p>
</body>
The code in its entirety, in case I've missed something/context is helpful:
<?php
require_once "../../config.php";
require_once $CFG->dirroot."/pdo.php";
require_once $CFG->dirroot."/lib/lms_lib.php";
// This is a very minimal index.php - just enough to launch
// chatlist.php with the PHPSESSIONID parameter
session_start();
// Retrieve the launch data if present
$LTI = requireData(array('user_id', 'result_id', 'role','link_id'));
$instructor = isset($LTI['role']) && $LTI['role'] == 1 ;
$p = $CFG->dbprefix;
if ( isset($_POST['message']) ) {
$sql = "INSERT INTO {$p}sample_chat
(link_id, user_id, chat, created_at)
VALUES (:LI, :UID, :CHA, NOW() )
ON DUPLICATE KEY
UPDATE chat = :CHA, created_at = NOW()";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':LI' => $LTI['link_id'],
':UID' => $LTI['user_id'],
':CHA' => $_POST['message']));
$messages = array();
header( 'Location: '.sessionize('index.php') ) ;
return;
}
if ( isset($_POST['reset']) ) {
$sql = "DELETE FROM {$p}sample_chat WHERE chat = :CHA";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':CHA' => $_POST['message']));
header( 'Location: '.sessionize('index.php') ) ;
return;
}
?>
<html>
<script type="text/javascript" src="<?php echo($CFG->staticroot); ?>/static/js/jquery-1.10.2.min.js"></script>
<body>
<form id="chats" method="post">
<input type="text" size="60" name="message" />
<input type="submit" value="Chat"/>
<input type="submit" name="reset" value="Reset"/>
<a style="color:grey" href="chatlist.php" target="_blank">Launch chatlist.php</a>
</form>
<p id="messages" >
<script type="text/javascript">
function htmlentities(str) {
return $('<div/>').text(str).html();
}
function updateMsg() {
window.console && console.log("Requesting JSON");
$.ajax({
url: '<?php echo(sessionize('chatlist.php')); ?>',
cache: false,
success: function(data){
window.console && console.log("JSON Received");
window.console && console.log(data);
$("#chatcontent").empty();
for (var i = 0; i < data.length; i++) {
entry = data[i];
$("#chatcontent").append("<p>"+entry[0] +
"<br/> "+entry[1]+"</p>\n");
window.console && console.log("entry " + entry[0]);
}
setTimeout('updateMsg()', 4000);
}
});
}
window.console && console.log("Startup complete");
updateMsg();
</script>
</p>
</body>
Major issue:
$.getJSON('<?php echo(sessionize('chatlist.php')); ?>', function(data){
^^^--- using http GET
if ( isset($_POST['reset']) ) {
^^^^---expecting HTTP POST
.getJSON() is for GET requests only. If you want to use a POST, you'll have to use $.ajax() instead.
You are doing a GET request using ajax. Make a POST request. Add Type. For Example
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I suggests best thing you can do is: Use PHP REQUEST variable. Using it use can accept either post or get requests. i.e. For example:
if ( isset($_REQUEST['reset']) ) {
/***Code to delete chat **/
}
I currently have two php files (index.php and update.php) In index.php, there is some javascript code and a button that sends a variable, called $sid, to update.php, where it is processed based on $sid. Here is the code for both index.php and update.php. I am not pasting it directly into StackOverflow, simply because of how you have to add code to your text on StackOverflow, and how JavaScript works with it's spacing hierarchy.
http://pastebin.com/fq87vvgz
Currently, when you press the button, an alert box does not pop up. If you put the PHP code in a PHP code checker, no errors appear.
Here is my code:
This is what is in index.php
<?php
$sid = 11;
?>
<script type="text/javascript">
$(document).ready(function(){
$('#vote').click(function(){
$.ajax({
url : 'update.php', // Notice how this sends to update.php
type : 'POST',
data : {
action : 'vote_server',
sid : $('#sid').data('sid')
},
dataType : 'JSON',
success : function(result) {
if (result.xhr == 'success') {
alert('You bumped your server!');
} else if (result.xhr == 'voted_already')
alert('You can only bump every 24 hours!')
}
});
});
})
</script>
<input type="button" class="btn btn-primary" id="vote" value="Vote up your server">
This is what is contained in update.php
<?php
define('action',$_POST['action']);
$result = array(
'xhr' => 'error'
);
if (action == 'vote_server')
{
$sid = (int)$_POST['sid'];
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$dbTime = #mysql_result(mysql_query("SELECT `id`, `last_updated` FROM `servers` WHERE `id` = '$sid'"), 0);
$timeDiff = $time - $dbTime;
if($timeDiff >= 86400){
mysql_query("UPDATE `servers` SET `last_updated` = '$time' WHERE `id` = '$sid'");
$result['xhr'] = 'success';
} else { $result['xhr'] = 'voted_already'; }
}
echo json_encode($result);
?>
Use query and ajax
in your index page...
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$( ".button" ).click(function() {
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
$.ajax({
type: "POST",
url: 'update.php',
data: {postedVar:var1, postedVar2:var2},
success: function(data)
{
alert(data);
}
});
});
});
</script>
<html>
<button class="button" data-var1="<?php echo "this is var1"; ?>" data-var2="<?php echo "this is var2"; ?>">Button</button>
</html>
On you update page...
access your vars like this
<?php
var1 = $_POST['postedVar1'];
var2 = $_POST['postedVar2'];
echo var1;
?>
...NOT TESTED
I am building a simple antibot for my email form.
This is a code which makes a problem:
<?php
session_start();
$a = rand(1, 10);
$b = rand(1, 10);
$antibot = $a + $b;
$_SESSION["antibot"] = $antibot;
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("#sendEmail").click(function(){
var antibot = $("#antibot").val();
$.post(
"test.php",
{antibot: antibot},
function(data){
alert(data.info);
},
"json"
);
);
);
);
</script>
</head>
<body>
<table>
<tr><td>AntiBot: <?php echo $a . ' + ' . $b;?> = </td><td><input type='text' id='antibot' /></td></tr>
<tr><td colspan='2'><input type='button' id='sendEmail' value='Send'/></td></tr>
</table>
</body>
</html>
And my test.php
<?php
session_start();
$antibot = $_POST["antibot"];
$data = array();
if(isset($_SESSION["antibot"])){
if($_SESSION["antibot"] == $antibot){
$data["info"] = "Session is isset and answer is right!";
}
else{
$data["info"] = "Session is isset but answer is NOT right!";
}
}
else{
$data["info"] = "Session is NOT isset!";
}
echo json_encode($data);
?>
I constantly get this info: "Session is isset but answer is NOT right!"
If you can see $_SESSION["antibot"] in test.php is setted but value is "" no matter what I type in input field #antibot!
I do not understand why this is happening, please can someone tell me where the problem is and how can I fix it?
I tested this code here:
http://onlinephpfunctions.com/stackoverflow/11981309/
And it seems completely valid.
I had to make some modifications to your javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#sendEmail").click(function(){
var antibot = $("#antibot").val();
$.post(
"test.php",
{antibot: antibot},
function(data){
alert(data.info);
},
"json"
)
})
})
</script>
After that it was working fine. It may just be some problems with cookies in your browser, or an error in your PHP config so sessions wont be stored right. Please check this, your code works OK, as you can see in the demo.
I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});