How to delete row using ajax php mysql - javascript

How to delete a record in php mysql using the AJAX.
here's the code:
delete_record.php
<?php
require_once "../include/connection.php";
if ($_REQUEST['rowid']) {
$sql = "DELETE FROM lesson1 WHERE id='".$_REQUEST['rowid']."'";
if (mysqli_query($conn, $sql) {
//echo "Success";
} else {
//echo "Error: $sql";
mysqli_error($conn);
}
}
myqli_close($conn);
?>
index.php
<script type="text/javascript">
var rowId = null;
$(document).ready(function() {
$(document).on('click', '#btnDel', function(e) {
e.preventDefault();
rowId = $(this).attr('data-id');
});
$('#accDelBtn').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'delete_record.php',
data: 'rowid=' + rowId,
success: function(data) {
alert('Records were deleted successfully');
$('#modalDelete').modal('hide');
}
});
})
});
</script>
what I'm trying to here is to delete a record.
when I'm clicking the delete. message is success but the data is not deleted.

You can try:
Print a message or rowid within:
if ($_REQUEST['rowid']) {}
Check the query in MySQL browser
Check the connection string

Related

How to add php form validation with ajax error handling

How can I add validation and php error handling with ajax. Now the success message come correctly but how can I implement error message on it? I might need to add some php validation please help.
Here is my JS.
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
$(".msg-ok").css("display", "block");
$(".msg-ok-text").html("Profile Updated Successfully!!");
},
error: function() {
//Error Message
}
});
});
PHP
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "<p>Succcessfully Updated</p>";
} else {
echo "Erorr while updating record : ". $connect->error;
}
$connect->close();
}
?>
ajax identifies errors based of status code, your php code will always return status code 200 which is success, even when you get error in php code unless its 500 or 404. So ajax will treat response as success.
if you want to handle php error, make following changes in your code
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "true";
} else {
echo "false";
}
$connect->close();
}
?>
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function (res) {
if(res == 'true') {
//success code
} else if(res == 'false') {
//error code
}
},
error: function() {
//Error Message
}
});
});

Select value into the textbox FROM ajax using php

I am trying to get the results from the database whether username is available or not . But it is not giving any results i am not getting ajax response this is the html code
<form id="user_form">
<input placeholder="username here" type="text" name="ajax-data" id="ajax-data">
<input type="submit" name="btnSubmit" id="btnSubmit" Value="Submit">
</form>
<span class="php_responce_here"></span>
This is the ajax code which i have used
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: {ajax-data: textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result);
}
});
});
});​
</script>
final code of php where i have used the validation and the query to find whether the username is available in the database or not the problem is that it is not giving any of the result
<?php
error_reporting(0);
require "config.php";// configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if($user_name)
{
$usernamecheck= mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check= mysql_fetch_row($usernamecheck);
if($check[0]==0)
{
if($user_name!=""){
if(strlen($user_name)>25){
echo "You have reached the maximum limit";
}
else{
echo "User name is valid";
}
}
else
{
echo "username is empty";
}
}
else{
echo "Username Already Taken";
}
}
?>
should be submit event not click:
$("form#user_form").submit(function(e) {
e.preventDefault();
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: { "ajax-data": textboxvalue },
success: function(result) {
$(".php_responce_here").html(result);
}
});
});
and as #Cyril BOGNOU pointed out;
data: { "ajax-data": textboxvalue }
You should too add data type to be returned with the parameter if you want to return JSON for example
dataType: 'JSON',
and Yes I think you should better write
data: { "ajax-data": textboxvalue }
So the update should be
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
dataType: 'JSON',
data: {"ajax-data": textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result.message);
}
});
});
});
and return json string from PHP script
<?php
error_reporting(0);
require "config.php"; // configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if ($user_name) {
$usernamecheck = mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check = mysql_fetch_row($usernamecheck);
if ($check[0] == 0) {
if ($user_name != "") {
if (strlen($user_name) > 25) {
$message = "You have reached the maximum limit";
} else {
$message = "User name is valid";
}
} else {
$message = "username is empty";
}
} else {
$message = "Username Already Taken";
}
echo json_encode(["message" => $message]);
}
?>
NOTE : mysql is deprecated. you should use mysqli or PDO
There are some mistakes in your code. check the below code. it should work.
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var textboxvalue = $("#ajax-data").val();
$.ajax({
data: {ajaxdata: textboxvalue},
type: "POST",
url: 'second.php',
success: function (result)
{
$(".php_responce_here").html(result);
}
});
return false;
});
});
</script>
You can not create variable ajax-data with -.
PHP
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$user_name'");
$check = mysql_num_rows($usernamecheck);
you should use mysql_num_rows instead of mysql_fetch_row. it will auto calculate the rows.
Check working example
Empty page? Nothing prints out?
<?php
error_reporting(-1);
ini_set('display_errors', 1);
require "config.php";// configuration file holds the database info
if(isset($username = $_POST['ajax-data'])){
if($l = strlen($username) <= 25 && $l > 2){
$sql = "SELECT * FROM users WHERE username='$username'"; // wide open for SQL injections. use mysqli or PDO instead.
if($rsl = mysql_query($sql) != false){ // ALWAYS verify if your query's ran successfully.
if(mysql_num_rows($rsl) != 0){
echo 'Username already exists';
} else {
echo 'Username is available';
}
} else {
echo 'Query failed: ' . mysql_error();
}
} else {
echo $l > 25 ? 'Reached limit' : 'Needs to be longer';
}
} else {
echo "post['ajax-data'] not set<\br>";
print_r($_POST);
}
?>
Then there is your Javascript code that I have questions on. Yet you have a submit button but you want to check if its valid upon change?
$(document).ready(function(){
$("#user_form").submit(function(event){
event.preventDefault();
$.ajax({
url: "second.php",
type: "post",
data: $(this).serialize(),
success: function(result){
$(".php_responce_here").html(result);
}
});
});
});​

Ajax cannot load data from php to div

This is the ajax function
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'searchphp.php',
data: {suburb_id: $('#suburb_id').val()},
success: function(data)
{
$("#tableContent").html(data);
}
});
});
});
this is the php file need to receive data, it worked perfect.
<?php
//Check the form if submit by post
if (isset($_POST["searchBtn"])) {
$strInputSuburb = "";
$strInputSuburb = $_POST["suburb_id"];
//Check if the input box is empty or not
//if BOTH "Suburb" AND "Street" is empty, it will display the error message.
if(!empty($strInputSuburb))
{
//Connect to database server and table
include("connection.php");
#mysqli_select_db($conn, "db")
or die ("Database not available");
$querySql1 = "select * from Infringement
where suburb like '%".mysqli_real_escape_string($conn, $strInputSuburb)."%' and Street1 like '%".mysqli_real_escape_string($conn, $strInputStreet)."%'
order by Suburb, Fines DESC";
$result1 = mysqli_query($conn, $querySql1)
or die ("No information return...");
$count = mysqli_num_rows($result1);
$i=1;
if(!$count==0){
//do stuff, like echo
}
else {
//do stuff
}
//Release the SQL clause
mysqli_free_result($result1);
//Close the connection to database
mysqli_close($conn);
}
else {
//do stuff
}
}
?>
i want load to this div
<div id="tableContent"></div>
the css style is
#tableContent {
width:100%;
height:400px;
}
The input box is below
<input type="textbox" class="form-control" name="suburb" placeholder="Suburb" id="suburb_id" >
<input type="submit"class="btn" name="searchBtn" id='submit' value="Search" />
I used php to get data from form before. after using Ajax, I deleted "form" tag.
Thank you so much.
You're not sending the searchBtn parameter, which the PHP script is checking for. Add it to the data: option.
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'searchphp.php',
data: {
suburb_id: $('#suburb_id').val(),
searchBtn: 'Search'
},
success: function(data)
{
$("#tableContent").html(data);
}
});
});
});
Or remove that check from the PHP script, and test if (isset($_POST['suburb_id'])) instead.

Ajax not submitting $_Post

I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);

How to update database thruogh dropdown without page reload

Please look at this code first:
$(document).ready(function() {
$("#alternatecolor [type=button]").each(function() {
$(this).on('click', function() {
btnObj = $(this);
rowId = $(this).attr("rowId");
changeStatus = $(this).attr("changeStatus");
$.get("changeStatus.php?rowId="+rowId+"&changeStatus="+changeStatus,function(data,status){
if(changeStatus == 0){
str ="Unverify";
btnText = "Verify";
newStatus = 1;
}
else{
str ="Verify";
btnText = "Unverify";
newStatus = 0;
}
if(data == 'success'){
alert("Status updated successfully to "+str+".");
btnObj.val(btnText);
btnObj.attr("changeStatus",newStatus);
}
else{
alert("some error");
}
});
});
});
});
</script>
Here is my change status page:
$dbhost = 'xxxxxx';
$dbuser = 'xxxxxxx';
$dbpass = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('xxxxxxxx');
$sql ="update experiment set verification=".$_GET['changeStatus']." where row=".$_GET['rowId'];
$retval = mysql_query( $sql, $conn );
if(!($retval))
{
die('error');
}
else{
echo "success";
}
mysql_close($conn);
I was using a button in this code to query my database with values 0,1. If pressed once, database queried with 1, if pressed again, database queried with 0.
Now, I have to put a dropdown in place of button with 3 values to query database with: 0,1,2. If selected first value, database row to be updated with value 0 and so on.
How would I do that?
remove button and add select like this:
<select class="my-select">
<option value="0">update</option>
<option value="1">create</option>
<option value="2">delete</option>
</select>
you also need to add data-rowId attribute.
jquery:
$(document).ready(function() {
$(".my-select").change(function() {
btnObj = $(this);
rowId = $(this).attr("data-rowId");
changeStatus = $(this).val();
$.get("changeStatus.php?rowId="+rowId+"&changeStatus="+changeStatus,function(data,status){
if(data == 'success'){
alert("Status updated successfully to "+str+".");
}
else{
alert("some error");
}
});
});
});
update
create
delete
You can do using class name or ID. If it's id then do $("#id1").click(function () {... in below code.
Awlad has done using GET method, below is using POST method.
$(function () {
$(".my-select").click(function () {
var category = $(this).text();
//$('label').css('color', selText);
$.ajax({
url: "invite_db.php",
type: "POST",
data: {"category": category},
success: function(data) {
$(".articleContent").html(data);
//setInterval("messageDisable()", 5000);
}
});
});
});
I have used parameter name according to my code. Please you change it
Here is your HTML and Javascript code
<select onchange="getval(this);">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<script type="text/javascript">
function getval(sel) {
$.ajax({
type: "POST",
url: url, // url is page where you want to process this post request
data: 'val=' + sel.value,
});
}
</script>
On PHP side
<?php
// Your database connection code
$val = $_POST['val'];
mysql_query("UPDATE 'tablename' SET 'column name' = $val 'Your WHere caluse'")
?>

Categories

Resources