2

I want to convert javascript variable to php variable to use it in sql query,but it doesn't work.

html code :

<select id = "dep_ID" name = "dep_ID" onchange="myFunction()">

javascript code in the same file:

<script>
    function myFunction(){

        var xo = document.getElementById("dep_ID").value;
        document.getElementById("demo").innerHTML = "You selected: " + xo;

        $.ajax({
            url: 'insert.php',                
            data: {duration: xo},
            type: 'POST',
            success: function(data) {
            alert(data);
            document.getElementById("demo").innerHTML = "You selected: " + <?php echo @$duration;?>;
            }
        });
    }
</script>

insert.php code:

<?php
$duration = $_POST['xo'];
return $duration ;
?>

I expect the output of dep_ID variable, but i get nothing.

1
  • 4
    I think you want $_POST['duration'], not $_POST['xo']. Commented May 30, 2019 at 13:40

2 Answers 2

1

Javascript and PHP systax are different. In the response of ajax call you will get javascript object. So you need to do changes as follows:

document.getElementById("demo").innerHTML = "You selected: " + data.duration;
Sign up to request clarification or add additional context in comments.

Comments

0

$duration variable in PHP code is NOT defined in the HTML file that contains the javascript.

I think you're confusing what happens BEFORE the html page is produced, with what happens WHEN the page i rendered and the user selects a value, with what happens AFTER the ajax call has been done and insert.php has been executed.

To be clear, this:

gets executed BEFORE anything has happened in the browser, so $duration is undefined.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.