adam
adam

Reputation: 63

jquery - how to create condition in success function

I want to create jquery ajax success function based resp from logout.php. If users not sign in,It redirect bring them to login page.,but it's not working as I'm expected,no event occur when user is logged or not.So, what is wrong with my ajax function?



logout.php

<?php
    if( !$user->is_logged ) {
        echo 'true';
    }else{
        echo 'false';
    }
?>

jquery function in index.html

$(function(){
  $.ajax({
    type: 'GET',
    url: "logout.php", 
    success: function(resp){
      if(resp =='true'){
        document.location = '../login_test.html';
      }
      if(resp=='false'){
         alert('U are logged');
        }           
    }
  });
});

Upvotes: 0

Views: 433

Answers (1)

Legendary
Legendary

Reputation: 2242

Change some errors and made it to better view:

PHP:

<?php
  header('Content-Type: application/json');
  if( !$user->is_logged ) {
        echo json_encode(array('status' => 'ok'));
  }else{
        echo json_encode(array('status' => 'bad'));
  }
?>

Javascript:

$(function(){
  $.ajax({
    type: 'GET',
    url: "logout.php", 
    success: function(resp){
      var state = JSON.parse(resp).status
      if(state == 'ok'){
        document.location.href = '/login_test.html';
      }
      else{
         alert('U are logged');
      }           
    }
  });
});

If you have no alert, and have no redirect - you have not .success callback, and problem one level above your condition. In that case show us your errors from js-dev-console from browser.

Upvotes: 1

Related Questions