Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Back to PHP from jQuery

I want to echo the HTML dropdown value through jQuery:

<select id="single">
  <option>Single</option>
  <option>Single2</option>
</select>

<script>
  function displayVals() {
    var singleValues = $( "#single" ).val();
    $( "p" ).html( "<b>Single:</b> " + singleValues);
  }
  $( "select" ).change( displayVals );
  displayVals();
</script>

and echo the dropdown value in PHP:

<?php
    echo $single;
?>
like image 712
Csaba Molnár Avatar asked Mar 16 '26 19:03

Csaba Molnár


1 Answers

You can't access select values in PHP without first submitting the form.

Here's a sample form which submits to a file called submit.php

<form method="post" action="submit.php">

<select id="my_select" name="my_select">
    <option value="1">One</select>
    <option value="2">Two</select>
    <option value="3">Three</select>
</select>

</form>

The contents of submit.php would look like this...

<?php
echo $_POST['my_select']; // Will output the value of my_select when the form was submitted
?>

You could also use ajax to submit data from your form to a PHP page, have the PHP page generate some HTML output and return it back to your jQuery, from there you can insert the resulting HTML into an element (div) in your page.

<form id="my_form" method="post" action="submit.php">

<label>Select the number of items you'd like @ £5.00 each</label><br>
<select name="my_select">
    <option value="1">One</select>
    <option value="2">Two</select>
    <option value="3">Three</select>
</select>

</form>

<div id="result"></div>

Create a PHP page to receive the data from the form.

$price = 5.00;
$noOfItems = $_POST['my_select'];

$totalCost = $price * $noOfItems;

echo "<p>$noOfItems @ $price will cost you $totalCost"; 

Then use some jQuery to submit the data from your form to the PHP back in the background, and then put the resulting HTML into the #result div.

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

    $("#my_select").change(function(){
        $.post("submit.php", $("#my_form").serialize(), function(response){
            $("#result").html(response);
        });
    });

}))
</script>
like image 125
SheppardDigital Avatar answered Mar 18 '26 07:03

SheppardDigital



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!