-1

I have created form on myform.php template with radio group input type and value is updated with onchange="javascript:document.post.submit()"'; . So every time whenever I change my selection, value gets updated with page refresh. Is there any way so I can update my selection without page refresh using ajax?

     <?php
          $foods = array('pasta', 'burger', 'pizza','popcorn');


            foreach ($foods as $food) {
            echo  '<input name="my_favorite_food" type="radio"   onchange="javascript:document.post.submit()"';
            $option = 'id=" ' .$food . '"';
            $option = 'value="' . $food . '"';

            if ($food == $my_favorite_food) $option .= 'checked="checked"';
            $option .= '>';
            $option .= '<label for=" '.$food .' ">' . $food .'  ';
            $option .=  '</label>';
            echo $option;
              }
         ?>

       <div id ="block">
        <?php 

        if ($my_favorite_food == "pasta") : ?>

          <h2>your favorite food is pasta</h2>
           <p> my pasta recipe......   </p>

        <?php endif;?>

        if ($my_favorite_food == "burger") : ?>

          <h2>your favorite food is burger</h2>
           <p> my burger recipe......   </p>

        <?php endif;?>

        if ($my_favorite_food == "pizza") : ?>

          <h2>your favorite food is pizza</h2>
           <p> my pizza recipe......   </p>

        <?php endif;?>

        if ($my_favorite_food == "popcorn") : ?>

          <h2>your favorite food is popcorn</h2>
           <p> my popcorn recipe......   </p>

        <?php endif;?>
<div>
galexy
  • 343
  • 3
  • 16
  • 37

1 Answers1

2

Generate the HTML for all of the options, and conditionally hide (style="display:none") those that aren't currently selected. The (generated) HTML would look something like this:

<input type="radio" value="burger" name="favourite_food" class="favourite"/> Burger
<input type="radio" value="popcorn" name="favourite_food" class="favourite"/> Popcorn
...

<div id="burger" class="favourite-display">
    <h2>your favorite food is burger</h2>
    <p> my burger recipe...</p>
</div>
...

Then the jQuery:

$(document).ready(function() {
    $('.favourite').on('change', function(event) {
        $('.favourite-display').hide();
        $('#' + this.value).show();
    });
});

There shouldn't be a need to actually submit the form (with or without AJAX) every single time just to control which part is shown.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76