views:

46

answers:

3
$(function() {
      $(".follow").click(function(){
        var element = $(this);
        var I = element.attr("id");
        var info = 'id=' + I;

        $.ajax({
            type: "POST",
            url: "listen.php",
            data: info,
            success: function(){}
            });

        $("#follow"+I).hide();  ///showing the remove button after the data has been entered
        $("#remove"+I).show();
        return false;

      });
});

the php file listen.php

<?php session_start();
include_once ('includes/connect.php');

$id = $_POST['id'];
$follower = $_SESSION['user_id'];

 $registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')");
?>

what i want to do is when i click the follow button, i wanna check if the data has been enetered into the database, before showing the remove button!!!(basically checking on the background!

A: 

Put the code you want to execute inside your 'success' callback function.

 $.ajax({
   type: "POST",
   url: "listen.php",
   data: info,
   success: function(){
       $("#follow"+I).hide();  
       $("#remove"+I).show();
   }
 });
John Strickler
A: 

do it like this:

listen.php

<?php session_start();
include_once ('includes/connect.php');

$id = $_POST['id'];
$follower = $_SESSION['user_id'];

 if($registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')")):
echo "true";
else:
echo "false";
endif;
?>

pass parameter in success function, example "msg". whatever was echo'ed in listen.php will be in the msg variable now

success: function(msg){}
if(msg == "true")
{
//do something
}
else
{
//show error message
}
            });
krike
A: 

mysql_query will return TRUE or FALSE. You can echo that from the PHP script, and have the ajax call read it.

listen.php:

<?php session_start();
include_once ('includes/connect.php');

$id = $_POST['id'];
$follower = $_SESSION['user_id'];

 $registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')");

echo json_encode(array('response'=>$registerlistener));
?>

In your JavaScript:

$.ajax({
type: "POST",
url: "listen.php",
data: info,
dataType: 'json',
success: function(data){
    if(data.response){
        // mysql_query returned TRUE
        $("#follow"+I).hide();
        $("#remove"+I).show();
    }
    else{
        // FALSE
    }
}
});

If you want, you can use the $.post shorthand:

$.post('listen.php', info, function(data){
    if(data.response){
        // mysql_query returned TRUE
        $("#follow"+I).hide();
        $("#remove"+I).show();
    }
    else{
        // FALSE
    }
}, 'json');
Rocket
same like me but cleaner :)
krike