3

    var val;
    $('select').on('change', function() {
        alert( this.value );
        val = this.value;
    })
    
    <?php
echo $variable = "<script>document.write(val)</script>";
?>
<select>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">four</option>

</select>

I want to get the value of the selected box and save it in a PHP variable. I want to save and echo val variable. Please help

5

2 Answers 2

1

use this code for use variable

  <?php
  session_start();
  echo $_SESSION['php_value'];
  ?>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    function getValue(obj){
    var value = obj.value;
    $.ajax({
        type:"POST",
        url: 'edit.php',
        data: "val="+ value,
        dataType: 'text',
        async: false,
        cache: false,
        success: function ( result )  {
            window.location.reload();
        }
    });
}

</script>

<select onchange="getValue(this)">
<option value="1" <?php if($_SESSION['php_value'] == 1) echo 'selected';?>>One</option>
<option value="2" <?php if($_SESSION['php_value'] == 2) echo 'selected';?>>Two</option>
<option value="3" <?php if($_SESSION['php_value'] == 3) echo 'selected';?>>Three</option>
<option value="4" <?php if($_SESSION['php_value'] == 4) echo 'selected';?>>four</option>

</select>

then create edit.php file

<?php
 session_start();
 $_SESSION['php_value'] = $_REQUEST['val'];
?>
Sign up to request clarification or add additional context in comments.

10 Comments

I need a value in a php variable. So where is a variable? help me please
So great to see three levels of language nesting use the src attribute.
JavaScript inside HTML is bad. JavaScript inside HTML inside PHP is worse.
i have just answer it , this is not need to structure, when question teller use , he will use it as structure
@ShafiqulIslam Thanks for your help. Your code is working fine. But I have little problem. <script src="ajax.googleapis.com/ajax/libs/jquery/2.1.1/…> when I included it in my code it reflects and dropdown is not working. and without it when i select dropdown then a popup appears and ask to reload page
|
0

Ajax can do this. Google it, and check out api.jquery.com and look at the ajax functions, .ajax(), .post(), .get(), .load(), etc.

As for your specific question, here is what you would do:

//Javascript file

$.post('my_ajax_receiver.php', 'val=' + $(this).val(), function(response) {
  alert(response);
  });

});

//PHP file my_ajax_receiver.php
<?php
   $value = $_POST['val'];
   echo "$value";
?>

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.