delete row with ajax function and php - php

i have a table with mysql Data,i add a trash button and i want remove each row when trash button is clicked with ajax function,
this is my html:
<table border="1">
<?php
$sql ="SELECT * FROM music";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_object($result)){
echo '<tr><td>'.$row->file_name.'</td><td>'.$row->composer.'</td><td>'.$row->lyric.'</td><td>'.$row->music_thumb.'</td><td>'.'
<a href="#" id="'.$row->msuic_id.'" class="trash" >
جذف کردن
</a>
'.'</td></tr>';
}
?>
</table>
and my ajax function here:
$(function(){
$('.trash').click(function(){
var del_id= $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type:'POST',
url:'delete.php',
data:del_id,
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
})
});
and also my "delete.php" page here:
<?php
include('../db_inc.php');
$music_number = "POST['del_id']";
echo '$music_number';
$qry = "DELETE FROM music WHERE msuic_id ='$music_number'";
$result=mysql_query($qry);
?>
i think my problem is ajax function;
thanks

try this
$.ajax({
type:'POST',
url:'delete.php',
data:{del_id:del_id},
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
})
and also change
$music_number = "POST['del_id']";
to
$music_number = $_POST['del_id'];

In addition to the above answers, you should delegate your on click handler to prevent unnecessary duplication
$(document).on('click', '.trash', function() { ... });

Your ajax code should be this:
$(function(){
$(document).on('click','.trash',function(){
var del_id= $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type:'POST',
url:'delete.php',
data:{'del_id':del_id},
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
});
});
});
And PHP code should be:
<?php
include('../db_inc.php');
$music_number = $_POST['del_id'];
//echo $music_number;
$stmt = $db->prepare("DELETE FROM music WHERE msuic_id=?");
$stmt->execute([$music_number]);
echo "YES";

Try this:
$music_number = POST['del_id']; in delete.php
write ajax function like:
$.ajax({
type:'POST',
url:'delete.php',
data:del_id,
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
});
Thanks

Here are the things that you need to correct
In "delete.php" file
$music_number = "POST['del_id']";
// to
$music_number = $_POST['del_id'];
Also, in the success callback of ajax, you are checking for "YES" in response which is not sent anywhere in this file.
Change to your ajax request
data: {'del_id':del_id},
Hope this helps.

send you data as object and not just value
...
type:'POST',
url:'delete.php',
data:{'del_id':del_id}, //<----here
....
and take it as POST in delete.php
$music_number = $_POST['del_id'];
updated
add this to your delete.php
<?php
include('../db_inc.php');
$music_number = $_POST['del_id'];
$qry = "DELETE FROM music WHERE msuic_id ='$music_number'";
$result=mysql_query($qry);
if($result) {
echo "Yes";
} else {
echo "No";
}
?>

$.ajax({
type:'POST',
url:'delete.php',
data:{del_id:del_id},
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
})

Related

Return JSON from PHP to ajax on button click

I have a page with list of buttons, when each button is clicked, it's value is captured and ajax call in made. PHP does DB updates on ajax call. I want to return data to ajax call. The data is obtained from DB. But I'm unable to point out what's the error in below code.
Here is PHP code:
if (isset($_GET['val']))
{
$chapter_id=$_GET['val'];
$sql= "SELECT file_name,edit_link,name,email FROM `chapter_list` where chapter_id='$chapter_id'";
$result = mysql_query($sql,$rst);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
}
$update=mysql_query("UPDATE `chapter_list` SET `status` = '$update_status' WHERE `chapter_list`.`chapter_id` = '$chapter_id';");
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
}
Here is the AJAX request
$(document).ready(function(){
$('.btn').click(function(){
var clickBtnValue = $(this).val();
$.ajax ({
url: '',
data: { val : clickBtnValue},
dataType:'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I'm not getting the alert!
Try like this.
Maybe response data is null.check your php code(query lines).
Here My php code is :
if (isset($_GET['val'])) {
$vol_name = 'dummy_name';
$vol_email = 'dummy_email';
$vol_link = 'dummy link';
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
exit;
}
My javascriptcode is :
<input type="text" class="btn" value="test" />
<script type="text/javascript">
if('addEventListener' in document){
document.addEventListener("DOMContentLoaded", function(e){
//dom loaded
$(document).on("click",".btn",function(e){
e.preventDefault()
var e_val = $(this).val();
console.log('my value is :' + e_val);
if(e_val){
$.ajax({
type: "get",
dataType: 'json',
url: 'here your url or slash',
data: { // request e_val
val : e_val,
}
}).done(function(xhr) {
// console.log(xhr);
if(xhr.name){
alert('response data is '+ xhr.name);
}
})
}
})
},false)
}
</script>
try this..
while($row = mysql_fetch_assoc($result))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
$ret[$vol_name]= array(
'email'=>$vol_email,
'link'=>$vol_link
);
}
then use in the return statement..
echo json_encode($ret);
You can send parameters in HTML
<button class="btn" atribute_id="21543">Button</button>
$(document).ready(function() {
$('.btn').click(function() {
var Value_of_Btn= $(this).attr("atribute_id"); <-------
$.ajax({
url: '',
data: {
val: clickBtnValue
},
dataType: 'JSON',
success: function(res) {
alert(res.name);
}
});
});
});

Ajax not being called by select

Hi I have a select box that when it is changed I want the value in a database to be updated via Ajax. Using the console I can see that my saveedit2.php file is not being called.
Select Box
<form><select id="workingpattern">
<?php
if(isset($workingpatterns) && !empty($workingpatterns)){
foreach($workingpatterns as $k4=>$v4) {
?>
<option value="<?php echo $workingpatterns[$k4]["workingpatternid"]; ?>">
<?php echo $workingpatterns[$k4]["text"]; ?></option>
<?php }}?>
</select></form>
Ajax:
<script>
$(document).ready(function(){
$('#workingpattern').change(function(){
var e = document.getElementById("workingpattern");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "saveedit2.php",
type: "post",
data: value,
success: function(data) {
console.log(data);
}});
});
</script>
SaveEdit2.php
<?php
require_once("connect_db.php");
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
?>
There are a few issues that I see. First, I would use 'this' to get the element and use jQuery to get the value since you are using it already. Secondly, you need a name for the value in the data set:
$('#workingpattern').change(function(){
var value = $(this).val();
$.ajax({
url: "saveedit2.php",
type: "post",
data: 'value='+value,
success: function(data) {
console.log(data);
}
});
});
Try
Ajax
$('#workingpattern').change(function(){
var value = $("#workingpattern").val();
$.ajax({
dataType: "json",
url: "./saveedit2.php",
data: {'value':value},
success: function(data){
if(data['result']=="ok")
alert("Done");
else
alert("Error");
}
});
SaveEdit2.php
<?php
require_once("connect_db.php");
$ajax_result = "error";
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
if($result)
$ajax_result = "ok";
echo json_encode(array('result'=>$ajax_result));
?>

Fetching data from database using ajax and php

Below filmdetails.php file i want to call on href click, how i can incorporate the same using ajax for mobile app. i mean when i click on link filmdetails.php?id=12 then below code will fetch the 12 id having data associated with it such as name and year of the film
I want to process this using ajax. please guide
<?php
include('connection.php');
$filmId = $_GET['filmId'];
$sql ="SELECT * FROM films where filmId ='$filmId'";
mysqli_query("SET NAMES utf8");
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result))
{
$id = $row['filmId'];
$name = $row['filmName'];
$year = $row['filmYear'];
echo "$name, $year";
}
mysql_free_result($result);
mysqli_close($conn);
?>
suppose your a tag has id named getcountry, than use
$(document).ready(function() {
$('#getcountry').click(function() {
$.ajax({
method: "POST",
url: "filmdetails.php",
data: { filmId: <?php echo $_GET['filmId']; ?> }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
I think This trick will be work.
<a href="filmdetails.php?foo_id=' . $film_id . '" class="clickMe">
<span id="results"></span>
<script type="text/javascript">
$('a.clickMe').click(function(e){
// Stop default click action in browser
e.preventDefault();
// Make ajax call
$.ajax($(e.target).attr("href"), {
cache:false,
success:function(data){
$("#results").html(data);
}
});
})
</script>
Send the filmId via your AJAX request.
$.ajax({
method: "POST",
url: "filmdetails.php",
data: { filmId: <?php echo $_GET['filmId']; ?> }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
You will see your data in an alert. You can put this data in document using jQuery's .html() method.

getting data from PHP file with json is failing

I can't get each data from PHP file, i'm always having AJAX failure, i tried many things, and looked for some pages for this problem but i can't find any solution, this is where i came last.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="someclass"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
e.preventDefault();
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM table WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$jsondata1 = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
echo json_encode($jsondata1);
}
mysqli_close($con);
I think there is no need to share HTML file, but if you want i can share with you.
Thank You!
You are overriding the array value in the loop and echo $jsondata1, so you are sending many different arrays with the echo inside the loop, try this code:
$jsondata1 = array();
while($row = mysqli_fetch_array($result)) {
$jsondata1[] = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
}
echo json_encode($jsondata1);
e.preventDefault(); is a problem. e is not defined and if it was the default action would have already occurred by the time the success function was called. Try
$('a[class="someclass"]').click(function(e){
e.preventDefault();
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
You need to encode the complete response.
when you echo each encoded it will not work.
Do something like
$jsonArray = array();
while(){
array_push($jsonArray, array($row['data1'], $row['data2']);
}
echo json_encode($jsonArray);
You're calling json_encode multiple times when what you need to be doing is assigning those intermediate variables to an array and encode that array using json encode for the return.
PHP:
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM table WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
$jsondata1 = [];
while($row = mysqli_fetch_array($result)) {
$jsondata1[] = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
}
mysqli_close($con);
die(json_encode($jsondata1));
JavaScript:
$(document).ready(function () {
var doc = $(document);
doc.on('click', 'a.someclass', function(e){
e.preventDefault();
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});

connecting ajax and php not work

what is the problem of this code?
it is menu and page change by ajax with out refreshing the page, but its not working
it is my ajax code
<script>
$(document).ready(function() {
$('.news').click(function give(id){
$('#main-unit').text('Please Wait...');
var place= id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
statusCode:{
success: function(data){
$('#main-unit').html(data);
}
}
});
});
});
</script>
this is my html tags
<ul>
<li><a class="news" onclick=\"give('news')\" href="#">news</a></li>
</ul>
and php code
mysql_connect("localhost", "root", "")
or die(mysql_error());
mysql_select_db("basi")
or die(mysql_error());
if($_POST['where']=='news'){
$result = mysql_query("SELECT * FROM contents WHERE type = 0");
while ($row = mysql_fetch_array($result)){
$title = $row['title'];
$text = $row['text'];
echo"
<div class='title'><span>$title</span></div>
<div class='content'>
$text
</div>
";
}
}
the information read from DB but dont return to html file.
The problem is with your JavaScript. You're waiting for document ready and (incorrectly) binding a click event listener that isn't being used! Try:
<a class="news" onclick="give('news')" href="#">news</a>
with the JavaScript:
<script>
function give(id) {
$('#main-unit').text('Please Wait...');
var place = id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
statusCode:{
success: function(data){
$('#main-unit').html(data);
}
}
});
}
</script>
A better solution would be to separate HTML from JavaScript - remove the onclick attribute from your menu link, and use pure jQuery to select it and bind an event that calls give() when it is clicked:
$(document).ready(function() {
$('.news').click(function(e) {
give('news');
});
});
FTFY
<script>
$(document).ready(function() {
$('.news').click(function give(id){
$('#main-unit').text('Please Wait...');
var place= id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
//I believe your mistake was here
success: function(data){
$('#main-unit').html(data);
}
});
});
});
</script>

Categories