PHP Delete from javascript button click - javascript

I'm currently doing a PHP page that displays bans and also gives an option to unban users.
I can't seem to get the button to work and run the query to unban. Any help would be much appricated.
It currently does nothing and I'm also unsure as to how to display the Pnotice errors as I get
Uncaught TypeError: Cannot read property 'required' of undefined
Here is the function listed in lightcms.php for banlist.php;
function banListAll() {
global $db;
$getBanListAllQuery = "SELECT * FROM users_bans";
$getBanListAll = $db->query($getBanListAllQuery);
while ($showBanListAll = $getBanListAll->fetch_assoc()) {
echo "<tr id=\"banID" . $showBanListAll['id'] . "\">";
echo "<td>";
echo $showBanListAll['id'];
echo "</td>";
echo "<td>";
echo $showBanListAll['added_date'];
echo "</td>";
echo "<td>";
echo $showBanListAll['value'];
echo "</td>";
echo "<td>";
echo $showBanListAll['reason'];
echo "</td>";
echo "<td>";
echo $showBanListAll['expire'];
echo "</td>";
echo "<td>";
echo "<button data-id=\"" . $showBanListAll['id'] . "\" type=\"button\" class=\"btn btn-xs btn-danger btn-unban\">Unban</button>";
echo "</td>";
echo "</tr>";
}
}
Here is the javascript on banlist.php
<script type="text/javascript">
$(".btn-unban").click(function(){
var articleId = "#banID"+ $(this).attr("data-id");
var myData = "unban="+ $(this).attr("data-id"); //post variables
var formData = new FormData(this);
$.ajax({
type: "POST",
url: "./engine/post/unban.php",
dataType:"json",
data: myData,
success: processJson
});
function processJson(data) {
// here we will handle errors and validation messages
if (!data.success) {
if (data.errors.required) {
new PNotify({
title: 'Uh oh!',
text: data.errors.required,
type: 'error'
});
}
} else {
new PNotify({
title: 'Success!',
text: data.message,
type: 'success'
});
$(articleId).fadeOut("slow");
}
}
});
</script>
And here is the unban.php file
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
$insert = "DELETE users_bans WHERE id = '$id'";// Do Your Insert Query
if($db->query($insert)) {
echo '{"success":true,"message":"User was unbanned!"}';
} else {
echo '{"error":true,"message":"Sorry this has not worked, try another time!"}';
}
//Need to work on displaying the error^
?>

Your JS looks for "errors.required" but your PHP sends "error" with no required.
Here's some code edits that (IMO) clean up the code. (any changes to sql are based on the assumption that you're using mysqli. that assumption based on the use of ->fetch_assoc()) Please consider atlest the change to unban.php as what you currently have is open to sql injection
Your new banListAll function:
function banListAll() {
global $db;
// don't use SELECT * if you can help it. Specify the columns
$getBanListAllQuery = "SELECT id, added_date, value, reason, expire FROM users_bans";
$getBanListAll = $db->query($getBanListAllQuery);
while ($showBanListAll = $getBanListAll->fetch_assoc()) {
$showBanListAll[] = "<button type='button' class='btn btn-xs btn-danger btn-unban'>Unban</button>";
// array_slice to get ignore the ['id']
echo "<tr data-banid='" . $showBanListAll['id'] . "'><td>" . implode("</td><td>", array_slice($showBanListAll,1)) . "</td></tr>";
}
}
New JS on banlist.php
<script type="text/javascript">
function processJson(data) {
// here we will handle errors and validation messages
if (data.error === false) {
row.fadeOut("slow");
}
// assuming we always get a "message"
new PNotify({
title : 'Uh oh!',
text : data.message,
type : 'error'
});
}
$(".btn-unban").click(function() {
var $this = $(this); // creating jQuery objects can be costly. save some time
var row = $this.closest('tr');
var banID = row.data('banid');
var postData = { unban: banID };
var formData = new FormData(this);
$.ajax({
type : "POST",
url : "./engine/post/unban.php",
dataType : "json",
data : postData,
success : processJson
});
});
</script>
And here is the unban.php file
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
// Don't just concat variables that came from users into your DB queries.
// use paramterized queries. If $db is a mysqli connection
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
$deleteStmt = $db->prepare($insert);
// if id is a number change "s" to "i" below
$deleteStmt->bind_param("i",$id);
if($deleteStmt->execute()) {
echo jsonResult(false,"User was unbanned!");
} else {
echo jsonResult(true,"Sorry this has not worked, try another time!");
}
// add this function to return results to your JS functions
// should make it harder to put "errors" instead of "error" ;)
function jsonResult($hasErrors, $msg) {
return json_encode(array("error"=>$hasErrors,"message"=>$msg));
}
and just in case you thought unban.php was getting unnecessarily long, here it is without comments
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
if ($deleteStmt = $db->prepare($insert)) {
$deleteStmt->bind_param("i",$id);
if($deleteStmt->execute()) {
echo jsonResult(false,"User was unbanned!");
} else {
echo jsonResult(true,"Sorry this has not worked, try another time!");
}
}
else {
print_r($db->error);
}
// the function should go into your general functions file
?>

Related

'Unexpected token ;' when trying to pass PHP variable in jQuery AJAX request

So im trying to run a PHP script that sets a deleted field in the database to poplulate if you drag a certain text element to the droppable area.
At the moment i have this droppable area:
<div class="dropbin" id="dropbin" >
<span class="fa fa-trash-o noSelect hover-cursor" style="font-size: 20pt; line-height: 225px;"> </span>
</div>
and this draggable text:
<div id='dragme' data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>
The area im having an issue with is this:
$("#dropbin").droppable
({
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var deletedby = <? if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>
var data = {noteid1: noteid, deletedby1: deletedby};
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
url: 'deleteNote.php',
datatype: 'json',
data: data,
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
EDIT: The line i get the error on is:
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
Im currently getting an "Unexpected token ;" and its stopping the droppable from working.
Just a side note, if i run it without the variables it hits everything apart from:
url: 'deleteNote.php',
Also inside deleteNote.php is this incase it helps:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid1'], $_POST['deletedby1']))
{
$noteid2 = $_POST['noteid1'];
$deletedby2 = $_POST['deletedby1'];
// echo "Hello...". $noteid;
$stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
$params = array($noteid2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
(I deliberatley don't have deletedby in the database just yet, ignore that)
Could anyone possibly help me to get this to work?
Try to add quotes in these lines and add php after <? in second line:
var noteid = "<?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>";
var deletedby = "<?php if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>";
OR
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
var deletedby = "<?=isset($_SESSION['username']) ? $_SESSION['username'] : "" ?>";

AJAX JQuery delete from html but not from mysql database

What is wrong here?
My PHP/HTML (The only part that matters):
if(isset($_POST['submit']))
{
$date = date('Y-m-d', strtotime(str_replace("-","/",$_POST['dateOfEntry'])));
$username = $_POST['user'];
$query = 'SELECT `ID`, `Date`, `Description`, `TypeOfDowntime`, `Machine#` FROM `machineissuesreport` WHERE `Date`="'.$date.'" AND `UpdatedBy` = "'.$username.'" ORDER BY `ID` DESC';
$conn = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($conn))
{
echo '<tr>';
echo '<td style="text-align: center" width="5px"><input type="button" name="edit" value="Edit"></td>';
echo '<td style="text-align: center" width="5px">Delete</td>';
echo '<td style="display: none;"><input type="hidden" value='.$row['ID'].'></td>';
echo '<td>'.$row['Date'].'</td>';
echo '<td>'.$row['Description'].'</td>';
echo '<td>'.$row['TypeOfDowntime'].'</td>';
echo '<td>'.$row['Machine#'].'</td>';
echo '</tr>';
}
}
?>
My Ajax/Javascript:
$(document).ready(function()
{
$('.delete').click(function()
{
if(confirm("Are you sure you want to delete this row?"))
{
var del_id = $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type: 'POST',
url: 'machineEntryLogEdit.php',
data: {'del_id':'del_id'},
success: function(data)
{
$ele.fadeOut().remove();
},
error: function (xhr, status, error)
{
alert(this);
}
});
}
});
});
My PHP (on an external script: machineEntryLogEdit.php):
include('connServer.php');
$deleteID = $_POST['del_id'];
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_connect($connection, $query);
if(isset($result))
{
echo "YES";
}
else
{
echo "NO";
}
?>
I have searched around and around for solutions but no avail. The only things it does is delete the record from the HTML table, but not from the database, causing the supposed-to-be-deleted row to reappear after refresh. I am still very new to AJAX (in fact I just learned it myself today) and still reading the documentations and forums. Thanks.
This should be data: {'del_id': del_id} remove quotes so it react as a variable, not just a single string. And one more thing, your delete query does not execute cause you're using :
$result = mysqli_connect($connection, $query);
Should be mysqli_query like the one you did on selecting data's part:
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_query($connection, $query);
It looks to me like you didn't pass the submit variable in your data. If you want to include a form you need to pass the data, right now the server is receiving only one parameter, del_id

Calling a POST variable in PHP-function

I have a PHP-file with multiple php functions in it.
I am sending a Javascript Variable with an AJAX-call, POST method to that PHP-file.`
Now the variable IS accessible in my PHP-file but not in that specific function where I want it...
$("#dropdown").change(function () {
var value = $("#dropdown").val();
console.log(value);
$.ajax({
type: "POST",
dataType: 'text',
url: "PhpFunctions.php",
data: {id:$("#dropdown").val()},
success: function (data) {
console.log(data);
$("div.geselecteerdVliegtuig").fadeIn("slow", function () {
console.log("Vliegtuigdetail faded in");
});
/*
$("div.vliegtuigenEnabled2").hide();
console.log("vliegtuigEnabled ID's hidden");
*/
},
error: function (err) {
alert('error: ' + err);
}
}); //END AJAX CALL`
//I CAN ACCESS DATABASE AND ID IS ACCESSIBLE HERE
//Connect to server
$connect = mysql_connect("localhost", "root", "root") or die(mysql_error());
//Connect to database
$select_db = mysql_select_db("Luchthaven") or die("Could not find database");
$id = $_POST['id'];
echo $id; //WORKS
//NEED TO ACCESS IS HERE
function GeselecteerdVliegtuig() {
makeConnection();
//Query the database
$id = $_POST['id'];
//$query = "SELECT * FROM vliegtuig WHERE vliegtuig_ID = 'PEG431';";
//echo "SELECT * FROM vliegtuig WHERE vliegtuig_ID = 'PEG431';<br/>";
$query = "SELECT * FROM vliegtuig WHERE vliegtuig_ID = '" . $id . "';";
echo "SELECT * FROM vliegtuig WHERE vliegtuig_ID = '" . $id . "';<br/>";
$fetch = mysql_query($query) or die("could not fetch data");
while ($row = mysql_fetch_assoc($fetch)) {
echo "<tr id=" . $row['vliegtuig_ID'] . ">";
echo "<td>" . $row['vliegtuig_ID'] . "</td>";
echo "<td>" . $row['maatschappij'] . "</td>";
echo "<td>" . $row['lengte'] . "</td>";
echo "<td>" . $row['breedte'] . "</td>";
echo "<td>" . $row['kilometerstand'] . "</td>";
echo "<td>" . $row['bouwjaar'] . "</td>";
echo "<td>" . $row['bereik'] . "</td>";
echo "<td>" . $row['aantalMotoren'] . "</td>";
echo "</tr>";
} // END WHILE
mysql_close(); //Make sure to close out the database connection
echo "<b>Connection closed<b><br/><br/>";
}
You can pass the $_POST['id'] variable to that function GeselecteerdVliegtuig($id) and call the function with GeselecteerdVliegtuig($_POST['id'])
Get rid of this line:
$id = $_POST['id'];
as you might want to use your functionality even if your value is not located in your $_POST["id"]. Modify your function header from
function GeselecteerdVliegtuig() {
to
function GeselecteerdVliegtuig($id) {
Call your function this way:
if (isset($_POST['id'])) {
GeselecteerdVliegtuig($_POST['id']);
}
and call your function from the page where you posted the value, make sure that the page where you posted exists, works and responds.
Finally, when everything is working change the way you are working with the database, because your current approach has a security leak due to SQL injection possibilities. What if I visit your page and execute the following in the console:
$("#dropdown").val("0'; delete from vliegtuig where '' = '");
and then trigger the post? It will remove every single record from your table unless you are making sure that these attempts fail.

PHP Ajax returning HTML twice

I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.
Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.
Index.php
<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");
$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";
$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);
$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn);
?>
Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.
Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
And as final the Javascript
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
note: HTML is being returned from the "page" class called inside Index.php
How do i not let everything get called twice?
Thank you,
EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php
AutoComplete.PHP
Please explain what should be in the file and why. I am clueless.
Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:
if(!isset($_REQUEST['calledByAjax']))
{
$IndexPage = new page();
echo $IndexPage->render();
}
and in your Ajax call:
data: { query: query_value, calledByAjax: 'true' },
Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.
First thing (this is a sample, not tested yet)
autocomplete.php
<?php
$search_string = $_POST['query'];
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
}
echo($output);
?>
autocomplete.js
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "autocomplete.php", //Here change the script for a separated file
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
} else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
search(); // call the function without setTimeout
}
});
});
Have luck :)

Error using Ajax in PHP and JQuery

i got a problem when i try to use ajax in a php file, which calls to another php file.
Here is the code of the php file:
<script>
function obtenerProductos(cat) {
parametros = {"idCat": cat};
$.ajax({
data: parametros,
url: '/bin/getProductos.php',
type: 'post',
beforeSend: function() {
$(".prods > form").html("Procesando, espere por favor...");
},
success: function(respuesta) {
$(".prods > form").html(respuesta);
}
});
}
function obtenerProducto(prod) {
parametros2 = {"idProd": prod};
$.ajax({
data: parametros2,
url: '/bin/getProducto.php',
type: 'post',
beforeSend: function() {
lista = $(".cPreview").html() + "<br/> AƱadiendo...";
$(".cPreview").html(lista);
},
success: function(respuesta) {
lista = $(".cPreview").html()+ respuesta.nombre + "\t" + respuesta.precio + "<br/>" ;
$(".cPreview").html(lista);
precio = parseFloat($(".precioT").html()) + respuesta.precio;
$(".precioT").html(precio);
}
});
}
</script>
In the first function of this script i call to the first PHP (getProductos.php) to get all the products of a category and receive a html which print in a form.
The second function calls to another php (getProducto.php) to get all the information of the selected product and print it in another div.
Here you have the PHP files named.
getProductos.php (This works)
<?php
include '../funciones.php';
$recibido = $_POST['idCat'];
echo obtenerProductosCategorias($recibido);
?>
getProducto.php (Dont Works)
<?php
include '../funciones.php';
$recibido = $_POST['idProd'];
echo obtenerProductos($recibido);
?>
And the 2 functions of this code:
function obtenerProductosCategorias($idCat) {
conectDB();
$string = "";
$sql = 'select * from Productos where id_categoria="' . $idCat . '";';
$resultado = mysql_query($sql);
while ($row = mysql_fetch_array($resultado)) {
$string = $string . "<input type='button' onclick='obtenerProducto(" . $row["id_producto"] . ");return false;' value='" . $row['nombre_producto'] . "' />";
}
return $string;
closeDB();
}
function obtenerProductos($idProd) {
conectDB();
$sql = 'select * from Productos where id_producto="' . $idProd . '";';
$resul = mysql_query($sql);
while ($row = mysql_fetch_array($resul)) {
$resultado["nombre"] = $row["nombre_producto"];
$resultado["precio"] = $row["coste_producto"];
}
return json_encode($resultado);
closeDB();
}
I have alerts inside the PHP to check that everything is going fine but the second function doesnt enter in his PHP and it returns undefined undefined without show any alert of the PHP thats why i think that the second function have some problems to reach his PHP but the URL is correct and the file is located in the right place.
Thanks for reading and sorry for my English.
Try defining $resultado as an array prior to assigning anything too it. Not sure but in some configurations this does break PHP.
function obtenerProductos($idProd) {
conectDB();
$sql = 'select * from Productos where id_producto="' . $idProd . '";';
$resul = mysql_query($sql);
$resultado = array();
while ($row = mysql_fetch_array($resul)) {
$resultado["nombre"] = $row["nombre_producto"];
$resultado["precio"] = $row["coste_producto"];
}
return json_encode($resultado);
closeDB();
}

Categories

Resources