Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP header() doesnt redirects after ajax is called

Tags:

ajax

php

I am using ajax to insert data. after registration if successful it will redirect to its registry page or registry.php. But it seems that it is not redirecting to its respective page and the weird thing is when i check it on the console on firefox it seems that it gives a right result, something like this POST xxxx/form_zuri/insertData.php 302 Found 50ms and GET xxxx/form_zuri/registry.php 302 Found 37ms.

heres the code for insertData.php

    if($data = $admin->insertRegistrantInfo($fname, $lname, $aname, $email, $password) == true) {
    session_regenerate_id(true);// destroying the old session id and creating a new one
    $_SESSION['id'] =  $data;
    header('location: registry.php');
    exit();

heres my ajax script:

$("#submit_third").click(function(){


    $.ajax({
        type: "POST",
        url: "insertData.php",
        data: {

            fname                       : $("#fname").val(),
            lname                       : $("#lname").val(),
            aname                       : $("#aname").val(),                
            email                       : $("#email").val(),
            password                    : $("#password").val()              

            },
        cache: false,
        success: function(data) {

        //window.location.replace('registry.php') ;   

        }
    });
    //window.location.replace('registry.php') ;  
    //return false;

});

if i will use the .replace js function it wont be able to get the SESSION ID.

any idea guys?

like image 772
user3052545 Avatar asked Jan 07 '14 15:01

user3052545


2 Answers

When you call a PHP Script in AJAX, the request is being executed by the AJAX call and not the current page the client is on, therefore it won't change the headers on the page that is actually being viewed - only on the response of the AJAX call. Which in this case won't do what you want.

Also, you can't change the headers when content has already been outputted which again in your case it will have been.

If you use window.location.href = 'registry.php' in your AJAX callback, the session id should be there. Using window.location.replace won't add a new record to your history.

like image 157
Ryan Avatar answered Oct 21 '22 07:10

Ryan


A different approach will be to create another session id, for example $_SESSION["passed"] = true; then after successful insert of your data you can refreshes your current page, and still use the header method.

php code

if (isset($_SESSION["passed"])){
if ($_SESSION["passed"]) header('location: registry.php');
}

on the javascript side you can reload after a successful query

location.reload();
like image 34
KKhanye Avatar answered Oct 21 '22 07:10

KKhanye