Ajax response not returning - php

I am having a table with data where I have an action button in last column to delete that particular row. I want to make the delete via ajax and without refreshing the page. I am using the following code but their is no response coming from the ajax page. Also the queries at the ajax page is not executing. Can I have some insight over what could be possibly wrong.
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var $tr = $(this).closest('tr');
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data: info,
success : function(response) {
if(response=='deletion success'){
$tr.find('td').fadeOut(1000,function(){ $tr.remove(); });
}
}
});
}
return false;
});
});
</script>
And at delete_entry.php
<?php
header('Content-Type: application/json');
session_start();
require("../config.php");
require("../Database.class.php");
require("../site.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$fnc=new site_functions($db);
$id = $_POST['id'];
$deleted_date = date("Y-m-d h:i:s");
$deleted_by = $_SESSION['session_admin_id'] ;
$nots = $db->idToField("tbl_ques","notes",$id);
if ($nots == "")
{
$date_string = "last deleted on|".$deleted_date."|" ;
}
else {
$date_string = $nots."last deleted on|".$deleted_date."|" ;
}
$fnc->update_is_not_deleted_for_Pearsonvue("tbl_ques",$id, "$deleted_date", $deleted_by);
$notes_data = array("notes"=>$date_string);
if($db->query_update("tbl_ques", $notes_data, "id=$id")){
http_response_code();
echo json_encode('deletion success');
}else{
http_response_code(204);
}
?>

Change your java script function as below
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data: info,
//changes from
success : function(response) {
if(response=='deletion success'){
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
}
});
//changes to
}
return false;
});
});
</script>
Also change you php file
<?php
header('Content-Type: application/json'); // Add this line its must
session_start();
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$id = $_POST['id'];
$deleted_date = date("Y-m-d h:i:s");
$deleted_by = $_SESSION['session_admin_id'] ;
$nots = $db->idToField("tbl_question","notes",$id);
if ($nots == "")
{
$date_string = "last deleted on|".$deleted_date."|" ;
}
else {
$date_string = $nots."last deleted on|".$deleted_date."|" ;
}
$fnc->update_is_not_deleted_for_Pearsonvue("tbl_question",$id, "$deleted_date", $deleted_by);
$notes_data = array("notes"=>$date_string);
//changes from
if($db->query_update("tbl_question", $notes_data, "id=$id")){
http_response_code();
echo json_encode('deletion success');
}else{
http_response_code(204);
}
//changes to
?>

Related

display data from database using ajax,mysql,php

Currently, I made script, which after onclick event,sending question to the database and showing data in console.log( from array ). This all works correctly, but.. I want to show data from array in the different position in my code. When I try to use DataType 'json' and then show some data, then it display in my console.log nothing. So, my question is: How to fix problem with displaying data? Is it a good idea as you see?
Below you see my current code:
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
//console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "text",
data: {id:id},
success: function(data){
console.log(data);
}
});
});
});
:
public function GetPlayer($id){
$id = $_GET['id'];
$query = "SELECT name,surname FROM zawodnik WHERE id='".$id."'";
$result = $this->db->query($query);
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()){
$this->PlayerInfo[] = $row;
}
return $this->PlayerInfo;
}else {
return false;
}
}
:
$info = array();
$id = $_GET['id'];
$vv = new AddService();
foreach($vv->GetPlayer($id) as $data){
$info[0] = $data['name'];
$info[1] = $data['surname'];
}
echo json_encode($info);
I think it would be better to change the line fetch_all in mysqli to rm -rf. That information in the DB is all obsolete, or completely not true.
Try this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class="profile" data-id="1">Click</button>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "json",
data: {id:id},
success: function(data){
console.log(data);
$.each(data, function(idx, item) {
console.log(item.surname);
});
}
});
});
});
</script>
</body>
</html>
PHP side:
<?php
class AddService {
public function GetPlayer($id) {
if (filter_var($id, FILTER_VALIDATE_INT) === false) {
return false;
}
$query = "SELECT name, surname FROM zawodnik WHERE id={$id}";
$result = $this->db->query($query);
if ($result->num_rows <= 0) {
return false;
}
// assumming you are using mysqli
// return json_encode($result->fetch_all(MYSQLI_ASSOC));
// or
WHILE ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return json_encode($data);
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$vv = new AddService();
// you don't need foreach loop to call the method
// otherwise, you are duplicating your results
echo $vv->GetPlayer($id);
}

Edit multiple values in ajax

I am trying to edit two columns using ajax and php.My code currently edits one values(name) in my table and saves it to my database.When i add the second variable (p) my ajax call it updates both columns p and y with the same value.How do i edit the third value and assign it a different value from y.I want the two different columns to have different values in my db(columns:name and capacity)
This code edits and updates two values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And this is what i tried to edit three values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var p = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y+"&capacity="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);
$(z).html(p);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And heres my php file(process.php)
<?php
include("connect.php");
if
($_GET['id'],$_GET['capacity'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$data' where id='$id'")){
echo "success";
}
else{
echo 'failed';
}
}
?>
And my table in index.php
<tbody>
<?php
$query = mysqli_query($con,"select * from mytable");
$i=0;
while($fetch = mysqli_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['name'].'</span></td>
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['capacity'].'</span></td>
</tr>';
}
?>
</tbody>
1) your just typo error : capacity=$data look this line and change it to capacity=$capacity :
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
2) And take look in If condition too .finally your code should be like this .
<?php
include("connect.php");
if($_GET['id'] && $_GET['capacity'] && $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
{
echo "success";
}
else
{
echo 'failed';
}
}
?>
You have error in your sql query. As you not passing correct parameters.
Please see below code.
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
// Check Sql
$query = "update mytable set name='$data',capacity='$capacity' where id='$id'";
if(mysqli_query($con,$query)){
echo "success";
} else{
echo 'failed';
}

Return a boolean from a PHP file to the AJAX one - Follow button

I'm creating a follow button, more or less like the twitter one.
You click the button, and you follow the user.
You click again, and you unfollow the user.
I have done this code
HTML
<div data-following="false" class='heart canal'><i class='fa fa-heart awesome'></i></div>
AJAX
$(document).ready(function() {
$(".heart.canal").click(function() {
if($(".heart").attr("data-following") == '0'){
$(".heart").attr('data-following', '1');
} else if($(".heart").attr("data-following") == '1'){
$(".heart").attr('data-following', '0');
}
var usuario = $(".left h4").attr("data-id");
var seguidor = $("#user_account_info .profile_ball").attr("data-id");
var seguir = $(".heart").attr("data-following");
$.ajax({
type: "POST",
url: "./include/php/follow.php",
data: { user: usuario, follower: seguidor, follow: seguir },
success: function(response) {
if(response == '0'){
$(".heart").addClass("like");
} else if(response == '1'){
$(".heart").removeClass("like");
}
}
});
return false;
});
});
PHP
<?php
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseña = "";
$conexion = new PDO($dsn, $usuario, $contraseña);
$resultado = null;
$sql = "";
$user = $_POST["user"];
$seguidor = $_POST["follower"];
$follow = $_POST["follow"];
if($follow == '0'){
$sql = "INSERT INTO seguidores(id_canal, id_seguidor) VALUES('$user', '$seguidor')";
} else if($follow == '1'){
$sql = "DELETE FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
}
if($conexion){ $resultado = $conexion->query($sql); }
return $follow;
?>
The problem is, everytime I click the button, I only insert data in the database. I mean, I only create follows.
When I click twice, it doesnt remove the follow.
Is there anyway to insert data when data-following = true and remove it when data-following = false ?
UPDATED
I have changed the boolean false and true for 2 strings, 0 and 1. But it doesn't work anyway.
There are numerous problems here. For one, like #Mark said, you need to understand that when sending ajax requests to PHP, you are sending strings. Also, in your JS, you are binding a click function to the .heart.canal, but then the function changes all elements with that class rather than the actual clicked element. Lastly, once you send the right information to PHP you need to print your results in order to see it in ajax.
Try the following:
JS:
$(document).ready(function () {
$(".heart.canal").click(function () {
var $heart = $(this);
if ($heart.data("following")) {
$heart.data("following", false)
} else {
$heart.data("following", true);
}
var usuario = $(".left").find("h4").data("id");
var seguidor = $("#user_account_info").find(".profile_ball").data("id");
$.ajax({
type: "POST",
url: "follow.php",
data: {user: usuario, follower: seguidor, follow: $heart.data("following")},
success: function (result) {
if (result) {
console.log("true");
} else {
console.log("false");
}
}
});
return false;
});
});
PHP:
$user = (int)$_POST["user"];
$seguidor = (int)$_POST["follower"];
$follow = ($_POST["follow"] === 'true') ? true : false;
if ($follow) {
// insert
} else {
// delete
}
print $follow;

submit ajax form with condition

hi i am working on an authentification page , so my code is the following
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
alert(result);
}
}});
});
});
i get the form , the login and password and i pass them to my php script .
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
if($msg == 0)
{
echo"false1";
}
else if($row[1] == crypt($password,$row[1]))
{
echo"true";
}
else
{
echo"false2";
}
?>
everything is goood , when i give the good email and password i get true otherwise i get false, that's not the problem , the problem is i am trying to redirect the user to another page called espace.php if the result is true so i've tried this .
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
form.submit(true);
}
else form.submit(false);
}});
});
});
now even if the login and password are not correct the form is submitted , how could i manage to do that i mean , if the informations are correct i go to another page , otherwise i stay in the same page.
use json to get result from authanication page
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
$result = array();
if($msg == 0)
{
$result['error'] = "Fail";
}
else if($row[1] == crypt($password,$row[1]))
{
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
?>
And in the ajax,, check what is the response.
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
form.submit();
}
}});
});
});

Reload a div only if there is new data

If I create a script like this, then it will reload the div every 2.5 seconds. I want a script that only displays if there is new data, if there is no new data it does not have to reload...
<script type="text/javascript">
function dispMsg() {
$("#displayMessage").load('load.php');
var newscrollHeight = $("#displayMessage").attr("scrollHeight") - 20;
$("#displayMessage").animate({ scrollTop: newscrollHeight }, 'normal');
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage"></div>
and here is the load.php:
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$id = $result['id'];
$from = $result['user_01'];
$to = $result['to_usr'];
$message = $result['message_01'];
$date = $result['date_send'];
echo "<span class='from'> $from </span>"
. "<span class='message'> $message </span> <br/>";
}
use the parameters and call back of $.load()
$.load(url, {param1:value, param2:value}, function(result){
if(result >5){
//do something
}
)
Example:
<?php
if($_REQUEST['action'] == 'check'){
if($_REQUEST['lastId'] < 5 ){
echo $_REQUEST['lastId']+1;
die;
}
}
if($_REQUEST['action'] == 'load'){
echo 'some conntent!';
die;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var lastId = 0;
function dispMsg() {
$.get('tmp.php', {action:'check', lastId: lastId}, function(responce){
if(responce !== 0){
alert(responce);
$('#displayMessage').load('tmp.php', {action:'load'});
}
});
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage">1</div>
You can send the last message id with each request. If the last message of your query is greater than the id sent, send the response. Otherwise send nothing.
function load_messages(){
var last = $('#messagewindow p:last').attr('id');
$.ajax({
url: base_url + "load.php",
type: "POST",
data: {
last: last
},
cache: false,
success: function(html){
//insert message
}
});
}
You can send the id as the id attribute in your HTML. Each message in the chat window is sent as a paragraph with some message id such as id="133".
Expanding on #Pé de Leão's solution, here's something more simple:
<?php
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$mysqli = new mysqli("host", "user", "pass");
if ($result = $mysqli->query($sql)) {
$msg = $result->fetch_assoc();
if (isset($_REQUEST['last']) && $msg['id'] != $_REQUEST['last']) {
echo "<span id='${msg['id']}' class='from'>${msg['user_01']}</span>";
}
}
And on the client side:
function dispMsg() {
var last = $('#displayMessages span.from').attr('id');
$.get(baseUrl + '/load.php', { last: last }, function(result) {
if (result) {
$('#displayMessages').html(result);
}
});
}
Note that this replaces everything in displayMessages.

Categories