0

I have the following script validation.php

<?php
if(!isset($_SESSION['userId'])){
    session_destroy();
    header('Location: home.php');
    exit;    
}
?>

I would like to execute this script every time someone clicks a button in the #main-display

$("#main-display").on('click', 'button', function (event){
    //some code in here
});

How would I go about doing this?

3
  • $("#main-display").on('click', 'button', function (event){ jQuery.ajax('your.domain.tld/path/validation.php');}); - that's all. Commented Mar 19, 2012 at 11:10
  • 2
    You will also need to remove header('Location: home.php'); and instead put similar to echo "redirect";... in the js you will have Akhil Thayyil's answer replacing alert("response is "+data); with if(data=="redirect"){ window.location.href="home.php"; } Commented Mar 19, 2012 at 11:12
  • 1
    Thanks ricky, you hit the nail on the head, I'll try this out now. Commented Mar 19, 2012 at 11:15

4 Answers 4

3

You cant do a redirect from within a ajax request directly since it will only redirect the response page to home.php and not the current main DOM window.

You are going to have to modify it to something like this in the php:

   if(!isset($_SESSION['userId'])){
       session_destroy();
       $response['status'] = 'false';
   }
   else {
       $response['status'] = 'true';
   }
   echo json_encode($response);

And then on the javascript

$("#main-display").on('click', 'button', function (event){
     $.getJSON('/path/to/loginStatus.php', {}, function(response) {
          if(response.status == 'false') {
               location.href = 'home.php';
           }
     });    
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Manatok, you need to specify the datatype as json, otherwise it response.status is undefined
ah yes, I have made the change.
1

To start from the simplest, $.get('validation.php') is enough to get your script to run, but to do something useful with it you 'll need to provide more context. For the most generic "do-everything" method with bazillions of options, see $.ajax; everything else is a subset of this¹.

¹ This is not strictly true, but there are only a couple of minor exceptions that you shouldn't care about at this point.

Comments

-1

Try this ..

  $("#main-display").on('click', 'button', function (event){
       $.get("validate.php",function(data){
    alert("response is "+data);

       });
    });

Comments

-1
$('#main-display').click(function(){
 $.get('validate.php');
});

Hope this works!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.