I want to return true when the number of rows in a table is more than one and show a div with jquery as shown in the jquery code .In addition return false when the number of rows is zero and hide a div as shown in the code below.The php code is executing and returning a correct value but the jquery code is neither showing or hiding a div.I need to show a div when the value returned is true and hide a div when the value returned is false;
**php code** php code for retrieving the number of rows from a table
<?php
require'php/connection.php';//a file for connecting to the database
$user_name=getUserField('user_name');//function for getting the name of the user in session
$query="select `order_id` from `inbox` where `buyer_name`='$user_name'";
$query_run=mysql_query($query);
$num_rows=mysql_num_rows($query_run);
if($num_rows >= 1) {
return true;
} else if($num_rows == 0) {
return false;
}
?>
jquery code Jquery code for either hiding or showing a div
$(document).ready(function() {
$.post('php/ManNotify.php',{},function(data){
if(true) {
$('#notify').show();
} else if(false) {
$('#notify').hide();
}
});
});
Do you realize your if statement reads,
if(true) ..
else if(false) ...
The hide will never execute. Is this your problem?
When using AJAX calls with PHP, you should echo the value rather than return it. Modify your PHP code like so:
<?php
require'php/connection.php';//a file for connecting to the database
$user_name=getUserField('user_name');//function for getting the name of the user in session
$query="select `order_id` from `inbox` where `buyer_name`='$user_name'";
$query_run=mysql_query($query);
$num_rows=mysql_num_rows($query_run);
if($num_rows >= 1){
echo json_encode(array("status" => true));
} else if($num_rows == 0) {
echo json_encode(array("status" => false));
}
exit;
?>
You'll also need to modify your JavaScript accordingly. Right now, if(true) will always execute on the return. Modify it like so:
// Shorthand for $(document).ready
$(function(){
$.post('php/ManNotify.php',{}, function(data) {
// JavaScript truthy/falsy will take care of the statement
if(data.status) {
$('#notify').show();
} else {
$('#notify').hide();
}
});
});
EDIT:
As #mplungjan points out in the comments below, the JavaScript could be simplified in the callback to be the following: $('#notify').toggle(data.status);. The resulting JavaScript would be:
// Shorthand for $(document).ready
$(function(){
$.post('php/ManNotify.php',{}, function(data) {
$('#notify').toggle(data.status);
});
});
Thanks to #mplungjan for the suggestion.
$(document).ready(function(){
$.post('php/ManNotify.php',{},function(data){
if(data == 'true'){
$('#notify').show();
}else if(data == 'false')
{
$('#notify').hide();
}
});
});
There are two problems with your code:
The server-side code. Returning boolean TRUE or FALSE this way will only render the page blank.
The jQuery code logic is wrong: if(true){ case will always be executed (because the value is, well, always true).
A very simple fix would be (untested):
if($num_rows >= 1){
echo 'true';
} else {
echo 'false';
}
Then, in the JS:
$.post('php/ManNotify.php', function(data){
if(data === 'true'){
$('#notify').show();
} else {
$('#notify').hide();
}
});
Note that this is not optimized.
$(document).ready(function(){
$.post('php/ManNotify.php',{},function(data){
if(data == "true"){
$('#notify').show();
}else if(data == "false")
{
$('#notify').hide();
}
});
});
Related
I need to compare two datetime objects but the ajax ain't working.
javascript
<script>
$(document).ready(function(){
$('.datepicker').change(function(){
var date=$(this).data('datepicker').getFormattedDate('yyyy-mm-dd');
$(this).attr('value',date);
});
$('#collectDate').change(function(){
var collectDate=$('#collectDate').val();
var expiryDate=$('#expiryDate').val();
$.post("index.php?ajaxController/fine",{collectDate:collectDate,expiryDate:expiryDate},
function(data){
if(data){
$('#fine').hide();
$('#collectFine').removeAttr('required');
}
else if(!data){
$('#fine').show();
$('#collectFine').attr('required');
}
});
});
$('#fine').hide();
});
</script>
Controller
<?php
class ajaxController extends CI_Controller{
public function fine() {
$data['collectDate']= $this->input->post('collectDate');
$data['expiryDate']= $this->input->post('expiryDate');
$this->load->view("backend/admin/fine",$data);
}
}
View
<?php
$collectDate=$collectDate;
$date= explode('/',$expiryDate);
$expiryDate1=new DateTime($date[2]."-".$date[0]."-".$date[1]);
$diff=$collectDate->diff($expiryDate);
if($diff>=0){
echo true;
}
else {
echo false;
}
I've also tried simple comparison operators but all in vain. It always executes the else part in success function.
It always returns false because you cannot really catch true/false in php code with ajax. What that code in your view does, is make some calculations, return true or false AND THEN RENDER AN HTML PAGE, an empty one in your case.
Calling that page with ajax, means you read the HTML, which if an empty page, means no data returned, so FALSE.
What you need to do is something like this:
In your view:
if($diff>=0){
echo 'true';
}
else {
echo 'false';
}
And in your jQuery:
$('#collectDate').change(function(){
var collectDate=$('#collectDate').val();
var expiryDate=$('#expiryDate').val();
$.post("index.php?ajaxController/fine",{collectDate:collectDate,expiryDate:expiryDate},
function(data){
if(data.indexOf('true') > -1){
$('#fine').hide();
$('#collectFine').removeAttr('required');
}
else if(data.indexOf('false') > -1){
$('#fine').show();
$('#collectFine').attr('required');
}
});
});
This should be fine.
The link:
<a class='dropdown' href='javascript:void(0);' onclick='mainLoginToggle();'>
mainLoginToggle():
function mainLoginToggle() {
$(document).mouseup(function (e) {
var container = $(".logindisplay");
if (container.has(e.target).length === 0) {
container.fadeOut(222);
}
});
if (document.getElementById('logindisplay').style.display == 'block') {
$(".logindisplay").fadeOut(222);
} else {
$(".logindisplay").fadeIn(222);
}
$.get("../include/removenotif.php");
return false;
}
removenotif.php:
<?php include("session.php"); $database->removeNotifications($session->username); ?>
removeNotification():
function removeNotifications($user) {
$q = "UPDATE notifications SET seen = '1' WHERE username = '$user'";
$result = mysql_query($q, $this->connection);
return true;
}
Basically, when the link is clicked it shows and hides the div, but also when it's clicked it's supposed to run the removeNotifications function, and not return any messages but successfully run the sql query. But it's not executing the query.
I've tested to see if the page is actually being called by changing the header information to try and get an error but nothing is happening. I'm not really sure where I'm going wrong here, any help would be appreciated. Thanks.
Why not use JQuery all the way?
Like this
Your link
<a class="dropdown" href="#">Click here</a>
Jquery
$(document).ready(function() {
$('.dropdown').live('click', function(){
var container = $(".logindisplay");
if (container.has(e.target).length === 0) {
container.fadeOut(222);
}
if (document.getElementById('logindisplay').style.display == 'block') {
$(".logindisplay").fadeOut(222);
} else {
$(".logindisplay").fadeIn(222);
}
$.get("../include/removenotif.php");
return false;
});
});
This way the PHP file is called.
Wezy
All i want is, a data will pass into this php file: check.php and this php file will pass data into that function when the page is ready. this is just an expirement.
ok I have this code:
$(document).ready(function() {
$.post("check.php", {
name: "log"
}, function(data) {
if (data === "yes") {
alert('has been login');
} else {
alert('has not login');
}
});
});
and i have this php code ("check.php") where the jquery post will pass the data into.
<? //check
$chk = $_POST['name'];
if (isset($chk === "log")) {
if (isset($_COOKIE['admin'])) {
if ($_COOKIE['admin'] === "login") {
echo "yes";
}
} else {
echo "no";
}
} else {
echo "no";
}
?>
but nothing happen, even i change the whole code in check.php into: "echo "yes";" theres nothing happen, i guess, its either there is no data receive or there is no data pass. Hope someone could help me into this simple and cute problem that im stuck with. thank you in advance
I think you missed a closing brace. This just works as expected:
$.post('check.php', { name: 'log' }, function(data) {
if (data === "yes")
{
alert ('has been login');
}
else
{
alert ('has not login');
}
});
Run this JSFiddle http://jsfiddle.net/S53k5/
and you will see the call passing by in Fiddler.
I would guess it's because you're using the header "name" and that is a reserved keyword.
I have a notification system that works with the following codes
jQuery:
$(document).ready(function(){$.get('/codes/php/nf.php', function(data) {
$('#check').html(data);});
});
setInterval(function(){$.get('/codes/php/nf.php', function(data) {
$('#check').html(data);});
}, 10000);
PHP:
//Database stuff would be here
$na = $num_rows; //Amount of notifications
if($na == "1"){
$nt="Notification";
} else {
$nt="Notifications";
}
if($na != "0"){
echo "<a href='#'>$na $nt</a>";
} else {
exit;
}
HTML: (It's a tipsy -- jQuery plugin -- tooltip)
title="<span id='check'>"
My only problem is when there is 0 notifications ($na = 0) a blank tooltip is displayed, and it looks really bad. So basically I can't have the 'title=' if I want to get rid of this problem, but I don't have any ideas. Anybody know I can fix this?
Ok, so I found out that I can't use this: title="" at all because even when there is no data at all, the tooltip is still being displayed.
try change
function(data) {
$('#check').html(data);
}
with this :
function(data) {
if (data != '') {
$('#check').html(data);
}
}
I have a rather confusing problem.
I have a php file (http://example.com/delete.php)
<?php
session_start();
$user_id = $_SESSION['user_id'];
$logged_in_user = $_SESSION['username'];
require_once('../classes/config.php');
require_once('../classes/post.php');
$post = new Post(NULL,$_POST['short']);
#print_r($post);
try {
if ($post->user_id == $user_id) {
$pdo = new PDOConfig();
$sql = "DELETE FROM posts WHERE id=:id";
$q = $pdo->prepare($sql);
$q->execute(array(':id'=>$post->id));
$pdo = NULL;
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
and I'm trying to get this jquery to post data to it, and thus delete the data.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This post? (" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("post Has Been Deleted!");
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
and when I do that, it returns "Post Has Been Deleted!" but does not delete the post.
Confused by that, I made a form to test the php.
<form action="http://example.com/delete.php" method="POST">
<input type="hidden" value="8" name="short"/>
<input type="submit" name="submit" value="submit"/>
</form>
which works beautifully. Very odd.
I have code almost identical for deleting of a comment, and that works great in the javascript.
Any ideas? Beats me.
Thanks in advance,
Will
EDIT:
this works... but doesn't follow the href at the end, which is the desired effect. Odd.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This Post? (http://lala.in/" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete/post.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("Post Has Been Deleted!");
******************************************
event.preventDefault();
return false;
******************************************
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
If your PHP script delete the post, it doesn't return anything.
My bad, it's not answering the real question, but still is a mistake ;)
Actually, it seems that PHP session and AJAX doesn't quite work well together sometimes.
It means that if ($post->user_id == $user_id) will never validate, hence the non-deleting problem.
2 ways to see this :
Log $user_id and see if it's not null
Try to send the $_SESSION['user_id'] with your ajax post and check with it. But not in production, for security reason.
1-
Your PHP should return something in every case (at least, when you're looking for a bug like your actual case).
<?php
[...]
try {
if ($post->user_id == $user_id) {
[...]
echo 'true';
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
2-
jQuery is nice to use for AJAX for many reasons. For example, it handles many browsers and make checks for you but moreover, you can handle success and error in the same .ajax() / .post() / .get() function \o/
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short'); // If that's where your data is... Fair enough.
if (confirm("Delete This Post? (http://lala.in/" + num + ")")) {
$.post("delete/post.php", {short: num}, // Relative is nice :D
function(data){
if (data == 'false') {
alert('Deleting Failed!');
}else{
alert("Post Has Been Deleted!");
// Your redirection here ?
}
});
}
});
3-
If you need to send data from a form to a script and then do a redirection, I won't recommand AJAX which is usually use not to leave the page !
Therefore, you should do what's in your comment, a form to a PHP script that will apparently delete something and then do a redirection.
In your code I don't see num defined anywhere...and invalid isn't set when you think it is, so you're not passing that 8 value back and you're getting the wrong message, either you need this:
$.post("http://example.com/delete.php", {short: $("input[name=short]").val()},
Or easier, just .serialize() the <form>, which works for any future input type elements as well:
$.post("http://example.com/delete.php", $("form").serialize(),
I'm not sure where your code is being called, if for example it was the <form> .submit() handler, it'd look like this:
$("form").submit(function() {
$.post("http://example.com/delete.php", $(this).serialize(), function(data){
if (data == 'false') {
alert('Deleting Failed!');
} else {
alert("Post Has Been Deleted!");
}
});
Note that you need to check inside the callback, since invalid won't be set to true until the server comes back with data the way you currently have it, because it's an asynchronous call.