mughees ilyas
mughees ilyas

Reputation: 526

getting variable from javascript to php

I have a simple combo box whose value I can get in JavaScript. I am doing that so I don't need to refresh the page. Also I want to use the selected value to do some conditional branching after combo box so how do I get the value of combo box from JavaScript to my variable $change.

echo '<select id="combo_1">';
echo '<option value="2">Submative</option>';
echo '<option value="1">formative</option>';
echo '</select>';

Below is my JavaScript:

    <script type="text/javascript">
    $(document).ready(function() {

        $('#combo_1').change(function(){

        });

    });

    </script>

Here I want to do $change = $(this).val(), but obviously I cant do it like this.
Any suggestions? i want to do it on the same page without refreshing or without submitting my url kinda look like this

 http://localhost/lms/grade/report/userdef/index.php

and i want it to be on click action cuz depending on the choice of combobox 2 very different procedures will be called

Upvotes: 1

Views: 623

Answers (3)

Goutam Pal
Goutam Pal

Reputation: 1763

<script type="text/javascript">
 $(document).ready(function() {

  $('#combo_1').change(function(){
        var combo_1 = $(this).val();
        $.ajax({
                type: 'GET',
                url: 'ajax.php',
                data: {'combo_1':combo_1},
                success: function(data){
                    alert(data)
                }
            });
  });

 });

 </script>

ajax.php


 if( isset($_GET['combo_1]) ) {
    echo $change = $_GET['combo_1'];
 }

Upvotes: 2

Gokul Gopala Krishnan
Gokul Gopala Krishnan

Reputation: 323

JS:

$.ajax({
    type: "POST",
url: './filename.php',
    beforeSend: function(){
        //If you want to do something 
},
data: 'data='$('#combo_1').val(), //Optional '&data2='+value+'&datan='+value,
    success: function(msg){
        alert(msg);
    }
});

PHP:

$val = $_POST['data'];
return 'received successfully';

This will alert 'received successfully'

Upvotes: 0

casraf
casraf

Reputation: 21694

You're gonna want to use AJAX and submit the form, then you can access the returned data without ever refreshing the page.

Basically:

HTML

<select name="combo" id="combo_1">
    <option value="2">Submative</option>
    <option value="1">formative</option>
</select>

JavaScript

$('#combo_1').change(function() {
    $.post('calcScript.php', $(this).serialize(), function(data) {
        alert(data);
    });
});

in PHP, you can access your combo data via $_POST['combo'].

Upvotes: 2

Related Questions