Deletinq record from database using ajax - javascript

I have problem with deleting records from database, using ajax and jquery. If i click to button nothing happens. there is my css:
<button class='delete_p' id_p='<?php echo $post_id; ?>'>x</button>"
<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script src="delete_post.js"></script>
and there is ajax that i'm using:
$(document).ready(function(){
$('.delete_p').click(function(){
var del_id = $(this).attr('id_p');
$.ajax({
type:'POST',
url:'delete_post.php',
data:'delete_id='+del_id,
});
});
});
and there is delete_post.php that i'm using:
<?php
include 'esas/core/database/connect.php';
$id = $_POST['delete_id'];
$query = "DELETE FROM `status` WHERE `id` = '$id'";
?>

data shouldn't be a string but a JavaScript object:
$.ajax({
type: 'POST',
url: 'delete_post.php',
data: {
delete_id: del_id
}
});

Related

How to extract/split part of the data AJAX Success returning

I have this PHP code to select data from a database:
<?php
include './database_connect.php';
$ppid=$_POST['selectPatientID'];
$query="SELECT * FROM patient WHERE p_Id='$ppid'";
$result= mysqli_query($conn, $query);
while($row= mysqli_fetch_array($result)){
echo ($row['p_fname']);
echo ' ';
echo ($row['p_lname']);
}
?>
But I need to get the p_fname and p_lname values separately. Is there anything I could do to achieve this?
This is my jQuery:
<script>
$(document).ready(function () {
$('#selectPatientID').on('change', function (event) {
event.preventDefault();
// alert("Hi");
$.ajax({
url: "UDPatient.php",
type: 'POST',
data: {selectPatientID: $('#selectPatientID').val()},
dataType: 'html',
success: function (result) {
$('#patientName').val(result); //in here, how can I get the p_fname and p_lname separetely and put them in two different input fields?
}
});
});
});
</script>
You should try something along the lines of
<?php
include './database_connect.php';
$ppid=$_POST['selectPatientID'];
$query="SELECT * FROM patient WHERE p_Id='$ppid'";
$result= mysqli_query($conn, $query);
$row= mysqli_fetch_array($result);
echo json_encode($row);
?>
You add the query results into an array $row, which you json_encode() and echo as the result
<script>
$(document).ready(function () {
$('#selectPatientID').on('change', function (event) {
event.preventDefault();
$.ajax({
url: "UDPatient.php",
type: 'POST',
data: {selectPatientID: $('#selectPatientID').val()},
dataType: 'html',
success: function (result) {
var jsonResult = JSON.parse(result);
var p_fname = jsonResult.p_fname;
var p_lname = jsonResult.p_lname;
// whatever else
}
});
});
});
</script>
The json result can be parsed ( or the dataType set as'json' alternatively').
you have to json_encode
$row = mysqli_fetch_array($result)){
header('Content-Type: application/json');// header for json encode response
echo json_encode($row);
exit;
Your jQuery ajax code will be:
$.ajax({
url: "UDPatient.php",
type: 'POST',
data: {selectPatientID: $('#selectPatientID').val()},
dataType: 'json',// to receive data into json format
success: function (result) {
alert(result.p_fname);
alert(result. p_lname);
}
});

Setting a session variable in PHP using AJAX

After a user clicks a div this javascript function runs:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": "<?php echo $rows['id']?>"},
success:function(data){
window.location.href = 'index.php';
}
});
});
I want to pass in an ID associated with the div the user clicks into my ajax.php file where this code runs:
<?php
session_start();
//connect to db here
$_SESSION['id'] = $_POST['id'];
?>
However this is not working. To expand further what I did to pass get the rows['id'] variable is run this SQL code:
$sql_select = "SELECT id FROM ids WHERE id = '$id'";
$results_select = $conn->query($sql_select);
I then outputted a bunch of divs with id's corresponding to them:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test'></div>";
}
?>
Does anyone know how I can accomplish this?
Use data attributes:
Try:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div data-id='".$rows['id']."' class = 'test'></div>";
}
?>
js:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": $(this).attr('data-id')},//fetch the data attribute
success:function(data){
window.location.href = 'index.php';
}
});
});
Please check your JS code for data: {"id": "<?php echo $rows['id']?>"}. This line may not be able to pass your actual value so store it into div with id attribute and get it by jQuery and pass it.
JS:
$('.test').click(function(e)
{
dataValue = $(this).attr('id');//Get user clicked div id attribute value...
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": dataValue},
success:function(data){
window.location.href = 'index.php';
}
});
});
PHP:
With above JS code you need to make some change for PHP code as well:
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test' id='". $select_rows['id'] ."'></div>";
}
Please confirm this code by print_r($_POST); on AJAX post handler page. This will print the POST data requested by AJAX code.
Let me know if there is any concern regarding this.

JS Toggle Class

I am stuck on this. I have an ajax function posting to php. The post function is working fine. I just want css to toggle on and off with each click while posting with each click.
When I click the '.fav-btn' button the first time I want 'fav-h' to be added to the class for styling. Also post to the php script.
When I click the '.fav-btn' button the second time I want 'fav-h' to be removed and button returns to original style. Also post again to the php script.
I have tried various things including the .removeclass. My code is below, I am not sure how to get the fav-h class style to be removed on the second click.
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').click(function(){
$(this).addClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
}
});
});
});
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn fav-h').click(function(){
$('.fav-btn fav-h').removeClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
}
});
});
});
Use $.toggleClass() to just have one block of code:
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').click(function(){
$(this).toggleClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){}
});
});
});
PS: your code was not working because you used $('.fav-btn fav-h'):
<div class="fav-btn">
<fav-h></fav-h> <!-- This is what this selector leads to -->
</div>
instead of the correct selector $('.fav-btn.fav-h'):
<div class="fav-btn fav-h"></div> <!-- Found the right one! -->
It looks like it is the same ajax call either way. You can probably just bind to the button once. Also, you might want to only update the class if the post was successful.
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').on('click', function(){
var $t = $(this);
$t.addClass('fav-saving');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
$t.toggleClass('fav-h');
},
complete: function(){
$t.removeClass('fav-saving');
}
});
});
});

Facing on Make Like Unlike Button in php , mysql using ajax calling

I m creating like and unlike button for my website , at my local server i used seprate file it it working fine but when i install at my website then it is not working properly.
I m Fetching some information using this code from url bar
<?php
error_reporting (0);
include "includes/session.php";
include 'database/db.php';
extract($_REQUEST);
if(isset($_GET["i"]))
{
$pid=($_GET['p']);
$lid=($_GET['i']);
}
?>
<?php
$likquery = mysql_query("select * from likes where userid=$id and postid=$lid");
if(mysql_num_rows($likquery)==1){
?>
<a class="unlike" id="<?php echo $lid ?>">UnLike</a> <span class="like_update" id="<?php echo $lid ?>"></span>
<?php }else{?>
<a class="like" id="<?php echo $lid ?>">Like</a>
<?php
}?>
AFTER this I use script
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('body').on('click','.like',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$('body').on('click','.unlike',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
And I m not getting any response but when i use
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(".like").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$(".unlike").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
only once it is changing the value
Ok, the second version works only once, because at the beginning, the event is on the button, then you re-render the button by changing it's class and text, so the events get unbinded.
Same is for the 1st version. Jquery says: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().... If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
So re-bind the events after changing the button.
I suggest something like this:
function bindEvents() {
$('.like').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
//rebind events here
bindEvents();
}
});
$('.unlike').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
//rebind events here
bindEvents();
}
});
}
$(document).ready(function(){
bindEvents();
});
Also notice that in var postData = 'postid='+postId+'&uid=<?php echo $id ?>'; code, the php part won't be treated as php. It will be just a string. So replace that part with the following, assuming that the code is located inside a php file:
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;

Cant make live ajax search work

I'm new to web development sorry but i just don't get problem
I just created this and its not working. please help i don't know whats the problem. i'm not getting any results.
but if i go to search.php it displays all names.
HTML
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<input type="text" onKeyup="getName(this.value)"/><br>
<div id="result"></div>
<script type="text/javascript">
function getName(value){
$.post("search.php", {partialName:value}, function(data){
$("#result").html(data);
});
}
</script>
php(search.php)
<?php
require 'includes/connection.php';
$partialName = $_POST['partialName'];
$query = "SELECT Name FROM Members WHERE Name LIKE '%$partialName%'";
$names = mysqli_query($dbc, $query);
while($namesArray = mysqli_fetch_array($names)){
echo "<div>".$namesArray['Name']."</div>";
}
?>
HTML:
<input type="text" id="search"/><br>
JS:
$("#search").on("keyup", function()
{
var value = $(this).val();
$.ajax({
url: "search.php",
type: "POST",
data: "partialName="+value,
success: function(data)
{
$("#result").html(data);
}
});
});
EDIT: Just as a note, it might be worth escaping the input into your MySQL query:
$partialName = mysqli_real_escape_string( $_POST['partialName'] );
<input type="text" id="search" /><br>
<div id="result"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#search').keyup(function(){
var name = $('#search').val();
var datastring = "partialName="+name;
$.ajax({
url: "search.php",
type: "POST",
data: datastring,
success: function(data)
{
$("#result").html(data);
}
});
});
});
</script>
<?php
require 'includes/connection.php';
$partialName = $_POST['partialName'];
$query = "SELECT Name FROM Members WHERE Name LIKE '%".$partialName."%' ";
$names = mysqli_query($dbc, $query);
while($namesArray = mysqli_fetch_array($names)){
echo "<div>".$namesArray['Name']."</div>";
}
?>

Categories