I try to DELETE a row in mysql. I got help to insert and it works well. I tried to use the same logic for delete one row with ID identification, but I can not delete the row.
What is wrong in this code?
...
Here is the full code:
Javascript:
function jsRecordDeleteWrite()
{
var jsObject = {
"ID": document.form_articles.ID.value
};
// ... the AJAX request is successful
var updatePage = function (response) {
alert("record successful deleted");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("deletingt record failed");
};
// Create an object to describe the AJAX request
$.ajax({
url : 'deletearticle.php',
dataType : 'json',
contentType: 'application/x-www-form-urlencoded',
data : jsObject,
type : 'POST',
success: updatePage,
error: printError
});
}
Here is deletearticle.php
<?php
$link = mysql_connect('localhost', 'admin0', 'star1star1star0');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sob', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//read the json file contents
$ID = $_POST['ID'];
//delete item from mysql table
$sql = mysql_query("DELETE FROM articles WHERE ID=$ID");
if(!mysql_query($sql))
{
die('Error : ' . mysql_error());
}
//database connection close
mysql_close($link);
//}
?>
Verify that the server receives in php
var_dump($ID);
If query is right, check the mysql user has rights to update table
Put single quotes around $ID:
//delete item from mysql table
$sql = mysql_query("DELETE FROM articles WHERE ID= '$ID'");
Related
i have a ajax and php as follows but it is not changing the value of html attribute with id #respo
is there any modification require?
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
dataType: "json",
data: {reccount: reccount},
success: function(response) {
var response = ($response);
$("#respo").text(response);
},
})
and php as
<?php
$id = $_POST['reccount'];
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "testsite");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "SELECT response from paper WHERE ID=$id";
$result=mysqli_query($link, $sql);
while ($row = mysql_fetch_row($result)) {
$response => $row['response'];
}
echo json_encode($response);
// Close connection
mysqli_close($link);
?>
i want to assign a value of response to html element with id respo
Your code must look like
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
success:function(data){
var obj = jQuery.parseJSON(data);
document.getElementById('elementName').value = obj.varaibleName;
}
});
When using Select2 on localhost (XAMPP) server to get data from the database, it works perfectly. But after deploying it to server, it doesn't work, and console shows 500 Internal Server Error.
Following is the code I'm using:
$('#search-box').select2({
placeholder: 'Select an item',
ajax: {
url: 'php/search.php',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
And the PHP code in search.php:
require_once("dbinfo.php");
// Opens a connection to a MySQL server
$connection=mysqli_connect ('localhost', $username, $password);
if (!$connection) { die('Not connected : ' . mysqli_error($connection));}
// Set the active MySQL database
$db_selected = mysqli_select_db($connection, $database);
if (!$db_selected) {
die ('Can\'t use db : ' . mysqli_error($connection));
}
$sql = "SELECT c_id, city_name FROM city
WHERE city_name LIKE '%".$_GET['q']."%'
LIMIT 10";
$result = $connection->query($sql);
$json = [];
while($row = $result->fetch_assoc()){
$json[] = ['id'=>$row['c_id'], 'text'=>$row['city_name']];
}
echo json_encode($json);
What is going wrong here?
In the ajax, set type to "GET"
ajax: {
url: 'php/search.php',
type: 'GET',
dataTy.......
This works for me.
I want delete a record from database and to do it I want use ajax..
So I have a table where I put into last td this:
<input type='image' src='./img/delete.png' onClick='deleteUser(".$utentiIscritti[$i][0].");' />
this is my deleteUser function:
function deleteUser(id){
$.ajax({
type:"post",
url: "deleteUserAjax.php",
data: {'id':id},
success: function(data){
console.log("OK");
location.reload();
},
error: function(xhr, status, error){
alert(xhr+"\n\n"+status+"\n\n"+error);
console.log("KO");
}
});
}
And this is my php page to connect to db and delelte the record:
<?php
$USERDB = "u";
$PASSWORDDB = "p";
$NAMEDB = "d";
$queryDeleteUser = 'delete from user where id = "'.$_POST['id'].'"';
$conn = mysql_connect("localhost", $USERDB, $PASSWORDDB)
or die("Errore nella connessione al database: " . mysql_error());
mysql_select_db($NAMEDB) or die("Errore nella selezione del database: " . mysql_error());
mysql_query($queryDeleteUser) or die("Errore nella query: " . $queryDeleteUser . "\n" . mysql_error());
dbDisconnect($conn);
But I obtain always (from every ajax request) error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
iscritti.php:80
Why???
You can consider two solutions.
Your code is buggy. Try to execute it on it's own. Just call it in your browser and check the result!
You have specified a relational path for your script. url: "deleteUserAjax.php", try instead an absolute path and check the result (url: "http://yourdomain.com/deleteUserAjax.php")
Maybe make it more cleaner:
HTML part:
<input type='image' src='./img/delete.png' value='<?=$id?>'>
jQuery part:
$(document).ready(function(){
$("#delete").on("click", function(){
var data = $(this).val();
$.ajax({
method: "POST",
url: "page_you_handle_it.php?action=delete",
data: {'id':id}
}).done(function(data){
//here you get response of your delete function!
});
});
});
PHP part:
$host = "[HOST]"; //Like localhost
$user = "[USER]"; //Like root
$pass = "[PASS]"; //Like 123
$db = "[DB]"; //Like users
$con = mysqli_connect($host, $user, $pass, $db) or die ("Conntecting the Database gone wrong");
$id = $_POST['id'];
$query_str = "DELETE FROM user WHERE id = '$id'";
$query = mysqli_query($con, $query_str);
if (!$query) //Do not run the `$query` in the return parts because it already runs when you say `if (!$query)`
{
echo 'Delete gone wrong';
}
else
{
echo 'Delete succes!';
}
I'm using PhoneGap to create a Android QR code scanning app which act as a client, while the server is using PHP with MySQL (WAMP). Below is the section of QR scanning app to send the scanned result to the server, it manage to send and get reply from server, so I think the problem is at my server code in the next section
$.ajax({
url: "http://192.168.1.2/receiveQR.php",
type: 'POST',
data: {
QR: result.text
},
success: function(response) {
$('#result').html(''); //clean the field
alert("QR sent to server successfully");
$("#result").append(response + '<br/>');
},
error: function() {
alert('Not working!');
}
});
Server code: to receive the QR scanned result as input then use the input to retrieve record from MySQL database to display the result on PHP page immediately, although my code can successfully retrieve the record from db, but the ECHO is show on my Android APP and not my server PHP interface.
I want to achieve result like Library Barcode Scanning result, is my method wrong?
<?php
if(isset($_POST['QR'])){ //check is the QR result is empty or not
$qr = $_POST['QR']; //QR scanned result send from APP to server
$tablename = "book";
$db = mysql_connect("localhost", "root", "");
if(!mysql_select_db("testing", $db)){
print mysql_error();
}
if(!empty($qr)) {
$sql="SELECT bk_title FROM ".$tablename." WHERE bk_id = '".$qr."'";
$retval = mysql_query($sql, $db);
if(! $retval){
die("Cound not get data: ".mysql_error());
}
while($row = mysql_fetch_assoc($retval)){
echo "Book Title :{$row['bk_title']} <br> ";
}
mysql_close($db);
}
$reply = "Server Received";
print json_encode($reply);
}
?>
You did couple of mistakes over here.
Please replace your code with below code:
$.ajax({
url : "http://192.168.1.2/receiveQR.php",
dataType: "json"
type : 'POST',
data : { QR : result.text},
success : function(response){
$('#result').html(''); //clean the field
alert("QR sent to server successfully");
$("#result").append(response.data + '<br/>');
},
error : function() {
alert('Not working!');
}
});
<?php
if(isset($_POST['QR']))
{
//check is the QR result is empty or not
$qr = $_POST['QR']; //QR scanned result send from APP to server
$tablename = "book";
$db = mysql_connect("localhost", "root", "");
if(!mysql_select_db("testing", $db)){
print mysql_error();
}
if(!empty($qr)) {
$reply=array();
$sql="SELECT bk_title FROM ".$tablename." WHERE bk_id = '".$qr."'";
$retval = mysql_query($sql, $db);
if(! $retval){
die("Cound not get data: ".mysql_error());
}
while($row = mysql_fetch_assoc($retval)){
$reply['data'] = "Book Title :{$row['bk_title']} <br> ";
}
mysql_close($db);
}
$reply['message'] = "Server Received";
print json_encode($reply);
}
?>
use this one
javascript
formData = {
QR: result.text
}
$.ajax({
url: "http://192.168.1.2/receiveQR.php",
type: 'POST',
data: formData,
success: function(response) {
$('#result').html(''); //clean the field
alert("QR sent to server successfully");
$("#result").append(response + '<br/>');
},
error: function() {
alert('Not working!');
}
});
php
<?php
if(isset($_POST['QR'])){ //check is the QR result is empty or not
$qr = $_POST['QR']; //QR scanned result send from APP to server
$tablename = "book";
$db = mysql_connect("localhost", "root", "");
if(!mysql_select_db("testing", $db)){
print mysql_error();
}
if(!empty($qr)) {
$sql="SELECT bk_title FROM ".$tablename." WHERE bk_id = '".$qr."'";
$retval = mysql_query($sql, $db);
if(! $retval){
die("Cound not get data: ".mysql_error());
}
while($row = mysql_fetch_assoc($retval)){
echo "Book Title :{$row['bk_title']} <br> ";
}
mysql_close($db);
}
$reply = "Server Received";
print json_encode($reply);
}
?>
I have taken a jQuery script which would remove divs on a click, but I want to implement deleting records of a MySQL database. In the delete.php:
<?php
$photo_id = $_POST['id'];
$sql = "DELETE FROM photos
WHERE id = '" . $photo_id . "'";
$result = mysql_query($sql) or die(mysql_error());
?>
The jQuery script:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The div goes away when I click on it, but then after I refresh the page, it appears again...
How do I get it to delete it from the database?
EDIT: Woopsie... forgot to add the db.php to it, so it works now >.<
There's no way the php could even come close to working. Where is the database? Check out http://www.php.net/manual/en/mysql.examples-basic.php from which you can see there's more to the database than just a query.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
You have your data as a GET string, but you are using a POST request, try changing your string variable to an object. Like :
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = { id : id };
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
Plus I am hoping you are preparing your MySQL connection properly in your PHP, you cannot just call mysql_query and hope it will know which database you mean, and how to connect to it by itself :)
Look at #Quotidian answer! :)