PHP header() called via AJAX not working properly

后端 未结 4 995
轮回少年
轮回少年 2021-01-25 06:29

I\'m new to web development.

Right now I\'m working on a login feature on a site. I used Javascript/AJAX to fetch the username and password and send it to a PHP file for

相关标签:
4条回答
  • 2021-01-25 07:11

    What's happening exactly?

    After header() is called in php, php still executes the rest of the script unless you stick an exit; after the header() call. This is only if you don't want to execute the rest of login.php

    0 讨论(0)
  • 2021-01-25 07:22

    You can one thing replace your code header("Location: profile.php"); by echo "window.location.href='profile.php'; and replace your success function as

         if(obj.status == 200) {
             eval(obj.responseText);
         }
    

    Thats it. now a response will be evaluated by script and will redirect your page on profile.php

    0 讨论(0)
  • 2021-01-25 07:24

    I don't think the redirect will work with AJAX. This is what will happen:

    1. AJAX request is sent to login.php
    2. login.php sends back a header with Location: profile.php
    3. The browser then redirects and fetches profile.php
    4. The results of profile.php is then passed to your XMLHttpRequest Object.

    A way to get the AJAX response to redirect your page is to do this:

    • The response from login.php returns a JSON response containing the status code (302 or 301) and the location to redirect to.

    • The response itself has a status code of 200 (successful).

    • The process the JSON response and check the status code for 302 or 301 and redirect to the location.

    0 讨论(0)
  • 2021-01-25 07:25

    You need to take out the echo statement before header(). Header won't work if anything has been output to the browser before it is called.

    Here's the php doc on that.

    0 讨论(0)
提交回复
热议问题