jphp
jphp

Reputation: 13

Is there a way to check if a user is logged in using JQuery?

I want to be able to display a message if a user is not logged in if they try rating a user by clicking a rating. Is there a way to add it to my JQuery code below or can I pass it to my PHP script?

I'm using PHP

Here is the JQuery code.

$('#rate li a').click(function(){
    $.ajax({
        type: "GET",
        url: "http://localhost/update.php",
        data: "rating="+$(this).text()+"&do=rate",
        cache: false,
        async: false,
        success: function(result) {
            // remove #ratelinks element to prevent another rate
            $("#rate").remove();
            // get rating after click
            getRating();
            getRatingAvg();
            getRatingText2();
            getRatingText();
        },
        error: function(result) {
            alert("some error occured, please try again later");
        }
    });

Upvotes: 0

Views: 2183

Answers (5)

Therichpost
Therichpost

Reputation: 1815

In Wordpress you can easily check with below code:

 if(jQuery('body').hasClass('logged-in')) {
 // add your jquery code
  }

Upvotes: 0

Kapil Kaisare
Kapil Kaisare

Reputation: 61

Use your update.php script to send back a codified response that includes an acknowledgement of whether the user is logged in; I am assuming the script echoes some value which is then received as the result variable in your jquery snippet.

if(result.loggedin == "1"){ //Assuming your output is a JSON object

}else{

}

Upvotes: 0

Reigel Gallarde
Reigel Gallarde

Reputation: 65284

just check it if one is login in your update.php script. If not login, echo something like "error".

then in your success handler,

    success: function(result) {
        if (!$.trim(result)==='error') {
           // remove #ratelinks element to prevent another rate
           $("#rate").remove();
           // get rating after click
           getRating();
           getRatingAvg();
           getRatingText2();
           getRatingText();
        } else {
           // not login, do something...
           alert('login first please...');
        }
    },

Upvotes: 1

dst
dst

Reputation: 1786

jQuery alone cannot test reliably if the user is logged in, but your request to PHP could send an answer if theuser was logged in or not. This answer can be checked and then display an error (or not).

Upvotes: 0

ZeissS
ZeissS

Reputation: 12135

Send something back to jQuery as the result and check it, before you perform your other steps.

Upvotes: 0

Related Questions