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.
Related
I am making an ajax call in a file called level1_1.php that posts to validate1_1.php (attached below). However, what happens is that the user gets redirected to validate1_1.php which simply prints to the screen the string (either "CORRECT", "INCORRECT", or "NOLIVES") that I want to be passed into the callback function that makes up the third parameter of my $.post call. How do I return back to level1_1.php from validate1_1.php??
level1_1.php:
session_start();
<h5>Type answer here: </h5>
<form>
<textarea rows="10" cols="50" name="userinput"></textarea>
<span> <?php echo $msg;?></span>
<br>
<input id="submit" type="submit" name="Submit">
</form>
<script>
$("#submit").click(function(){
$.post("validate1_1.php",
{
userinput: $("#userinput").val;
},
function(data){
if (data == "CORRECT")
{
alert("Good job! Get ready for the next level!");
// take user to next level
window.location.replace("game.php");
}
else if (data == "INCORRECT")
{
alert("Sorry, that is incorrect. You have lost a life.");
}
else
{
// redirect user to game over screen
window.location.replace("gameover.php");
}
});
});
</script>
validate1_1.php:
<?php
session_start();
$msg = "";
$userinput = preg_replace('/\s+/', '', $_POST["userinput"]);
// if incorrect, lose life
if (strcasecmp($userinput, $_SESSION["ptext"]) != 0)
{
$_SESSION["lives"]--;
$msg = "INCORRECT";
// if no more lives, game over!
if ($_SESSION["lives"] == 0)
{
$msg = "NOLIVES";
}
}
// otherwise, move on to next level
else
{
$msg = "CORRECT";
}
echo $msg;
?>
change the below line
userinput: $("#userinput").val;
to
userinput: $("#userinput").val();
Here are some fixes. If you still have problems, use your browser's debugging tools to help.
$("#submit").click(function(e){
// 1. prevent your submit button from submitting the form
e.preventDefault();
$.post("validate1_1.php",
{
// 2. you're using 'name' attribute not 'id' attribute
// 3. val() not val
userinput: $("[name=userinput]").val();
},
function(data){
if (data == "CORRECT")
{
alert("Good job! Get ready for the next level!");
// take user to next level
window.location.replace("game.php");
}
else if (data == "INCORRECT")
{
alert("Sorry, that is incorrect. You have lost a life.");
}
else
{
// redirect user to game over screen
window.location.replace("gameover.php");
}
});
});
What I want to do
When writing in the text field, I want the <div class="result"> to be filled with what PHP is echoing.
But it doesn't work!
Jquery
$(document).ready(function() {
var search = $("#search");
if (search.val() !== '') {
search.keyup(function() {
$.post("index.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
});
}
});
php
if (isset($_POST['search'])) {
echo 'hello';
}
html
<input type="text" name="search" id="search"/>
<br />
<div class="result"></div>
Problem
When filling the input, nothing happens, and it meant to POST the entered data on keyup (When entering a new character/or deleting.
What is stopping it from working? I am new to jQuery .
Thanks.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
This is wrong.
if (search.val() !== '') {
The above line should be,
if (search.val() != '') {
EDIT:
Then wrap the if condition inside the keyup function.
$(document).ready(function() {
var search = $("#search");
search.keyup(function() {
if (search.val() != '') {
$.post("getInputs.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
}
});
});
When I run into situations like this, I just start breaking the problem in half to see where its failing. Here are a couple things I would try.
First, in your jQuery, add some output to the console:
if (search.val() !== '') {
console.log("I am not empty so I should go to index.php");
search.keyup(function() {
$.post("index.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
});
}
else
{
console.log("search val was empty");
}
Of course you could always check the browsers network profiler to see if it made a POST to that resource. This will tell you if the problem is in your search.val test.
Then, if you want to debug the PHP side, you could remove the isset test and just always return "hello". That will tell you if its an issue with your POST variables or checks.
Finally, you could output the data result to be sure something is coming back at all. This will remove any issues with $(".result").html() being the problem:
$.post("index.php", { search : search.val()}, function(data) {
console.log(data);
$(".result").html(data);
});
If none of these work, maybe you could just switch around the way you bind to keyup in the first place:
$(document).ready(function() {
$("#search").keyup(function() {
if ($(this).val() !== '') {
$.post("index.php", { search : $(this).val()}, function(data) {
$(".result").html(data);
});
});
}
});
$(document).ready(function() {
var search = $("#search");
});
This fire only at document ready but not on keyup, means in var $("#search").val() will be blank.
Change your code to capture inpute value on every key-up stroke.
$(document).ready(function() {
search.keyup(function() {
var value = $("#search").val();
if(value!="")
{
$.post("index.php", { search : value}, function(data) {
$(".result").html(data);
});
}
});
});
Your logic is incorrect. You are only setting the keyup event handler if your #search has text in it. Unfortunately when that script runs on document ready, there is NO value in #search so your keyup handler never gets set, which is why it never fires.
I rewrote some of your logic and was able to get it to work. One being the way your checking to ensure you have a value. Instead of string comparing I am checking the length. Also, instead of binding the event to the field, I bind the event on the document and target the field. Try it:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<input type="text" name="search" id="search"/>
<br />
<div class="result"></div>
<script>
$(document).ready(function() {
$(document).on('keyup', 'input#search', function() {
if($(this).val().length > 0) {
$.post('index.php', {"search":$(this).val()}, function(data) {
$('div.result').html(data);
});
}
});
});
</script>
// when the html is loaded
$(document).ready(function() {
// find an element with the id 'search'
var search = $("#search");
// if this element's value is NOT an empty string -- oh look, it is!
if (search.val() !== '') {
// well, going to skip all this here then
search.keyup(function() { // don't care
$.post("index.php", { search : search.val()}, function(data) { // don't care
$(".result").html(data); // don't care
});
});
}
// YAAAAY! All done!
});
Actually nothing is wrong in your code. I have tried your code itself. Only issue was that you have called keyup function conditionally. Your Javascript code should be like below:
$(document).ready(function() {
var search = $("#search");
search.keyup(function() {
if (search.val() != '') {
$.post("index.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
}
});
});
Here, condition should be inside the keyup function.
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
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.