Delete MySQL row from JQuery Ajax - javascript

Good Day!
I'm trying to delete a row in a MySQL database, via PHP, with an AJAX request.
I thought it was easy with $.ajax {}but for some reasons, no row isn't deleted...
I have this script (with jQuery):
function deleteRecord(i) {
console.log("Line to delete: " + i);
$.ajax({
type:"post",
url:"../php/delete.php",
data: { delete : i },
success:function(data){
console.log("Line deleted from the database.");
$("#results").empty();
showWholeDB();
}
});
}
and in the PHP side:
<?php
if (isset($_POST['delete'])) {
$sql = "DELETE id FROM table1 WHERE id=".$_POST['delete'];
$con = mysqli_connect("localhost", "root", "", "myDB");
if (!$con) {
die("Connection failed: " . mysqli_error($con));
}
mysqli_query($con, $sql);
mysqli_close($con);
}
?>
In the console log I see the messages:
Line to delete: 215
(the line I want to delete)
and :
Line deleted from the database.
Then the frame empties and the database is loaded again, but my line is still here!
I used this post here.
I'm not sure if I missed something but it's not working...
Can somebody help me, please ?
Thank You very much in advance! :)

Your Delete query syntax should be
DELETE FROM table1 WHERE id=2
Try to use prepared statement like this .
<?php
if (isset($_POST['delete'])) {
$con = mysqli_connect("localhost", "root", "", "myDB") or die("Connection failed: " . mysqli_connect_error());
$stmt = $con->prepare("DELETE FROM table1 WHERE id=?");
$stmt->bind_param('i',$_POST['delete']);
//The argument may be one of four types:
//i - integer
//d - double
//s - string
//b - BLOB
//change it by respectively
$stmt->execute();
$row_count= $stmt->affected_rows;
if($row_count>0)
{
echo "Deleted";
}else{
echo "Not Deleted";
}
$stmt->close();
$conn->close();
}
?>

Change
$sql = "DELETE id FROM table1 WHERE id=".intval($_POST['delete']);
TO
$sql = "DELETE FROM table1 WHERE id=".intval($_POST['delete']);

Check your delete query
DELETE FROM table_name [WHERE Clause]

i think the "delete" parameter in ajax did not post the data to url that's why this is my running code
Jquery :
$.ajax({
url: 'url',
type: 'post',
data: {
'user_id': id
},
success: function (res) {
$('#user_'+id).slideUp(500);
}
});
PHP :
mysql_query("DELETE FROM tblusers WHERE user_id = $user_id");

Your delete syntax is wrong, see delete from documentation And you should also use prepared statements in your php.
function deleteRecord(i) {
console.log("Line to delete: " + i);
$.ajax({
type:"post",
url:"../php/delete.php",
data: {delete : i },
dataType : "json",
encode : true,
success:function(data){
if(data == "ok"){
console.log("Line deleted from the database.");
$("#results").empty();
showWholeDB();
}else{
console.log(data);
}
}
});
}
</script>
delete.php
<?php
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
if (isset($_POST['delete'])) {
$idToDelete = intval($_POST['delete']);
$sql = "DELETE FROM table1 WHERE id= ?";
$stmt = $con->prepare($sql);
$stmt->bin_param("i", $idToDelete);
if ($stmt->execute()) {
echo "ok";
} else {
echo "Error : " . $con->error;
}
}
?>

<?php
if (isset($_POST['delete'])) {
$sql = "DELETE FROM table1 WHERE id=".$_POST['delete'];
$con = mysqli_connect("localhost", "root", "", "myDB");
if (!$con) {
die("Connection failed: " . mysqli_error($con));
}
mysqli_query($con, $sql);
mysqli_close($con);
}
?>

Related

Function Send from JS to PHP

I've tried to pass the "hide" value for delete a record. But the JS function send the data but the mysql code don't work.
With the "insert to" it works, for this it's strange that the same code don't work.
This is my code.
<script type="text/javascript">
function invia()
{
var hides = document.getElementById('hide').value;
$.ajax({
type: 'POST',
url: "note_db_php/delete_db_note.php",
data: {"hide": hides},
success: function(data){
console.log("Dati inviati");
},
error: function(data) {
console.log("Dati non inviati");
}
});
};
</script>
and this is the delete page;
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
$hide = $_POST["hide"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM note WHERE id='$hide'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
The console.log it work, and print "Dati inviati". So really, I don't understand. I have not error's message. But still don't work.
I have no idea why your code is not working -- you haven't described in any detail what error messages you are getting. But what other problem you have is that you are leaving yourself open to SQL Injection attacks and so you should be using a prepared statement. If this also corrects your problem (doubtful), that's a bonus:
$stmt = $conn->prepare("DELETE FROM note WHERE id=?");
/* Bind our parameter: */
$stmt->bind_param('i', $hide); // assuming $hide is an integer value, else use 's' for string
$success = $stmt->execute(); // execute the statement
if (!$success) {
error code here
}
$stmt->close();
I think the issue is with the sql query - $sql = "DELETE FROM note WHERE id=$hide";
Can you put the $hide in single quotes and try?
$sql = "DELETE FROM note WHERE id='$hide'"; // this will work
here your problem in sql syntax, and one line
enter code here
after else open on your code that causing error
updated query here , its working
// sql to delete a record
$sql = "DELETE FROM note WHERE id='$hide'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
The attribute dataType is missing and type should be method.
$.ajax({
url:"note_db_php/delete_db_note.php",
method:'POST',
dataType:'json',
data:{
"hide": hides
},
success:function(data) {
console.log("Dati inviati");
},
error: function (request, status, error) {
console.log("Dati non inviati");
}
});
Replace your query -
$sql = "DELETE FROM note WHERE id='$hide'";
With below one -
$sql = "DELETE FROM note WHERE id = ".$hide;
And on the ajax end please console your data. If it is giving error then please echo your query (echo $sql), and copy and run the query in PHPMyAdmin.

Selecting row with multiple parameters (ajax and PHP)

Good Day,
I'm new to PHP/MySQL and I try to send a request from ajax and select a row in a database with multiple parameters.
Is this the good way to do that ?
AJAX (Jquery):
function readLine(name, firstname) {
$.ajax({
type: "post",
url: "./php/readLine.php",
dataType: 'json',
data: { name: name, firstname: firstname },
success: function(data) {
console.log(data);
}
error: function(data) {
console.log("An error occured!");
}
});
}
PHP:
<?php
$sql = "SELECT * FROM table1 WHERE firstname=".intval($_POST['firstname'])." AND name=".intval($_POST['name']);
$con = mysqli_connect("localhost", "root", "", "myDB");
if (!$con) {
die("Connection failed: " . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$to_encode = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
$to_encode[] = $row;
}
echo json_encode($to_encode);
mysqli_close($con);
?>
Thanks for your help.
You can do it using PDO with prepared statements, that'll make sure the user input is made safe. Like this:
try {
$db = new PDO('mysql:dbname=db_name;host=localhost', 'db_user', 'db_password');
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
$sql = "SELECT * FROM table1 WHERE firstname=:firstname AND name=:name";
$stmt = $db->prepare($sql);
$stmt->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STRING);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STRING);
$stmt->execute();
$result = $stmt->fetchAll();
echo json_encode($result);
Move the first 5 lines into an include, then you only need this code once.
Firstly, you should use prepared statements instead, as currently the code is susceptible to SQL Injection attacks. I cannot emphasise this enough, an attacker would be able to wreak havoc on your database with the code you currently have.
You should use something like the following (taken from the page linked above, and this comment on the same page). Note that I have removed the intval calls to your POSTed data, as I assume they are strings rather than integers.
$to_encode = array();
$mysqli = new mysqli("localhost", "root", "password", "myDB");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM table1 WHERE firstname=? AND name=?")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $_POST['firstname'], $_POST['name']);
/* execute query */
$stmt->execute();
/* instead of bind_result: */
$result = $stmt->get_result();
/* now you can fetch the results into an array - NICE */
while ($myrow = $result->fetch_assoc()) {
// use your $myrow array as you would with any other fetch
$to_encode[] = $myrow;
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
echo json_encode($to_encode);
$stmt = $con->prepare("SELECT * FROM table1 WHERE name=? and firstname=?");
$stmt->bind_param($name ,$firstname);
// set parameters and execute
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$name = mysqli_real_escape_string($con, $_POST['name']);
$stmt->execute();
$stmt->bind_result($to_encode);
$stmt->fetch();
echo json_encode($to_encode);

AJAX PHP combination returning empty string to the JS

I have an AJAX request to fetch the data from MySQL. On request the result variable in the success part contains an empty string, "". If I change the dataType to json I don't get any results in return.
$.ajax({
url: "test.php",
dataType: 'text',
success: function(result) {
alert(result);
}
});
<?php
$con = mysqli_connect("localhost", "root", "", "test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM 'tabel_name'";
$result = mysqli_query($con, $sql);
?>
What could be the reason for this empty string as a result? I have data in the table and I don't get any exceptions.
In your php code
<?php
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM 'tabel_name'";
$result=mysqli_query($con,$sql);
$resultant_array = array();
$index = 0;
while($row = mysql_fetch_array($result)) {
foreach($row as $column => $val) {
$result[$index][$column] = $val;
}
$index++;
}
echo json_ecode($resultant_array);
?>
This way you will get response data within your success promise of ajax

Cannot pass data from my JavaScript to my PHP file

When I click on "subcribeButton" I want it to save the value and pass that value to my PHP file. I want that PHP file to then make a post to the SQL database.
This is my js:
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "save.php", { email: email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
This is my php code, I would like my php code to accept data from my js file and then post the data to my sql database:
<?php
$servername = "localhost";
$username = "user";
$password = "pw";
$dbname = "db_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
echo $text
$sql = "INSERT INTO MyGuests (email)
VALUES ($text)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The result is I'm getting the following error:
POST http://flockto.it/home/save.php 500 (Internal Server Error)
send # jquery.js:4
ajax # jquery.js:4
m.(anonymous function) # jquery.js:4
(anonymous function) # email.js:13
dispatch # jquery.js:3
r.handle # jquery.js:3
so why not adding a callback in your ajax request so you can debug it in console or with an alert see this it may help you
$.post( "save.php", { "email" : email } , function(result){
console.log(result);//here the result will display what you will echo after getting the post in your php file
});
so in your php file you can add this
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
//so if you check the console you will get the email
//value from your php file so then you can insert it at the DB as you want
You have a syntax error.
Your code is missing the ; at the end of this line:
echo $text
It should be:
echo $text;
The solution:
In the js file url was wrong and quotation marks around email were missing
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "data/save.php", { "email": email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
In the php file used the wrong variable
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
$sql = "INSERT INTO MyGuests (email)
VALUES ('$text')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
A million thanks to everyone who replied to this thread and helped me solve the issue.

Save entire DOM in mysql

I am not sure if this is possible, but I am looking for a way to save the entire state of my webpage without explicitly saving each element to a database.
For example, I dynamically create buttons, checkboxes, text etc. until the webpage looks as it needs. Can I save the DOM as a string, or blob in a database, and parse it later the get the webpage back?
I have tried things like:
var doc = document.documentElement.outerHTML;
Then save the string to database but it doesn't work.
I am using an AJAX call to a PHP script to write to mysql:
jQuery.ajax({
type: "POST",
url: 'connect/database.php',
dataType: 'json',
data: {functionname: 'connect_to_database', arguments: [user_id, user, doc] },
success: function (obj, textstatus) {
if( !('error' in obj) ) {
}
else {
console.log(obj.error);
}
}
});
PHP looks like:
// connection script
$servername = "XXX";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
$user_id = $_POST['arguments'][0];
$user = $_POST['arguments'][1];
$string = $_POST['arguments'][2];
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table (user_id, user, string) VALUES ('$user_id', '$user', '$string')";
# $sql = "UPDATE crows_nest SET json_string='$configuration' WHERE user = '$user'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Use a prepared statement to prevent problems with special characters in the document string.
$stmt = $conn->prepare("INSERT INTO table (user_id, user, string) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $user_id, $user, $string);
if ($stmt->execute()) {
echo "New record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

Categories