ajax run mysql query and check whether mysql query was true or false? - php

I am using the following ajax script to run my MySQL query and then only want the jquery to fade out my div and fade in another if the query returned true otherwise if the query returned false don't do anything.
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "include/fade_to_do_list.php",
data: "theOption=" + $(this).attr("id"),
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("success") >-1 ){
setTimeout(
function() {
$("#to_do_list").fadeOut();
}, 3500
);
setTimeout(
function() {
$("#compliance_list").fadeIn();
}, 500
);
}
}
});
});
</script>
PHP/MYSQL:
<?php
session_start();
include 'config.php';
$query = "SELECT * FROM supplier_stats WHERE complete_count = > 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0) {
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
if($result2) {
$return['res'] = 'success';
} else {
}
}
echo json_encode($return);
?>
Please can someone show me where I am going wrong? I currently get no error and my jquery just doesnt execute. Thanks

mysql_query() always return you something. You need to count number of affected row.
Also problem is with equal to greater then operator it is used as >=
$query = "SELECT * FROM supplier_stats WHERE complete_count >= 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
$total=mysql_affected_rows();
if($total >0) {
$return['res'] = 'success';
} else {
}

Related

Datatable not refreshing on ajax inside each loop

Scenario :
I have a datatable which has checkbox on each row. When i try to select all checkbox and remove all selected data from datatable, it was not refreshing but the code works perfectly fine on the backend. But when i try to select all except 1 row (any of the row) it works fine...
phpaction :
$query = "
SELECT id ID, code Code, name Name, description Description FROM tablename WHERE active = 1 ORDER BY id ASC";
$res = mysqli_query($dbcon, $query);
if (mysqli_num_rows($res) > 0) {
$data = array();
$tbl = '';
while ($row = mysqli_fetch_assoc($res)) {
$data[] = $row;
}
echo json_encode($data);
} else {
echo json_encode('');
}
ajax:
$datatable.find('input[type="checkbox"]:checked').each(function() {
ID = $(this).attr("value").substr((($(this).attr("value")).length - 8) * -1);
remove(ID);
});
function remove(ID) {
requestAction = 'remove';
$.ajax({
url: 'phpaction.php',
method: 'post',
data: {
requestAction: requestAction,
ID: ID
},
success: function(data) {
list();
},
error: function(err) {
console.log(err);
}
});
}

Ajax cannot display the response from php

I know that this question is already answered a lot, but even the previous responses from php are working, this response cannot work and i cannot find the reason for this issue.
Although php was send the response succesfully, ajax cannot display without refreshing the page first.
Here is my jquery.ajax code in the file helpers.js:
function likeButton(commentId, userId) {
$.ajax({
url: "requests.php",
type: "POST",
data: {
like: "likeUp",
commentId: commentId,
userId: userId
},
success: function(response) {
$("#comment_body").append(response);
}
});
}
Here is my php code in requests.php:
if(isset($_POST['like'])) {
if($_POST['like'] == "likeUp") {
$commentId = $_POST['commentId'];
$userId = $_POST['userId'];
$sql = "SELECT gaming_comment_like FROM gaming_comments WHERE gaming_comment_id='$commentId'";
$result = mysqli_query($conn, $sql);
if($row = mysqli_fetch_assoc($result)) {
$gaming_comment_like = $row['gaming_comment_like'];
}
$gaming_comment_like = $gaming_comment_like + 1;
$sql_update = "UPDATE gaming_comments SET gaming_comment_like='$gaming_comment_like' WHERE gaming_comment_id='$commentId'";
$result_update = mysqli_query($conn, $sql_update);
exit();
}
}
here is the eventhandler that calling the likeButton function, which is in a php file:
<p><img src='like.png' class='like_button' onclick='likeButton(".$gaming_comment_id.", ".$user_id.");'>$gaming_comment_like</p>";

Getting Ajax reponse as null in php

I have a form in that I am trying to do inline editing and adding using AJAX call.
Firstly I am displaying data in HTML table. And then if enter data into text boxes and click on add button record adding displaying data in HTML table. After I click edit button data showing in the textboxes fine.
But I am getting the ajax response as null.
I couldn't figure it out.
This is my AJAX code PHP file:
$(function() {
$(".scrollingTable tbody a").click(function() {
//debugger;
var link = $(this).attr('href');
var arr = link.split('=');
var id = arr[1];
//alert(id);
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
cntid: id
},
success: function(datas) {
var data = $.parseJSON(datas);
$("#num").val(data.id);
$("#namegr").val(data.vndr_cntname);
$("#designation").val(data.designation);
$("#mobilegr").val(data.vndr_cntmobile);
$("#maildgr").val(data.vndr_cntmail);
}
});
});
});
$(function() {
$('.txtcbt a').click(function() {
debugger;
var cntname, designation, mobile, email, vndrid, id, cid;
cid = $("#num").val();
cntname = $("#namegr").val();
designation = $("#designation").val();
mobile = $("#mobilegr").val();
email = $("#maildgr").val();
vndrid = "<?php echo $selectid; ?>";
//alert(cid);
if (cntname == "" || designation == "" || mobile == "" || email == "") {
alert("fields should not be empty");
} else {
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
id: cid,
name: cntname,
dgnation: designation,
mobileno: mobile,
emailid: email,
vid: vndrid
},
success: function(html) {
var dat = $.parseJSON(html);
alert(html);
alert("it came to success");
$("#num").val("");
$('#namegr').val("");
$('#designation').val("");
$('#mobilegr').val("");
$('#maildgr').val("");
}
});
}
});
});
This is file AJAX is calling:
<?php
require('Assests/connection/connection.php');
error_reporting(0);
$vcntlist = "";
if (!empty($_POST['cntid'])) {
$id = $_POST['cntid'];
$result = mysqli_query($conn, "SELECT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,`vndr_id` FROM `vndr_cntdtls`where id=$id");
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_array($result);
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
if (!empty($_POST['name']) && !empty($_POST['dgnation']) &&
!empty($_POST['mobileno']) && !empty($_POST['emailid']) &&
!empty($_POST['vid'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$degination = $_POST['dgnation'];
$mobile = $_POST['mobileno'];
$email = $_POST['emailid'];
$vndrid = $_POST['vid'];
if (empty($_POST['id'])) {
$query = mysqli_query($conn, "INSERT INTO `vndr_cntdtls`(`vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`, `vndr_id`) VALUES ('$name','$degination','$mobile','$email',$vndrid)");
} else {
$update1 = mysqli_query($conn, "UPDATE `vndr_cntdtls` SET `vndr_cntname`='$name',`designation`='$degination',`vndr_cntmobile`='$mobile',`vndr_cntmail`='$email' WHERE id=$id") or die(mysqli_error($conn));
}
$result = mysqli_query($conn, "SELECT DISTINCT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,vc.vndr_id FROM `vndr_cntdtls` vc INNER JOIN vendors v ON vc.vndr_id=$vndrid") or die(mysqli_error($conn));
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
}
echo json_encode($row);
?>
There could be a lot of ways it is not working.
First:
You need to put a application/json in your php so it can be compatible with the browser you are using.
header('Content-Type: application/json');
echo json_encode($row);
Second:
Why are you doing a while loop and assigning it into an unused variable?
You can simplify it by doing:
$row = mysqli_fetch_array($result);
header('Content-Type: application/json');
echo json_encode($row);
Unless it is multiple rows then:
$rowcount = mysqli_num_rows($result);
$rows = array();
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($row);
Third
null values usually appears when a variable you are trying to use is not initialized. By having the error_reporting turned off it does not display the error.
error_reporting(true);
Fourth
Check also the logs for database error, I assume it has something to do with MySQL query not having to reach the $row initialization.
Fifth
I believe you need to have it fetched as associative array for it to be useful
$row = mysqli_fetch_assoc($result);

AJAX SET INTERVAL

I want to get the latest post_id in the table without refreshing it, but the problem is whenever a user inserts a value to the database, It echoes infinitely the last post_id. I want it to echo only once. But I still want to get the latest post_id from the table.
Here is my main php:
<div id = "this_div">
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id ASC LIMIT 20";
$execute_query = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($execute_query))
{
$get_this_id = $row['post_id'];
echo $get_this_id."<br>";
}
$_SESSION['get_this_id'] = $get_this_id;
?>
</div>
here is my jQuery ajax:
<script>
var refreshId = setInterval(function(){
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
$.ajax({
url: 'another_file.php',
data: {},
success: function(data)
{
if(compare_session != data)
{
$('#this_div').text($('#this_div').text()+data);
}
}
});
},400);
</script>
here is the php code of another_file.php
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id DESC LIMIT 1";
$execute_query = mysqli_query($con,$query);
if($row = mysqli_fetch_assoc($execute_query))
{
echo $get_this_id = $row['post_id'];
}
?>
You are not updating the compare_session variable , it holds always the initial value . So update it inside success callback function
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
var refreshId = setInterval(function () {
$.ajax({
url: 'another_file.php',
data: {},
success: function (data) {
if (compare_session != data) {
$('#this_div').text($('#this_div').text() + data);
}
compare_session = data;
}
});
}, 400);

Query in Jquery IF statement

I have a jquery save script like :
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Your file is save as : '+ naam);
window.location.replace("index.php?id=latest");
}
else
{
alert('Not saved');
}
I save a div in save.php which creates an new id in the database
What I want to achive is were
window.location.replace("index.php?id=latest");
id=latest must become (id=id from last saved file).
I tried
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
window.location.replace("index.php?id="+MBId);
and
var MBID =
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo $MBId ?>
window.location.replace("index.php?id="+MBId);
They both failed.
How can I run the query in the if(naam !=null) statement?
At first place you must fix your jQuery POST... You don't use POST respond which is wrong.. You should wait for it and then continue with other actions
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam }, function(responde){
if(responde.id)
window.location.replace("http://yoururl.com/index.php?id="+responde.id);
else
alert("No responde...");
}, "json");
}
else
{
alert('Not saved');
}
For better results I suggest you to use JSON data in that post/respond..
At your PHP code you have to set:
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo json_encode(array('id'=>$MBId));
exit();
?>
P.S. For window.location.replace please set your FULL url: "http://localhost/index.php?id=" OR atleast put slash at start of it "/index.php?id="
Solution
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Uw moodboard is opgeslagen als '+ naam);
window.location.replace("index.php?id=<?php $q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = ($data[0] + 1); echo "$MBId";?>");
}
This Works for me , i didnt need to make a jquery var i could echo the variable in php.
And i had to add 1 cause the sql query is loaded when the page is loaded.
So the file isn't saved yet when i get the highest id.

Categories