简体   繁体   中英

Including Php Code that will redirect user within a javascript file?

I have a file (confirm.js) which will redirect a login page to a home page if the Username and Password were entered correctly. I am getting an error on the line:

<?php header("Location: ../MedCompany/homepage.php ?>

The error that I am receiving from the console is as following:

Uncaught Syntaxerror: Unexpected token <

How should I include the php code within my javascript document so it can redirect to another php file. Why is my code incorrect?

I thought <php? php code ?> <php? php code ?> is the proper way of doing this

$('document').ready(function () {
    button = document.getElementById("button");
    button.onclick = function () {
        var data = $("#loginform").serialize();
        $.ajax({
            type: 'POST',
            url: '../MedCompany/php/welcome.php',
            data: data,
            success: function (response) {
                console.log("response was " + response);
                if (response == "Login Succesfull") {
                    <?php
                    header("Location: ../MedCompany/homepage.php");
                    ?>
                }
                else {
                    $("#error").html('<div class="alert alert-info" role="alert">;' + response + '</div>');
                }
            }
        });
    }
});

You can't just plonk a bit of PHP in the middle of Javascript code and expect it to do what you want. The Javascript parser is attempting to parse it as Javascript and, funnily enough, isn't managing it.

You need to redirect the browser using Javascript methods, ie setting the window.location object:

window.location = "../MedCompany/homepage.php";

Using the PHP method will only work when the PHP engine is working, ie when the code is being executed on the server, not in the browser.

if you put the JavaScript code in file .js, you can not use php.


you can use:

window.location.href = "../MedCompany/homepage.php";

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