Ria
Ria

Reputation: 526

After ajax rerun php

I have an select menu that submits without reloading the page as follows:

<select id="option" name="option">
<option value="15">15/option>
<option value"30">30</option>
<option value"90">90</option>
</select>

It will submit to the current page as follows, without reloading the page

<script type="text/javascript">
    $('#option').change(function(){
        var option_val = $(this).val();
        $.ajax({
        type: 'post',
        url: "$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];",
        data: "option="+option_val,
       success: function(data)
        {
           window.alert(data)
        }
        });
    });
</script>

The result of a change in the option menu is an popup window with all the code of the page echoed back.

What i want to do on the page is use the $_POST['option'] that is submitted and recalculate a price for example

<body>
//some code and div's
<?php
if (isset($_POST['option'])) {
    $option = $_POST['option'];
$price= $row_product['price'] + $option;
echo $price;
} ?>
</body>

The are several places where I would like to use the submitted option value

Any help welcome Sorry if it is very obvious

Upvotes: 0

Views: 311

Answers (1)

Sampgun
Sampgun

Reputation: 2977

The only way is making a PHP page that does the calculation

HTML/page1.php

<select id="option" name="option">
    <option value="15">15</option>
    <option value="30">30</option>
    <option value="90">90</option>
</select>
<div id="dynamic">
    <p>DEFAULT CONTENT</p>
</div>

HTML/page2.php

$option = 0;
if(isset($_GET["option"])){
    $option = $_GET["option"];
}
//do calculations
echo "<my-html-stuff>lorem ipsum</my-html-stuff>";

JS

var dynamic = $("#dynamic");
$('#select').on("change", function() {
   var selected = $(this).val();
   dynamic.load("page2.php?option=" + selected, function() {
       dynamic.html("<p>CONTENT OPTION "+selected+"</p>");
   });
});

Fiddle ==> https://jsfiddle.net/tonysamperi/4dbwwn3g/

WITH JSON

page2.php

header('Content-Type: application/json');

$option = 0;
if(isset($_GET["option"])){
     $option = $_GET["option"];
}
$response = ["result" => $option];
echo json_encode($response);

JS

$('#select').on("change", function() {
   var selected = $(this).val();
   $.get("page2.php?option=" + selected, function(response) {
       //do stuff with data
       console.debug("RESPONSE", response);
   });
});

Upvotes: 1

Related Questions