The code should work the following way: Press a button -> row gets deleted from database.
I tried to follow and copy answers from other questions but with no working solution.
The jquery code:
$(document).on('click', ".menuRemove", function(event) {
var del_h3name2 = $(this).parent().parent().prev().text();
$.ajax({
type:'POST',
url:'deleteaccordion2.php',
data:{'del_h3name2':del_h3name2},
success: function(data){
if (data=="YES") {
alert("YES")
} else {
alert("can't delete the row")
}
}
});
}
and php code (deleteaccordion2.php):
<?php
require 'database.php';
if ( isset($_SESSION['user_id']) ) {
$id = $_SESSION['user_id'];
$accordion = $_POST['del_h3name2'];
echo '$accordion';
$delete = "DELETE FROM useraccordion WHERE id='$id', h3= '$accordion' ";
$result = mysqli_query($delete);
if ($result) {
echo "YES";
} else {
echo "NO";
}
}
?>
You didn't add the html so I really don't know if the value you are sending is correct, but you do have error in your SQL syntax:
DELETE FROM useraccordion WHERE id='$id', h3= '$accordion'
^ This is wrong.
You can DELETE where id = x AND h3 = y:
$delete = "DELETE FROM useraccordion WHERE id='$id' AND h3= '$accordion' ";
Note that your code is vulnerable for SQL injections (read about boby tables).
Related
I would like to update the data in the frontend when it is changed in the database. The code I'm using is given below:
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<div id="test">
<?php
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = 1;";
if(mysqli_fetch_assoc(mysqli_query($conn, $query))["name"] == "MyName")
echo 'Hi <b>MyName!</b>';
else
echo 'You are not <b>MyName</b>.';
?>
</div>
<script>
setInterval(function(){
$.get("/test.php", function(data){
let $data = $(data);
$("#test").append($data.find("#test > *"));
});
}, 1000);
</script>
However, when the data is updated, it does not get updated in the frontend unless refreshed. When I use jQuery's load() function, it works perfectly. Why does this not work?
As I suggested in the comment, if you create a stand alone PHP Script, it might be like:
getUserName.php
<?php
$id = (int)$_GET['id'];
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = $id;";
$myName = "";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$myName = $row;
}
}
mysqli_free_result($result);
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($myName);
?>
This is a very basic example and I would strongly advise you switch to using prepared statements to avoid the risk of SQL Injection.
In your HTML you can now do:
<script>
setInterval(function(){
$.getJSON("/getUserName.php", { id: 1 }, function(data){
$("#test").append(data.name);
});
}, 1000);
</script>
This will ping the script every second and you will have a list of names appearing.
the success function is working but the data is not going in the database
$(document).ready(function() {
$("#ChatText").keyup(function(e){
if(e.keyCode == 13) {
var ChatText = $("#ChatText").val();
$.ajax({
type:'POST',
url:'InsertMessage.php',
data:{ChatText:ChatText},
success:function(){
$("#ChatText").val("");
}
});
}
});
setInterval(function(){
$("#ChatMessages").load("DisplayMessages.php");
},15000000);
$("#ChatMessages").load("DisplayMessages.php");
});
PHP
<?php
session_start();
include "connectToDB.php";
if(isset($_POST['ChatText'])){
$uid = $_SESSION['userid'];
$gid = $_SESSION['GameId'];
$ct = $_POST['ChatText'];
$sql = "INSERT INTO `chats`( `ChatUserId`, `chatGameId`, `ChatText`) VALUES ('$uid','$gid',$ct);";
$result = mysqli_query($_db , $sql);
}
?>
one thing u could do to debug is that echo your sql query and see if you get the correct query that works. You can event try out that query in phpMyAdmin and see whats going on. Hard to tell anything without debug.
This question already has answers here:
How can I get the data-id attribute?
(16 answers)
Closed 5 years ago.
I am new to Ajax and I am confused as to how we pass data in Ajax. I have an index.php file which displays some data, it has a link to delete the record, now the problem is, I am not able to figure out how to transfer the id value from index.php of the selected record to ajax file. Also, how should I go about once I have fetched the value in delete.php page where lies the code to delete records.
I have coded as below.
index.php
<div id="delMsg"></div>
<?php
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
echo"</tr>";
}
echo "</table>";
?>
ajax-file.js
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(str){
$('#delMsg').html(str);
}
})
})
})
delete.php
<?php
$id=$_GET['id'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"delete from member where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "error";
}
?>
Hopefully this conveys the idea of how an AJAX call works.
The first thing we want to do is setup our trigger, which in your case is a button with an onclick event.
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<!-- <button id="delete">Delete Something</button> -->
<button id="delete" onclick="onClickHandler(5)">Delete Something</button>
<p id="message">AJAX</p>
<script>
/* Notice I removed the document ready */
function onClickHandler(id)
{
event.preventDefault();
$.ajax(
{
url:"delete.php",
method:"POST", /* In the real world you want to use a delete here */
data: { /* plugin your data */
id: id,
name: "Bob",
age: 25
},
dataType:"html",
success: function(success) {
// Handle the success message here!
if (success) {
$('#message').text("Your message was received!");
}
},
error: function(error) {
// Handle your errors here
$('#message').text("Something went wrong!");
}
});
};
</script>
Notice how my data is prepared in the data object. I leave it up to you to figure out how to grab data and set it in the right field. You could: $('#someId').value(); or pass it through a function. If this is a source of confusion I can clarify.
data: { /* plugin your data */
id: 1,
name: "Bob",
age: 25
},
Next, we need to setup our script.
delete.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Obviously validate the data.
// But this is how you access it.
// $_POST is a global array, so you can access it like so:
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
// Do your server side stuff...
$sql = "DELETE FROM member
WHERE id = '{$id}' AND name = '{$name}' AND age = '{$age}'";
// Do your SQL (delete) here
// $con = mysqli_connect("localhost","root","","ajaxtest");
// Use prepared statements http://bobby-tables.com/php
// $data = mysqli_query($con,"delete from member where id='$id'");
// if ($data) { // Your condition
// This is where you would check if the query passed
// and send back the appropriate message.
if ($id) {
echo json_encode($id);
}
else {
echo http_response_code(500);
}
}
else {
echo "You don't belong here!";
}
you should use what is called JSON ( Javascript Object Notation, I think). This will let you order your data better to do that you have to use, json_encode.
Now I am not exactly sure what you mean by this id value from index.php
But taking your index.php file, I would change it like this
//make sure the is no space here
<?php
//start output buffering
ob_start();
$html = ['<div id="delMsg"></div>'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
$html[] = "<table>";
while($row=mysqli_fetch_array($data))
{
$html[] = "<tr>";
for($i=0;$i<$col;$i++)
{
$html[] = "<td>".$row[$i]."</td>";
}
$html[] = "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
$html[] = "</tr>";
}
$html[] = "</table>";
$result = [
'html' => implode("\n", $html),
'debug' => ob_get_clean()
];
header("Content-type:application/json");
echo json_encode($result);
//?> ending tags are undesirable
Your JavaScript part will change too
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(data){
$('#delMsg').html(data.html);
}
})
})
})
You can see now that instead of just returning HTML, We will be returning it like this data in the Javascript and $result in php
{
html : '<div id=" ...',
debug : ""
}
I added ob_start and ob_get_clean this can be helpful because you cannot just echo content when outputting JSON, so this will catch any echo or print_r type content and put that into the debug item in the return.
Just replace
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
To
echo "<td><a onclick="deleteRow($row[0])">Delete</a></td>";
Javascript
function deleteRow(recordID)
{
event.preventDefault();
$.ajax({
type: "GET",
url: "delete.php",
data:{id: recordID}
}).done(function( result ) {
alert(result);
});
}
In your PHP I recommend you to use PDO which is more easy and protected from SQL injection attacks.
PHP:
$db = new PDO('mysql:host=localhost;dbname=yourDB','root','');
$query = $db->prepare("Delete From yourTableName Where ID=:ID");
$id=$_GET['id'];
$query->bindParam('ID', $id);
$query->execute();
if ($query->rowCount()) {
echo "success";
}
else
{
echo "fails";
}
I have a jquery save script like :
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Your file is save as : '+ naam);
window.location.replace("index.php?id=latest");
}
else
{
alert('Not saved');
}
I save a div in save.php which creates an new id in the database
What I want to achive is were
window.location.replace("index.php?id=latest");
id=latest must become (id=id from last saved file).
I tried
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
window.location.replace("index.php?id="+MBId);
and
var MBID =
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo $MBId ?>
window.location.replace("index.php?id="+MBId);
They both failed.
How can I run the query in the if(naam !=null) statement?
At first place you must fix your jQuery POST... You don't use POST respond which is wrong.. You should wait for it and then continue with other actions
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam }, function(responde){
if(responde.id)
window.location.replace("http://yoururl.com/index.php?id="+responde.id);
else
alert("No responde...");
}, "json");
}
else
{
alert('Not saved');
}
For better results I suggest you to use JSON data in that post/respond..
At your PHP code you have to set:
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo json_encode(array('id'=>$MBId));
exit();
?>
P.S. For window.location.replace please set your FULL url: "http://localhost/index.php?id=" OR atleast put slash at start of it "/index.php?id="
Solution
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Uw moodboard is opgeslagen als '+ naam);
window.location.replace("index.php?id=<?php $q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = ($data[0] + 1); echo "$MBId";?>");
}
This Works for me , i didnt need to make a jquery var i could echo the variable in php.
And i had to add 1 cause the sql query is loaded when the page is loaded.
So the file isn't saved yet when i get the highest id.
My PHP script generates a table with rows which can optionally be edited or deleted. There is also a possibility to create a new Row. The PHP is activated through jQuery Events.
Now all works well, I can edit delete and create an Item. After each action which makes use of the PHP script the HTML table gets updated.
But when I try after an Event to do an action again the HTML Table doesn't get updated though in the background the PHP script makes an entry into the database.
Does someone of you know why my HTML Table doesn't update itself when I trigger a second event?
Here is the Script:
PHP
<?php
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD)
or die ("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME,$dbh)
or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if($action == "new")
{
mysql_query("INSERT INTO `place` (`id`, `name`) VALUES (NULL, '$name')");
}
elseif($action == "edit")
{
mysql_query("UPDATE `place` SET `name` = '$name' WHERE `id` = '$id'");
}
elseif($action == "delete")
{
mysql_query("DELETE FROM place WHERE id = '$id'");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=".$row["id"]." class=inputfield_td><input class=inputfield_place type=text value=".$row["name"]." /></td><td class=place_name>".$row["name"]."</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function (html){
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display","none").prevAll(".place_name").css("display","none").prevAll(".inputfield_td").css("display","block").nextAll(".cancel").css("display","block").nextAll(".save").css("display","block").prevAll(".inputfield_td").css("display","block");
});
$(".cancel").live("click", function() {
myvariable5 = $(this).prevAll(".place_name").html();
$(this).css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none").nextAll(".save").css("display","none").siblings().find("input[type=text]").val(myvariable5);
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display","none").prevAll(".cancel").css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none");
$.post("place/place_list.php", {action: "edit", name: ""+myvariable1+"", id: ""+myvariable2+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
$.post("place/place_list.php", {action: "delete", id: ""+myvariable3+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {action: "new", name: ""+myvariable4+""}, function (html){$("#place_container").replaceWith(html);});
});
});
I think I know. You do replaceWith instead of append, so your DIV with ID #place_container disappears after the first operation (you are left with only a table in your page), and of course jQuery does not find it and is unable to refresh it with new content from the second operation.
Just use append or, better yet, html methods.
Shouldnt you replace the complete table ?
$("#place_container").html(html);