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);
}
}
Related
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();
}
});
});
Trying to learn how to do an autocomplete. I have the following in my html file (the code pasting function won't work so I have an image:
Between the head tags I have the following function:
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("autocomplete_script.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
I want to send the value of the checked radio button to autocomplete_script.php so I can do an if else within the php. I can't find any examples that are helping me, I though this would be an easy one. Can anyone help?
form.serialize() function gets all the data from the form, then you send it to the autocomplete_script.php, your lookup script looks something like this.
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.ajax({
url:'autocomplete_script.php',
type:'POST',
data:$("form").serialize(),
success:function(data)
{
//SUCCESS do your thing, response as data
}
});
}
} // lookup
Hope It Helps
This is how I post a new comment:
if (guest.val() != '' && comment.val() != '')
{
$.post("events.php?action=send", $("#form").serialize() , function(data)
{
$("#processing").html('');
if ($(data).html() == 'Hello fuckign world!')
{
$("#comments").html(data);
}
else
{
$("#comments").html(data);
$("#guest_name").val('');
$("#text").val('');
submit.fadeIn("slow");
}
});
}
else
{
$("#processing").html('');
$(".error").fadeIn("slow");
$(".error").html('Please fill up the fields!');
$(".error").click(function() {
$(".error").fadeOut("slow");
});
submit.fadeIn("slow");
}
});
loadComments();
});
function loadComments()
{
$.post("events.php?action=reload", { reload : 'true' } , function(callback)
{
$(".comments").html('');
$(".comments").html(callback);
});
}
Before that, of course I have document ready, and on click function.
Now, at the end I put this:
loadComments();
Which is:
function loadComments()
{
$.post("events.php?action=reload", { reload : 'true' } , function(callback)
{
$(".comments").html(callback);
});
}
So after the jQuery finishes it's action, it will send a post again to load all results, and updatethe div that holds the data.
But for some reason , after submiting, it doesn't reload the results. I have to do F5 to reload the results..
Question:
What have I done wrong? how do I fix it? How do I reload the results using jquery/ajax?
That's how I fetch the results:
if (isset($_POST) && isset($_GET['action']) && $_GET['action'] == 'reload')
{
$select = $CONNECT_TO_DATABASE->query("SELECT * FROM comments LIMIT 10");
while($row = $select->fetch( PDO::FETCH_ASSOC )) {
echo
'
Name: '.$row['client_name'].'<br />
Message: '.$row['client_message'].' <br />
Likes: '.$row['client_likes'].' <br /> <br /> <hr></hr>
';
}
}
Fixed it, I had to put loadComments() function inside the click() function.
So when you're performing the post comment, you're inside a click() function. therefore it wouldn't do anything outside of it.
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 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.