i use php code in javascript. However, there is an error.
I don't know what went wrong with my code. Can you take a look?
function wp_auth_javascript() {
if (is_page('login')) {
?>
<script type="text/javascript">
function auth_adult(){
IMP.certification({ // param
merchant_uid:'merchant_' + new Date().getTime(),
min_age: 19
}, function (rsp) { // callback
if (rsp.success) {
alert('success');
<?php $_SESSION['adult'] = 'y'; wp_redirect(home_url()); exit; ?>
}else{
alert('fail');
}
});
}
</script>
<?php
}
}
add_action('wp_head', 'wp_auth_javascript');
When I use this code, When I go to the login page, It is automatically redirected to home url. I thought I would be redirected when I succeed in the callback, but it doesn't work that way at all. What is the problem?
Try to redirect by Javascript, not PHP.
if (rsp.success) {
alert('success');
window.location.href = '/'; // Or anything you want.
}
The PHP inside your if statement will run all the time you access the login page despite you authorize (by Javascript) success or fail.
But that just the example code, you should call to admin-ajax.php or a php files like @May Weather VN's anwser to assign the session to them.
I think this line incorrect :
<?php $_SESSION['adult'] = 'y'; wp_redirect(home_url()); exit; ?>
Instead :
<?php ($_SESSION['adult'] = 'y') ? wp_redirect(home_url()) : exit; ?>
Bad code. When js function is sent to browser you cannot use php code, instead send ajax to server to set SESSION and then redirect by javascript.