bonaca bonaca - 4 months ago 8
Javascript Question

passing variable - Undefined index error

I want to pass

path
variable from js to
plus-page.php
and then go to that page.

$("#btnpage").click(function(){
path = $('#spantwrap').html();
console.log(path); // works, that's a simple html code.
$.ajax({
url: 'plus-page.php',
type: 'post',
data: {'path': path},
success: function() {
console.log(path);
}
});
location.href = 'plus-page.php';
});


plus-page.php

<form id="form1" action="?" method="post">
<input type="hidden" name="path" value="<?php echo $_POST['path'];?>" // line 46
</form>


Error:
Undefined index: path on line 46...

Answer

The solution is of course to get rid of ajax call and just post your form to plus-page.php because it doesn't make any sense in current form

But if you really want to have this logic, i.e passing some variable to second page and redirect to that page later then you should keep the passed value in session and use it later on

<?php
if (isset($_POST['path'])
{
    $_SESSION['path'] = $_POST['path'];

    // to stop only in case of AJAX call use the following line:
    // if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')

    die();
}
?>

<form id="form1" action="?" method="post">    
<input type="hidden" name="path" value="<?php echo $_SESSION['path'];?>" // line 46
</form>

Note that this DOESN'T make any sense if you want to redirect immediataly