开发者

jQuery to post to php file

I have an index.html file which I want to run some jQuery when it is loaded. Essentially, I want to check to see if a user is already logged in based on some session variables.

So index.html will contain some jQuery which uses $(document).ready(function(){ })开发者_开发技巧;

In this function I want to just fire autheticate.php which checks to see if $_SESSION['user'] is set, if it is then it will redirect to home page otherwise it will redirect to login page...

how can I post in jQuery without having a html form? I just want to post to a url...

EDIT:

Based on @jondavidjohn's answer I changed my web app so that it uses index.php to check sessions:

<?php

session_start();

if(isset($_SESSION['username'])){
  //go to home page
  header('Location: ...home.html');
}else{
  //go to login page
  header('Location: ...login.html');
}

?>


It is surely possible doing this with javascript, but it is not secure at all...

You need to be checking at the server level for $_SESSION['user'] before you even send the content to the browser...

My answer would be to do the checking / redirecting with PHP before anything gets sent to the browser, it will be less complicated and more secure...

The reason a javascript solution is insecure is that you are relying on a technology that resides and is controlled by the client to control access to protected areas.


You can use $.post(url, params), where url is a string and params is a hash with your post data.


    $.post("/authenticate.php",null,function(data){

    // do something based on response returned
   if($data){alert("authenticated");}
    else
      alert("not authenticated");
    });

in your php file

if(isset($_SESSION['user']))
{    
 echo true;
}
else
return false;


Use $.post() to post data via AJAX to a page. Doing it this way won't allow the PHP script to redirect the user, you'll have to java JavaScript redirect them.

$.post('/path/to/page.php', {userID: 5}, function(data){
    // Use window.location to redirect
});

Or, you can create a "fake" <form> element, and post that.

var $form = $('<form/>').attr({
   method: 'post',
   action: '/path/to/page.php'
});
var $input = $('<input/>').attr({
  name: 'userID',
  type: 'text'
}).val('5');
$input.appendTo($form);
$form.submit();

I suggest you take @jondavidjohn's advice, and have PHP redirect the user before the page is sent to the browser. That's much more secure.


Why bother with the AJAX request? Since you're building the page with PHP, just have PHP embed some variables in a JavaScript block:

<script type="text/javascript">
   var is_logged_in = <?php echo $_SESSION['logged_in'] ? 'true' : 'false' ?>;
</script>

This'd save you an HTTP round-trip to retrieve data you already had available.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜