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 **/
}
Related
I have this ajax function which inserts data using modal but I'm currently having a problem in passing the array values in my insert query. How can i convert the it to pass multiple information to my query ?
My input textbox in html
<input type="text" class="form-control text-center" id="author_lname[]" name="author_lname[]" placeholder="Last Name" required>
<input type="text" class="form-control text-center" placeholder="First Name" id="author_fname[]" name="author_fname[]" required>
<input type="text" class="form-control text-center" id="author_mname[]" name="author_mname[]" placeholder="Middle Name / Initial" required>
Ajax function
var getauthor_lname = $("#author_lname").val();
var getauthor_fname = $("#author_fname").val();
var getauthor_mname = $("#author_mname").val();
var whatprocess = "ADDBOOK";
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: {getauthor_lname:getauthor_lname,
getauthor_fname:getauthor_fname,
getauthor_mname:getauthor_mname ,
whatprocess : whatprocess
},
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: '',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
$("#datatables").load(window.location + " #datatables");
});
}
else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).catch(swal.noop)
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
PHP FOR INSERTING AUTHORS
$getauthor_lname = $_POST["getauthor_lname"];
$getauthor_fname = $_POST["getauthor_fname"];
$getauthor_mname = $_POST["getauthor_mname"];
for ($i = 0; $i < count($getauthor_fname); $i++) {
if ($getauthor_fname[$i] != "" && $getauthor_mname[$i] != "" && $getauthor_lname[$i] != "") {
$query = "INSERT INTO tbl_author (book_isbn, author_firstname, author_middlename, author_lastname) VALUES (? , ? , ? , ?)";
$stmt = $mysqlconnection->prepare($query);
$getauthor_lname[$i] = htmlspecialchars(strip_tags($getauthor_lname[$i]));
$getauthor_fname[$i] = htmlspecialchars(strip_tags($getauthor_fname[$i]));
$getauthor_mname[$i] = htmlspecialchars(strip_tags($getauthor_mname[$i]));
$stmt->bind_param("ssss", $getbook_isbn, $getauthor_fname[$i], $getauthor_mname[$i], $getauthor_lname[$i]);
$stmt->execute();
}else{
echo "ERRORauthor";
}
}
I would package all of my variables into an array and ship it from the AJAX call using data and unwrap the array at the PHP layer where i can the directly pass the values into the INSERT statement and just execute the query. I would think you validated your data already at the javascript layer to avoid data corruption. Hope this helps or reply if you have some more questions.
Quick question though: why do you have your id and name set to be arrays. I wouldn't think those are necessary for a single input field
var author_lname = $('#author_lname').val()
var author_fname = $('#author_fname').val()
var author_mname = $('#author_mname').val()
var whatprocess = 'ADDBOOK'
var entries = {'author_lname': author_lname, 'author_mname': author_mname, 'author_fname': author_fname, 'whatprocess': whatprocess}
var json = JSON.stringify(entries)
$.ajax({
url: 'functioncall.php',
method: 'POST',
data: { entry: entries },
success: function (data) {
console.log(data)
// var getdata = data.trim();
},
error: function (jqXHR, exception) {
console.log(jqXHR)
}
})
$author_fname = $author_info['author_fname'];
$author_mname = $author_info['author_mname'];
$author_lname = $author_info['author_lname'];
if ( !(empty($author_fname)) && !(empty($author_mname)) && !(empty($author_lname)) ) {
$query = "INSERT INTO tbl_author (book_isbn, author_firstname, author_middlename, author_lastname) VALUES (? , ? , ? , ?)";
$stmt = $mysqlconnection->prepare($query);
$stmt->bind_param("ssss", $getbook_isbn, $getauthor_fname[$i], $getauthor_mname[$i], htmlspecialchars(strip_tags($author_lname)));
$stmt->execute();
}
else{
echo "ERRORauthor";
}
could someone help me out?
I have these 2 files:
keywords.php
records.php
The keywords.php is like a search page where user submits a query like keywords.php?keywords=robert
Now what I want, is to send the value robert to records.php and display all records matching the name robert from the blog_posts table to the keywords.php page
my keywords.php
<?php
$keywords = $_GET['keywords'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="bootstrap/js/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="col-lg-12" id="results"></div>
<div id="loader_image"><img src="loader.gif" alt="" width="24" height="24"> Loading...please wait</div>
<div class="margin10"></div>
<div id="loader_message"></div>
</div>
<script type="text/javascript">
var <?php echo $keyword; ?>;
var busy = false;
var limit = 15
var offset = 0;
function displayRecords(lim, off) {
$.ajax({
type: "GET",
async: false,
url: "records.php",
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default" type="button">Loading please wait...</button>').show();
}
window.busy = false;
}
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
</body>
</html>
and this is my records.php
<?php
require_once("config.php");
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$keywords = $_GET['keywords'];
$sql = "SELECT * FROM blog_posts WHERE keyword LIKE '".$keywords."' ORDER BY postid ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<h3>' . $res['keyword'] . '</h3>';
}
}
?>
thanks alot for your help
There are several changes needed in keywords.php. Take a look at the changes below.
<?php
$keywords = $_GET['keywords'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="bootstrap/js/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="col-lg-12" id="results"></div>
<div id="loader_image"><img src="loader.gif" alt="" width="24" height="24"> Loading...please wait</div>
<div class="margin10"></div>
<div id="loader_message"></div>
</div>
<script type="text/javascript">
var keywords = '<?php echo $keywords; ?>'; // Changed
var busy = false;
var limit = 15
var offset = 0;
// Changed/New
var data = {
'limit': limit,
'offset': offset,
'keywords': keywords,
};
function displayRecords(lim, off) {
$.ajax({
type: "GET",
async: false,
url: "records.php",
data: data, // Changed
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html,textStatus,jqHXR) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").css('display','none');
$("#loader_message").html(html);
}
window.busy = false;
},
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
</body>
</html>
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 :)
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 need help with two things.
First: if I hit empty submit button. It should show me a error.
Second: If there is 0 results, it will give an error.
$(document).ready(function(){
$(".search").click(function(){
$.post("search.php", { keywords: $(".keywords").val() }, function(data){
$("div#search").empty()
$.each(data, function(){
$("div#search").append("- <a href='#?id=" + this.id + "'>" + this.title + "</a><br>");
});
}, "json");
});
});
--
$query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords");
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
$error = 'error';
echo json_encode( $error );
} else {
$query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR);
$arr = array();
$query->execute();
while( $row = $query->fetch(PDO::FETCH_ASSOC) ) {
$arr[] = array( "id" => $row["id"], "title" => $row["title"]);
}
echo json_encode( $arr );
}
OK I have painstakingly recreated (jsfiddle does not let you copy/paste) this on my local machine. Your html/js code should look like this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="search" class="keywords">
<input type="submit" name="submit" class="search">
<div id="search"></div>
<script>
$(document).ready(function(){
$(".search").click(function(){
$.post(
"search.php",
{ keywords: $(".keywords").val() },
function(data){
$("div#search").empty()
$("div#search").append(data);
},
"json"
);
});
});
</script>
</body>
</html>
And for the PHP search.php page:
<?php
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
echo json_encode( "error" );
}
else {
// run mysql commands
// if resultset == empty
// echo json_encode( "error" );
echo json_encode( "actual data" );
}
?>
To parse json data in javascript do this:
$.post(
"search.php",
{ keywords: $(".keywords").val() },
function(data) {
$("div#search").empty();
obj = JSON.parse(data);
$("div#search").append(obj.id + " " + obj.title);
},
"json"
);
try using $(this) instead of this