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.
Related
I have written a script i JQuery and PHP,
After the success return from PHP, AJAX function should catch a success response but I am not getting that.
Below is the code:
$.ajax({
url :"script_admin-add-category.php",
method :"POST",
data :{lExpensesId:lcl_ExpensesId},
success:function(data){
//if(data=="ok"){
if(data=="YES"){
alert("EMAIL");
}else{
alert(data);
}
//}
//if(data=="ok"){
//alert("Expenses Id already exists!");
//}else{
//alert(data);
//}
}
});
and here is the php code
//Check connection
if(!$conn){
die("Connection Failed: " .mysqli_connect_error());
}else{
//echo "helloooo";
if(isset($_POST["lExpensesId"])){
$lExpensesId = $_POST["lExpensesId"];
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
if($query_result = mysqli_query($conn, $Lquery)){
if(mysqli_num_rows($query_result )){
echo 'YES';
}else{
//echo "Proceed";
}
}else{
echo "Not Okay";
}
}else{
}
}
I can see the echo value on browser and alert value also. But if condition is not working for success function???
Try set correct data type for returned data.
$.ajax({
url: 'script_admin-add-category.php',
method: 'POST',
data: {lExpensesId: lcl_ExpensesId},
dataType: 'text',
success: function (data) {
if (data === 'YES') {
alert('EMAIL')
} else {
alert(data)
}
}
})
#J Salaria as i understood your question you are having problem with jquery AJAX and PHP code as you are not getting you desired result. There are different ways to send the data through jquery ajax which i will be explain in detail.
$_POST["lExpensesId"] are you getting this ID from a HTML <form> ?.Because here i'll be showing you 3 different practiced ways to send data through ajax..
NOTE: YOUR CODE IS VULNERABLE TO SQL INJECION. I'LL BE ALSO SHOWING YOU THE METHODS TO OVERCOME.IF YOU WANT TO LEARN MORE ABOUT SQL INJECTION CLICK ON THIS LINK SQL INJECTION LINK
HTML FORM CODE :
<form action="" id="send_lExpensesId_form" method="post">
<input type="text" name="lExpensesId" id="lExpensesId" >
<input type="submit" name="submit" >
</form>
FIRST WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var form_serialize = $(this).serialize();
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:form_serialize,
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
SECOND WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var form_serialize = new FormData($(this)[0]);
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:form_serialize,
contentType: false,
processData: false,
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
THIRD WAY FOR SENDING DATA THIS IS USED WHEN A LINK CLICKED OR TO DELETED THROUGH ID OR CLASS
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var lcl_ExpensesId = $("#lExpensesId").val();
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:{lExpensesId:lcl_ExpensesId},
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
HERE IT THE PHP CODE WITH mysqli_real_escape_string(); AGAINST SQL INJECTION
<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "demo";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST["lExpensesId"])){
$lExpensesId = mysqli_real_escape_string($conn, $_POST["lExpensesId"]);
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
if($query_result = mysqli_query($conn, $Lquery)){
if(mysqli_num_rows($query_result )){
echo 'YES';
}else{
echo "Proceed";
}
}else{
echo "Error".mysqli_connect_error();
}
}
?>
HERE IT THE OTHER PHP CODE WITH MYSQLI->PREPARED WHICH IS BETTER AGAINST SQL INJECTION
<?php
// WITH MYSQLI PREPARED STATEMENT AGAINST SQL INJECTION
$sql = $conn->stmt_init();
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId =?";
if($sql->prepare($Lquery)){
$sql->bind_param('i',$lExpensesId);
$sql->execute();
$sql->store_result();
if($sql->num_rows > 0){
echo 'YES';
}else{
echo "Proceed";
}
}
else
{
echo "Error".mysqli_connect_error();
}
?>
I HOPE YOU GOT ANSWERE FOR YOU QUESTION IF YOU HAVE OTHER DOUBTS FEEL FREE AND COMMENT BELOW
All methods are known and many thanks for assistance. My question is that Why I am not able to get proper return from PHP. Below is my code:
var lcl_ExpensesId = $("#IExpensesId").val();
//alert(lcl_ExpensesId);
$.ajax({
url :"script_admin-add-category.php",
method :"POST",
data :{lExpensesId:lcl_ExpensesId},
success:function(data){
if(data=="ok"){
alert("Inserted");
}else{
alert(data);
}
}
});
ob_start();
/------------------FUNCTION TO READ ACCOUNTS DROPDOWN EXPENSES LIST -----------------------/
require_once 'db_config.php';
$newlist = fxn_CONFIGURATION();
$HOST = $newlist[0];
$DBNAME = $newlist[1];
$UNAME = $newlist[2];
$PSWD = $newlist[3];
$conn = mysqli_connect($HOST, $UNAME, $PSWD, $DBNAME);
//Check connection
if(!$conn){
die("Connection Failed: " .mysqli_connect_error());
}else{
if(isset($_POST["lExpensesId"])){
$lExpensesId = $_POST["lExpensesId"];
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
$query_result = mysqli_query($conn, $Lquery);
if(mysqli_num_rows($query_result) > 0){
echo "ok";
}else{
echo "Proceed";
}
}
}
mysqli_close($conn);
ob_flush();
As, i am using this AJAX in my one of input keyup method so whatever I will type, each and everytime, it will execute PHP script. I am having a item as FOOD in databse. When i type "F", I got Proceed, "O" - Proceed, "O" - Proceed, "D" - ok....
When I type D, i should get "Inserted" instead of Ok....
This is my doubt that why i m getting this????
The above problem is resolved by using exit() statement in PHP as I am getting five ↵↵↵↵↵ after my values and it means I am having 5 lines of html without closing ?>. So the best way to resolve the issue is to use exit() in PHP as per need
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);
}
?>
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;
}
I am building a small php application where you can add people and then see them on a page. When I was simply adding it went fine, but then I started using a switch and now it doesn't work to either add or retrieve. I cannot see any problem in my syntax, can anyone see something wrong?
php
<?php
$con = mysql_connect("hostWasHere","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbIsHere", $con);
try{
switch($_POST['action'])
{
case 'retrieve':
$show=mysql_query("Select * from test",$con);
while($row=mysql_fetch_array($show)){
echo "<li><b>$row[firstName]</b> : $row[lastName]</li>";
}
mysql_close($con);
break;
case 'new':
$sql="INSERT INTO test (firstName, lastName)
VALUES
('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
break;
}
}
?>
The javascript using this is :
function saveToServer() {
alert("clicked");
$.post("api.php", {
'action': "new",
'fname': $('#fname').val(),
'lname': $('#lname').val()
},
function () {
alert("succes");
}
);
}
function getFromServer() {
console.log("in get!");
$.ajax({
type: "post",
url: "api.php",
data: "action=retrieve",
success: function (data) {
$("#comment").html(data);
console.log("success!");
}
});
}
You are using a try block without any catch or finally – this doesn't work. Most likely, your server is configured not to output any errors, so it dies silently.
A few other remarks:
As pointed out in the comments, please use PDO or MySQLi instead of the deprecated MySQL class.
Beware of SQL injection and always sanitize properly, no excuses. (My code below with PDO uses prepare and takes care of this.)
Use quotes when you're accessing an array with a string as key: $_POST['fName'] or $row["lName"], as opposed to $row[lName].
Output all errors while you're developing your page by adding error_reporting(E_ALL) at the top of your file. Note that server settings may still suppress the error output, but this generally takes care of everything.
Using a switch statement with a lot of code is never a good idea; you want to keep all code there rather lightweight or switch to a combination of if, else if and else.
Enough talk. Here's my edit for your page, using PDO instead of the deprecated MySQL family.
<?php
error_reporting(E_ALL);
// PDO has more options to read about
// for initialization, but this should do for now
$con = new PDO("host=host;dbname=db_here", "username", "password");
if (!$con) {
die('Could not connect: !');
}
// Do some validation on $_POST before using it.
$action = '';
if(isset($_POST['action'])) {
$action = $_POST['action'];
}
if($action == 'retrieve') {
$sql = $con->execute('SELECT * FROM test');
$rows = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
echo '<li><b>'.$row['firstName'].'</b> : '.$row['lastName'].'</li>';
}
$con = null;
}
else if($action == 'new') {
$sql = $con->prepare('INSERT INTO test (firstName, lastName)
VALUES (?, ?)');
// TODO: more checks on fname and lname before accepting
if(isset($_POST['fname']) || isset($_POST['lname'])) {
$result = $sql->execute( array($_POST['fname'], $_POST['lname']) );
if(!$result) {
die('Error occured');
}
else {
echo 'Added 1 row';
}
}
$con = null;
}
else {
// TODO: Default page
}
PS: Please don't ever trust user input. The code is still inserting $_POST values rather blindly (just checking that they're at least set), further checks with is_scalar() and some length checks would probably be good.
I hope this can help – good luck with your project!
PHP PAGE:
<?php
include "linkpassword.inc";
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_assoc($showresult);
}
function addVote()
{
$sql= "UPDATE mms SET votes = votes+1 WHERE color = '".$_POST['color']."'";
$result= mysql_query($sql) or die(mysql_error());
return $result;
}
addVote();
showVotes();
?>
I am trying to get the output of the array to load into a JavaScript page where I can break up the array into seperate divs that have IDs assigned to them. Here is what I tried
<script>
$(document).ready(function () {
$('.answer').click(function (e) {
var color = $(this).attr("data-color");
$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
dataType: 'json',
cache: false,
success: function(showVotes) {
$('#rvotes').html(showVotes[0]);
},
error: function (jqXHR) {
}
})
})
});
</script>
Where am I going wrong??
From what you've posted in comments, what you have is an array of objects.. not html, as your function seems to indicate. Depending on what you want done, the answer would be either of the following, to access that object's properties:
showVotes[0].votes
Or
showVotes[0]['votes']
Eg:
$('#rvotes').html(showVotes[0].votes);
Or etc.
Second attempt:
Firstly, change your current 'showVotes' function to this:
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_assoc($showresult)) {
$response[] = $row;
}
return json_encode($response);
}
Secondly, remove your 'connected successfully' text from the page, as well as any other text generated by anything else(aka, the other function which returns a result pointer). I may be wrong, but it would seem to me that the generation of this other text is causing the returned json to be interpreted as malformed.
Quick explanation on PDO:
try {
$dbh = new PDO("mysql:host=localhost;dbname=dbname", "user", "password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
echo "Error! Could not connect to database: " . $e->getMessage() . "<br/>";
die();
}
Connecting to the database.. This is how I've learned to do it, though I've been warned(and downvoted) to not check for errors this way, though it was never explained why.
Database interaction:
$stmt = $dbh->prepare("UPDATE mms SET votes = votes+1 WHERE color = :color");
$stmt->bindParam(":color",$_POST['color']);
$stmt->execute();
Result use:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$response[] = $row;
}
And so on and so forth. PDO escapes the values for you, so you don't have to worry about injection attacks.