user784637
user784637

Reputation: 16102

How to execute a php header script from javascript?

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?

Upvotes: 0

Views: 229

Answers (4)

Manatok
Manatok

Reputation: 5706

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';
           }
     });    
});

Upvotes: 3

Vimalnath
Vimalnath

Reputation: 6463

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

Hope this works!

Upvotes: -1

Akhil Thayyil
Akhil Thayyil

Reputation: 9403

Try this ..

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

       });
    });

Upvotes: -1

Jon
Jon

Reputation: 437336

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.

Upvotes: 1

Related Questions