简体   繁体   中英

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?

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

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 .

Try this ..

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

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

Hope this works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM