简体   繁体   中英

javascript variable not reading php variable

in the script below the javascript variable (date) is not displaying the value of the php variable (field). Php variable is the info that i need to pass to another page.

If I dont use if (isset($_POST['submit'])) and set $field="something"; then it works. What am I doing wrong?

Thanks in anticipation for the help

<HTML>
<BODY>

<?php 
if (isset($_POST['submit'])) {$field = $_POST['field'];}
?>

<FORM name="filter" METHOD ="POST" ACTION ="">

<select name="filteroptions" onChange="chgAction()">

<option value="" selected="selected">select an option</option>

<option value="Date Range" <?php if(isset($_POST['filteroptions']) && $_POST['filteroptions'] == 'Date Range') echo 'selected= "selected"'; ?>>Date Range</option>

</select> 

<input type="text" name="field">

<INPUT TYPE = "submit" name="submit">

</form>


 <script>

function chgAction() {

var date = "<?php echo "/log/date.php?id=".$field; ?>";

        var form = document.filter;

    console.log('chgAction()');
    console.log(form.filteroptions.selectedIndex);

    switch (form.filteroptions.selectedIndex) {
        case 1:
            form.action = date;
            break;
           }

} 

</script>

</BODY>
</HTML>

The $_POST will only contain data after the the data has been submitted. And your code can only work if the data is posted back to this page.

So if a user who has not submitted data to this page, has just loaded this page. Then it will not work. The $field will not exist because there is no post array value "submit".

If a user is either on this page or another page, that posts data to this page & within that post data contains the fields: 'submit' & 'field' then it'll work.

As in this PHP Fiddle , if field is set and submitted already you'll get the log for the corresponding date, if field is not defined it will complain

<?php 
    if(isset($_POST['submit'])){
        $field = $_POST['field'];
    }else{
        $field = '';
    }
?>
<form name="filter" method="POST" action="">
    <select name="filteroptions" onChange="chgAction()">
        <option value="" selected="selected">select an option</option>
        <option value="Date Range" <?php if(isset($_POST['filteroptions']) && $_POST['filteroptions'] == 'Date Range') echo 'selected= "selected"'; ?>>Date Range</option>
    </select>
    <input type="text" name="field">
    <input type = "submit" name="submit">
</form>
<script>
    function chgAction() {
        var field = "<?php echo $field; ?>";
        if(field != ''){
            var date = "/log/date.php?id=" + field;
            alert(date);
        }
        else{
            alert('Please select a date range');
        }
    }
</script>

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