Success message displaying on the wrong page - php

I am new to Ajax and I am trying CRUD operations using the same. I have an index.php page where I can insert and display data, also I have links to update and delete data over there.Create, Read, Update are working fine. Now the problem is that when I click the link to Delete, I am successfully sending the id to the delete_back.php and the value is getting deleted but the success message which should be printed on the index.php as I have a div named #delete_msg over there but somehow the success message is being printed on delete_back.php.
index.php
<div id="delete_msg"></div>
select_back.php
<?php
include("config.php");
$data=mysqli_query($con,"select * from student");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a href='update_front.php?id=$row[0]&nm=$row[1]&add=$row[2]&cont=$row[3]'> Update </a></td>";
echo "<td><a class='delete' href='delete_back.php?id=$row[0]'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
?>
delete_back.php
<?php
$id=$_GET['id'];
include("config.php");
$data=mysqli_query($con,"delete from student where id='$id'");
if($data=="true")
{
echo "Data Deleted";
}
else
{
echo "Delete Error";
}
?>
ajax file
$(".delete").click(function(event){
event.preventDefault();
$.ajax({
url:"delete_back.php",
dataType:"html",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
})
})

add data-id attribute to anchor tag:
echo "<td><a id='delete' data-id='".$row[0]."' href='#'>Delete</a></td>";
You can do in your ajax be like:
$("#delete").click(function(event){
var obj = $(this); // first store $(this) in obj
var id = $(this).data('id'); // get id of data using this
$.ajax({
url:"delete_back.php",
dataType:"html",
data: { id: id },
type: "Post",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
})
})
in your php file:
$id=$_POST['id'];

First of all, I really hope you don't have a loop which prints multiple anchors with same ID...
That said, according to your html, your JS should be like the followin, otherwise you will lose your id value:
$("#delete").click(function(event){
event.preventDefault();
var my_href = $(this).attr('href');
$.ajax({
url: my_href,
dataType:"html",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
});
return false;
});
But this isn't a really nice coding style.. I would suggest to use html5 data- attribute to store your id value
echo "<td><a id='delete' data-id='".$row[0]."' href='#'>Delete</a></td>";
You can also use javascript:; instead of # if you don't want your url to change..
And your JS should be like:
$("#delete").click(function(event){
// you can avoid preventing default behaviour because your anchor doesn't have any href value
var del_id= $(this).data('id');
$.ajax({
url: "delete_back.php",
dataType:"html",
data: {id: del_id} // use object for better reading
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
});
});
I also suggest you to check .done() construct LINK and deferred.done()

I believe that the delete link is coming from a loop containing other delete links too. If so, this is what you should do.
echo '<td><a class="lnk-delete" href="#" data-id="'.$row[0].'">Delete</a></td>'; //The delete links should have 1 class name
Then make your ajax call
$('.lnk-delete').click(function(e){
var id = $(this).data('id');
ajax({
url: 'delete_back.php'
data: {id: id},
type: 'POST',
success: function(data){
$('#delete_msg').html(data);
}
});
});
Get the id of the item you want to delete in php
$id = $_POST['id'];

<?php
//select_back.php
echo "<td><a id='delete' href='#'>Delete</a></td>";
?>
<input type="hidden" id="hidden_id" name="id" value="<?php echo $row[0]; ?>">
<script>
$("#delete").click(function(event){
event.preventDefault();
var hidden_id =$("#hidden_id").val();
$.ajax({
type:'GET',
url:"delete_back.php",
data:"id="+hidden_id,
success:function(data){
if(data.trim() == 'success')
{
$("#delete_msg").html("<div style='color:green;'>deleted successfully</div>");
}else{
//error
}
}
});
});
</script>
<?php
// delete_back.php
$id=$_GET['id'];
include("config.php");
$data=mysqli_query($con,"delete from student where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "Delete Error";
}
?>

Related

How to transmit php data in ajax form

I have a problem with transmitting php data in ajax function.
What I want is to send a html form, in which i have php value from a mysqli_fetch_array. The value is the number of the post, which is my primary key.
Being new to javascript, I don't really know how to do this.
Here is my onclick function code :
<script>
function foo () {
$.ajax({
url:"vote.php?no_post=<?php $post ['no_post'] ?>", //what I'd like to do
type: "POST", //request type
success:function(result)
{
alert(result);
}
});
}
</script>
In the php page, I have this fetch array, here we focus on button named "up" :
if(!isset($_POST['more']))
{
while($post = mysqli_fetch_array($res))
{
echo
'<p>'.
'<center>'.
'<img src="image/'.$post['image_post'].'">'.
'</center>'.
'<br/>'.
'<label>'.$post['desc_post'].'</label>'.
'<p>'.
'<a id="darkBlue" href="account.php?no_post='.$post['no_post'].'">'.'#'.$post['login'].'</a>'.
'<p>'.
'<label>'.$post['time'].'</label>'.
'<p>'.
'<label>'.$post['vote_post'].' points'.'</label>'.
'<footer>';
if (isset($_SESSION['login']))
{
echo '<button class="btn btn-success" name="up" id="up" onclick="foo()">+</button>'.
'&nbsp'.
'<button class="btn btn-danger" name="down" id="down">-</button>'.
'&nbsp'.
'Comment'.
'<hr>';
}
EDIT***
And finally my php page where the sql request is executed :
<?php
if (isset($_POST['up'])) // 2 buttons on the first html FORM
{
$req="UPDATE post SET vote_post=vote_post+1
WHERE no_post=".$_GET['no_post'].""; //picking up the value from my url
$res=mysqli_query($con,$req);
}
else if (isset($_POST['down']))
{
$req2="UPDATE post SET vote_post=vote_post-1
WHERE no_post=".$_GET['no_post'].""; //picking up the value from my URL
$res2=mysqli_query($con,$req2);
}
else
echo 'Error';
?>
Thanks for you help.
You have missed echo in below line.
url:"vote.php?no_post=<?php echo $post['no_post'] ?>", //what I'd like to do
EDIT
As you have used POST method, it should be passed in data like:
$.ajax({
url:"vote.php",
type: "POST", //request type,
data: {
postCount : <?php echo $post['no_post']; ?>
}
success:function(result)
{
alert(result);
}
});
You can try something like that :
<script>
function foo () {
$.ajax({
url:"vote.php",
type: "POST", //request type
data: {no_post: <?php echo '$post['no_post']'?>}
success:function(result)
{
alert(result);
}
});
}
</script>
It's better to use data : [...] instead of using parameters in url

How to pick multiple rows of values of the same id value from the database and display in ajax?

I have written code for button to send a value to php file using ajax as show below :
<script>
$(document).ready(function(){
$(".open-AddBookDialog").click(function(){
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax({
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result1){
var packagetype = package_type;
alert(packagetype);
}
});
});
});
</script>
This is the ajax code for the button which i have written. My button code is :
<a data-toggle="modal" id="custId" data-name="<?php echo $arr["package_name"]; ?>" data-id="<?php echo $arr["id"]; ?>" href="#myModal" class="open-AddBookDialog btn btn-submit" OnClick='change(this);'>Book / Enquiry / Pay</a>
When clicking this button in href, I want to send a id value to a php file using ajax.
data1.php
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
$arr = mysqli_fetch_array($query1);
echo $arr['package_type'];
echo $arr['package_price'];
mysqli_close($con);
?>
using the id value, I want to pick multiple rows of package type and package price from the database having the same id value.After picking the multiple rows of these values i want to send it to the main php file and display all the values of all the rows picked from the database.
Can anyone suggest how to do this ?
<script>
$(document).ready(function()
{
$(".open-AddBookDialog").click(function()
{
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax(
{
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result)
{
resultJson=jQuery.parseJSON(result);
$.each(resultJson.packageDetails, function(i, item) {
var packagetype = item.package_type;
var package_price = item.package_price;
alert("packagetype :- "+packagetype+" ----- package_price :-"+package_price);
});
}
});
});
});
</script>
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
//$arr = mysqli_fetch_array($query1);
while( $strPackageResult=mysqli_fetch_array($query1,MYSQLI_ASSOC) )
{ $ArrPackage[]=$strPackageResult; }
if( isset($strPackageResult) ){ unset($strPackageResult); }
mysqli_free_result($query1);
if( isset($query1) ){ unset($query1); }
$myResultPackageArray=array();
if( isset($ArrPackage) && is_array($ArrPackage) && count($ArrPackage)>0 ) {
$tempArray=array();
foreach( $ArrPackage as $tempPackage )
{
$tempArray['package_type']=$tempPackage['$tempPackage'];
$tempArray['package_price']=$tempPackage['package_price'];
$myResultPackageArray['packageDetails'][] =$tempArray;
}
}
mysqli_close($con);
echo json_encode($myResultPackageArray);
?>
There are some basic things you should know first then you can easily rectify your errors.
Debuging javascript
Prepared Statements
PHP Error Handling
This is not you have asked but as a programmer i will suggest you to go through it.
As going through your code
var packagetype = package_type;
package_type is undefined. If you are using chrome inspect element and check the console you will see the error.
Hope this will work.

Loop through submit buttons and post to MySQL w/ ajax

I currently have a form(s) that gets created based on the number of rows in the DB. Each row gets pulled in to its own form where data is editable. Each row also has it's own button.
$i = 0;
while($row = mysql_fetch_array( $result )) {
if ($row['stage']=='1'){ $i++;
<form method="post" name="form<?php echo $i;?>' id='form<?php echo $i;?>">
<input type="text" name="product<?php echo $i;?>" value="<?php echo $row['product'];?>" id="product<?php echo $i;?>" />
<input type='button' name='submit<?php echo $i;?>' value='NEXT'/>
</form>
JQUERY
$(".submit1").click(function(){
$.ajax({
type: "post",
url: "xx1.php",
data: $("#form1").serialize(),
success: function() {
alert("UPDATE SUCCESS");
location.reload();
},
error: function () {
alert("FAILED");
}
});
});
xx1.php
$ProductOne= strip_tags($_POST['product1']);
if ($StageOne == "1"){
SQL STATEMENT
}elseif ($StageOne == "2"){
SQL STATEMENT
}elseif ($StageOne == "3"){
I currently have xx.php for each row (xx1.php,xx2.php,xx3.php) and in my php file my $_POST['x'] matches the xx.php ($_POST['product1'], $_POST['product2'], $_POST['product3']
How do write something that says if submitx is clicked update that row where i = i (update product1 when submit1 is clicked, update product2 when submit2 is clicked)
You need to get button id (the one which got clicked) and call the respective file for the execution.
$("button").click(function() {
//extract the name of the button clicked
var name = $(this).attr('name');
//get the button id from name.
var buttonId = name.split('submit')[1];
$.ajax({
type: "post",
url: "xx.php",
data: $("#form" + buttonId + "").serialize(),
success: function() {
alert("UPDATE SUCCESS");
location.reload();
},
error: function () {
alert("FAILED");
}
});
});
data sent to xx.php has the id. So you may use this id to operate on xx.php.
$id = //get the id from form data sent from js
$Product = strip_tags($_POST["product{$id}"]);
.
.
//use id instead of number in further operations.

Unable to pass data to php using ajax

First i echo images for which i set ID with php function. Now im tyring to get the ID value with jQuery click function and pass it to another php function, but unfortunately i always get the undefined index error. Can the reason be in xampp config or something else? Becasuse the code seems to be "right".
jQuery
$(function postImgId() {
$('img').click(function() {
var imgId = $(this).attr('id');
$.post('functions.php', {postId:imgId},
function(data) {
$('#content').html(data);
console.log(imgId);
});
});
});
php
function showPlayer() {
$number ='';
$number = $_POST['postId'];
if(isset($_POST['postId'])) {
echo "<h2>";
echo $_POST['postId'];
echo "</h2>";
}
}
Try:
Put this in your click function:
var imgId = $(this).attr('id');
$.ajax({
type: "GET",
url: "functions.php",
data: 'playerId=' + imgId,
success: function(data){
$('#content').html(data);
}
});
now check with isset($_GET['playerId']) and so on in your php:
if(isset($_GET['playerId'])) {
echo "<h2>";
echo $_GET['playerId'];
echo "</h2>";
}
This playerId should not be something important in your database like the unique AI id.
Whole thing also works with POST see: http://api.jquery.com/jquery.post/

Call for another ajax from the result one ajax request got

I've header file in which I have search box where user can search for products, this works on ajax request & for getting the info I've livesearch.php file.
Now with the searched products, I want to add 'Add to Cart' button directly. So in fact for every search result there will be one button to add that product in cart. To achieve this, I need to add another ajax request for adding that product into cart.
But nothing's happening while I click on add button. Here's my code.
Header.php
<script type="text/javascript">
$(document).ready(function()
{
$(".searchproductbrand").keyup(function()
{
var kw = $(".searchproductbrand").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "livesearch.php",
data: "kw="+ kw,
success: function(option)
{
$("#livesearch").show();
$("#livesearch").html(option);
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
});
}
else
{
$("#livesearch").html("");
document.getElementById("livesearch").style.border="0px";
}
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function()
{
$(document).live('click', '.buynow', function()
{
var productid = $(this).attr('id');
var quantity = $('.quantity_'+productid).val();
var type= $('.type_'+productid).val();
$.ajax
({
type: "POST",
url: "db_addtocart.php",
data: {'quantity'=quantity, 'type'=type, 'productid'=productid},
success: function(option)
{
this.attr('value','Added');
}
});
return false;
});
});
</script>
<?php
<input type="text" id="text" class="searchproductbrand">
?>
livesearch.php
<?php
while(blah blah){
echo "<input type='text' id='quantity' class='quantity_".$row["productid"]."'>".
" <select name='type' class='type_".$row["productid"]."'>".
"<option value='Unit'>Unit</option>";
"</select>";
echo " <input type='button' class='button' id='".$row["productid"]."'
class='buynow' value='Buy Now'>";
}
?>
db_addtocart.php
This file gets the values of variables & insert into table, nothing sort of important.
What wrong am I doing? Any help will be appreciated.
Try updating your js to the code below. I used .delegate() instead of .live() as according to the manual it is better to use with jQuery 1.4.3+.
$(document).ready(function() {
$(".searchproductbrand").keyup(function(){
var kw = $(".searchproductbrand").val();
if(kw != ''){
$.ajax({
type: "POST",
url: "livesearch.php",
data: {kw:kw},
success: function(option){
$("#livesearch").show();
$("#livesearch").html(option);
$("#livesearch").css("border","1px solid #A5ACB2"); // used $('#...') instead of document.getElementById() AND .css() instead of style.border
}
});
}
else {
$("#livesearch").html("").css("border","0px"); // used $('#...') instead of document.getElementById() AND .css() instead of style.border
}
return false;
});
$(document).delegate('.buynow','click', function(){
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val(); // changed from .quantity_ to #quantity - requires change in php code
var type= $('#type_'+productid).val(); // changed from .type_ to #type - requires change in php code
$.ajax({
type: "POST",
url: "db_addtocart.php",
context: this, // added as 'this' below was out of scope. see the docs for more info
data: {quantity:quantity,
type:type,
productid:productid},
success: function(option){
this.value = 'Added'; // changed from this.attr('value','Added');
}
});
return false;
});
});
This will also require you to update the html created in livesearch.php to the following code. Mainly changing from class=... to id=...
<?php
while(blah blah){
echo "<input type='text' id='quantity_".$row["productid"]."' />";
echo " <select name='type' id='type_".$row["productid"]."'>".
"<option value='Unit'>Unit</option>".
"</select>";
echo " <input type='button' class='button buynow' id='".$row["productid"]."' value='Buy Now'>";
}
?>
Here is a working JSFiddle example - http://jsfiddle.net/X8n3d/
What's going on is that your $(".buynow").click is bound to the element which are in the dom on load of your page. Any button with .buynow added after that has no event.
You need to use jQuery's on() method so the click event works for all elements.
Juste replace $('.buynow').click(function(e){..}) with $(document).on('click', '.buynow', function(e){..}) and it should work.

Categories