Delete record with ajax via id - php

Having trouble deleting a record from mysql databse using ajax/jquery. Issue I am having is that it does not delete from the database but does delete from the list. What am I doing wrong here?
Here is my code:
jQuery(document).ready(function(){
$(".deleteitem").click(function(){
var parent = $(this).closest('li');
var id = parent.attr('id');
$.ajax({
type: "POST",
data: "id=" +id,
URL: "delete.php",
success: function(msg){
$('#'+id).remove();
}
});
});
});
My php file delete.php:
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$id = $_POST['id'];
if (isset($id)) {
$query = "DELETE FROM img_slider WHERE id = '$id'";
mysqli_query($query) or die('Error, insert query failed');
}
The HTML markup:
<li id='".$row['id']."'>
<a href='#' class='deleteitem'><img src='../img/delete.png'></a>
</li>

Firstly test to make sure calling the delete file with a valid id works. The javascript below should work fine.
<script type="text/javascript">
<!--
$(function() {
$('.deleteitem').click(function(e) {
e.preventDefault();
var id = $(this).parent('li').attr('id');
$.get('delete.php',{ id: id}).done(function(data) {
if(data=='Error, insert query failed') {
// dont delete from list
alert('Failed to delete '+id);
} else {
//delete from list
$('#'+id).remove();
alert('Deleted '+id);
}
});
});
});
//-->
</script>
EDIT: updated the script to assist parent-id handling.
Are you able to say where the error is coming from? Most modern browsers should offer you some insight into what line, or what section the error is occurring on.
The script above should replace all your javascript.

Related

Ajax and PHP not updating database

This ajax code gets called, I tested it, but the database does not get updated.
I think the code is small enough not to need any further explanation. When something from the class pdb gets clicked, it saves its source to the database.
$(function(){
$('.pdb').on('click',function(){
var sou = $(this).attr('src');
var iddo = $(this).attr('id');
var data = 'id='+iddo+'&value='+sou+'&turno='+(bia)?true:false;
$.ajax({
data: data,
type: "post",
url: "database.php",
success: function(data){
alert("Prova: " + data);
}
});
});
});
database.php
<?php
mysql_connect("localhost","pierostesting","");
mysql_select_db("my_pierostesting");
$id=$_POST['id'];
$value =$_POST['value'];
$turno=$_POST['turno'];
if(true){
$sql="UPDATE board SET $id=$value, turno=$turno WHERE partita=0";
$result=mysql_query($sql);
if($result){
echo "Nailed it";
}
}else{
}
?>
remove
var data = 'id='+iddo+'&value='+sou+'&turno='+bia;
and debug ajax calls use either console or firebug extension
replace:
var data = 'id='+iddo+'&value='+sou+'&turno='+(bia)?true:false;
with
data = { 'id':iddo,'value':sou,'turno':(bia)?true:false}
Needed to change the PHPto this:
$sql="UPDATE board SET $id='$value', turno=$turno WHERE partita=0";
Simply change $value with '$value', bloody ''. Thank you all guys.

Multiple Ajax requests Colliding

I'm building a webshop for a project at university. I have a search bar in header, navigation bar on the left. In both cases I send data with Ajax (from search bar a keyword, from navs a category and subcategory). Ajax response is a PHP script that prints products based on category and subcategory or keyword. At the end of it it prints pagination links and select element for number of products per page. If I submit a keyword or click on a nav, it prints out results fine, but if I then change the page or a number on select element (another Ajax request) , the results default because category/subcategory or keyword are not being sent anymore. This is the code for search bar request:
$("#searchButton").click(function(){
$("#searchBar").blur();
var keyword=$("#searchBar").val();
$.ajax({
type:"GET",
url:"print.php",
data: { keyword:keyword }
}).done(function (data){
$('#content').html(data);
return false;
});
});
and this is the code for pagination:
$(document).on("change", "#paginationSelect", function(){
var productsPerPage=$("#paginationSelect").val();
$.ajax({
type:"GET",
url:"print.php",
data: { productsPerPage:productsPerPage }
}).done(function (data){
$('#content').html(data);
return false;
});
});
I'm wondering what's the best way to save the data sent by last Ajax request so that I can send it again while changing pagination stuff. Should I change the PHP file or Ajax requests and what's the best way to do it?
Edit:
This is the PHP file:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
mysql_connect("localhost", "root", "") or die("Couldn't connect to database.");
mysql_select_db("webshop") or die("Couldn't select a database.");
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
if(isset($_GET["category"]) & isset($_GET["subcategory"])){
$category=$_GET["category"];
$subcategory=$_GET["subcategory"];
$query="SELECT * from proizvod where kategorija='".$category."' and podkategorija='".$subcategory."'";
}
else if(isset($_GET["keyword"])){
$keyword=$_GET["keyword"];
$query="SELECT * from proizvod where ime like '%".$keyword."%'";
}
else{
$query="SELECT * from proizvod";
}
$result=mysql_query($query);
$numProducts=mysql_num_rows($result);
if(isset($_GET["productsPerPage"]))$productsPerPage=$_GET["productsPerPage"];
else if($numProducts>=10) $productsPerPage=10;
else $productsPerPage=$numProducts;
if(isset($_GET["pageNum"]))$pageNum=$_GET["pageNum"];
else $pageNum=1;
if(isset($keyword)) print "<div id=\"keywordMessage\" class=\"col-lg-12\">Traženi pojam: ".$keyword."</div>";
if(mysql_num_rows($result)==0) print "<div class=\"col-lg-12\">Nema rezultata</div>";
for($i=0;$i<($pageNum-1)*$productsPerPage;$i++){
$row=mysql_fetch_array($result, MYSQL_ASSOC);
}
for($i=($pageNum-1)*$productsPerPage;$i<$pageNum*$productsPerPage;$i++){
$row=mysql_fetch_array($result, MYSQL_ASSOC);
print("<div class=\"col-lg-6\">
<table class=\"article\">
<tr><td colspan=\"2\"><img src=\"images/".$row["id"].".jpg\" class=\"imgArticle\"/></td></tr>
<tr><td colspan=\"2\"><b>".$row['ime']."</b></td></tr>
<tr><td>Kategorija: </td><td>".$row['kategorija']."</td></tr>
<tr><td>Opis: </td><td>".$row['opis']."</td></tr>
<tr><td>Cijena: </td><td>".$row['cijena']." kn</td></tr>
</table>
</div>");
}
print("<div class=\"col-lg-12\" id=\"paginationControl\">
<span class=\"col-lg-4\">
Prikazano: ".(($pageNum-1)*$productsPerPage+1)."-".$pageNum*$productsPerPage."/".$numProducts."
</span>
<span class=\"col-lg-4\" id=\"pageNumbers\">");
if($productsPerPage!=0){
for($i=1;$i<=ceil($numProducts/$productsPerPage);$i++){
if($i==$pageNum) print($i." &nbsp ");
else print("<a class=\"pageNumControl\" href=\"#\">".$i."</a>");
}
}
print("</span>
<span class=\"col-lg-4\">Proizvoda po stranici:
<select id=\"paginationSelect\">
<option value=\"10\" "); if($productsPerPage==10){ print("selected");} print(">10</option>
<option value=\"20\" "); if($productsPerPage==20){ print("selected");} print(">20</option>
<option value=\"30\" "); if($productsPerPage==30){ print("selected");} print(">30</option>
<option value=\"50\" "); if($productsPerPage==50){ print("selected");} print(">50</option>
</select>
</span>
</div>");
mysql_free_result($result);
?>
You could use jQuery .Data(). But please note, if you refresh the entire page, the .data() information is lost.
So, without have more code this is the best example I could come up with. I am storing the search information in the #searchBar's data, then retrieving it on pagination change.
$("#searchButton").click(function() {
var $sb = $("#searchBar"),
keyword = $sb.val();
$sb.data({
prevKeyword: keyword
}).blur();
$.ajax({
type: "GET",
url: "print.php",
data: {
keyword: keyword
}
}).done(function(rtnData) {
$('#content').html(rtnData);
return false;
});
});
$(document).on("change", "#paginationSelect", function() {
var productsPerPage = $("#paginationSelect").val(),
previousKeyword = $("#searchBar").data('prevKeyword');
// Do something with the keyword
console.log(previousKeyword);
$.ajax({
type: "GET",
url: "print.php",
data: {
keyword: previousKeyword,
productsPerPage: productsPerPage
}
}).done(function(rtnData) {
$('#content').html(rtnData);
return false;
});
});

Show DIV with AJAX in PHP After Saving Data to Mysql

I Have a problem here. I try to show up the information box using DIV after successfully save the data to mysql.
Here my short code.
// Mysql insertion process
if($result){?>
<script type="text/javascript">
$(function() {
$.ajax({
$('#info').fadeIn(1000).delay(5000).fadeOut(1000)
$('#infomsg').html('Success.')
});
}
</script>
<?php }
How can DIV appear? I tried but nothing comes up. Any help? Thank you
a basic jQuery ajax request:
$(function() {
$.ajax({
url: "the url you want to send your request to",
success: function() {
//something you want to do upon success
}
});
}
lets say you have a session of ID and you want to retrieve it in your database.
here is: info.php
<input type="hidden" name="id"><input>
<input type="submit" onclick="showResult(id)" value="Click to Show Result"></input>
function showResult(id){
$j.ajax(
method:"POST",
url:"example.php",
data: {userid:id},
sucess: function(success){
$('#infomsg').html(Success)
});
}
<div id= "infomsg"></div>
example.php
$id = $_POST['userid']; ///////from the data:{userid :id}
//////////config of your db
$sql = mysql_query("select * from users where id = $id");
foreach ($sql as $sq){
echo $sq['id']."<br>";
}
the "infomsg" will get the result from the function success and put it in the div.

Updating Database from Javascript by calling PHP script

Ive been trying to get this for age
I am building a website which has an activity wall. I have the whole thing working except the like and unlike buttons. I have them currently just showing a text box I like or I don't like
<a href='#' onclick='like()'>Like</a>
or
<a href='#' onclick='unlike()'>Unlike</a>
Now these call these scripts
<script>
function like()
{
alert("I like");
document.getElementById("p1").innerHTML="<a href='#' onclick='unlike();'>Unlike</a> | 1 Life<hr/>";
}
function unlike()
{
alert("Dont like anymore");
document.getElementById("p1").innerHTML="<a href='#' onclick='like();'>Like</a> | 0 Lifes<hr/>";
}
</script>
I have a php script that connects to the database and adds or removes the like which I know works. I don't need to return anything to the javascript but how do I call that php script giving the postID and username??
Ok so using this I have modified it a little. But it still doesnt work :S
==LikeUnlink.php==
<?php
include 'phpScripts/OpenConnection.php';
$mode = $_GET['mode'];
$username = $_GET['username'];
$postID = $_GET['LikeID'];
echo $username."<br/>";
echo $mode."<br/>";
echo $postID."<br/>";
if($mode == 0)
{
$query = "INSERT INTO tbl1Ups (Username, ActivityID) VALUES ('$username', $postID)";
}
else
{
$query = "DELETE FROM `tbl1Ups` WHERE Username='$username' AND ActivityID=$postID";
}
$result = mysql_query($query) or die(mysql_error());
==MembersHome.php==
<script type="text/javascript">
function process(LikeId, Username, currentLikes, likeUnlike)
{
//your validation code
$.ajax(
{
type: 'GET',
url: LikeUnlike.php, //file where like unlike status change in database
data:{like:LikeId, username:Username, mode:likeUnlike},
success: function(data)
{
alert('It Works');
}
} );
}
</script>
==Like link==
<a href='Javascript:void(0)' onclick='process(".$row['ID'].", \"".$username."\", ".$likes.", 0);'>$linkText</a>
try this
<script type="text/javascript">
function process(LikeId) {
//your validation code
$.ajax( {
type: 'POST',
url: LikeUnlike.php, //file where like unlike status change in database
data:{like:LikeId},
success: function(data) {
//code you want to do after successfull process
}
} );
}
</script>
make changes in html
<a href='Javascript:void(0)' onclick='process(1)'>Like</a>
<a href='Javascript:void(0)' onclick='process(0)'>Unlike</a>

Jquery not connecting to .php

I am having some trouble with my jquery. I am not sure if it is connecting to doc.php but I am not getting anything inserted into my database.
I have an insert command in doc.php which I know is working.
I'm trying to create a way to update prices in a database, from doc.php, that searches out items one at a time.
The doc.php is searching by var, then updating in the same page.
The foreach loop function then, takes the var one by one, sends them to the doc.php page that then searches by var and updates into the database.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die (mysql_error());
$sql = "SELECT var FROM table";
$query = mysql_query($sql) or die (mysql_error());
while ($result = mysql_fetch_array($query)) {
$variable = array($result['var']);
foreach ($variable as $variable1) {
?>
<script src="jquery-1.7.2.min.js" type="text/javascript">
$(function() {
var valueToSend = '<?php echo $variable1; ?>';
$.ajax({
url: "doc.php",
dataType: "json",
type: "POST",
data: { Variable: valueToSend },
success: function (m) {
alert(m);
},
error: function (e) {
alert("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
}
}
?>
First of all, what do you want to do with this code? If you want to read & write to db using php, ajax call is unnecessary. If you want to practice ajax & php you need to read some howto because your code is somewhere strange ;). This is nice collection of tutorials for jQuery and some for PHP read some and practice.

Categories