Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

jQuery Ajax passing value on php same page

I am kinda confused on it, when trying to send value on the same page.

 <script>
      $("select[name='sweets']").change(function () {
      var str = "";
      $("select[name='sweets'] option:selected").each(function () {
            str += $(this).text() + " ";

          });

            jQuery.ajax({
            type: "POST",
            data:  $("form#a").serialize(),

            success: function(data){
                jQuery(".res").html(data);

                $('#test').text($(data).html());


            }
            });  
            var str = $("form").serialize();
            $(".res").text(str);
    });
    </script>
 <div id="test">
 <?php
  echo $_POST['sweets'];
  ?>
  </div>
<form id="a" action="" method="post">
  <select name="sweets" >
   <option>Chocolate</option>
   <option selected="selected">Candy</option>
   <option>Taffy</option>
   <option>Caramel</option>
   <option>Fudge</option>
  <option>Cookie</option>
</select>
</form>

Well it will display if its in the top of html tag but if its inside the body it will display null.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is the working code for you. To send ajax request to the same page you can keep url parameter empty, which you are already doing. If you are trying to make the script behave differently when $_POST has value then use isset as I have used below.

 <?php
  if(isset($_POST['sweets'])) 
  {
    echo $_POST['sweets'];
    exit;
  }
  ?>

    <script>
        $(function(){
          $("select[name='sweets']").change(function () {
          var str = "";
          $("select[name='sweets'] option:selected").each(function () {
                str += $(this).text() + " ";

              });

                jQuery.ajax({
                type: "POST",
                data:  $("form#a").serialize(),

                success: function(data){
                    jQuery(".res").html(data);

                    $('#test').html(data);


                }
                });  
                var str = $("form").serialize();
                $(".res").text(str);
        });
        });
        </script>


 <div id="test">

  </div>

<form id="a" action="" method="post">
  <select name="sweets" >
   <option>Chocolate</option>
   <option selected="selected">Candy</option>
   <option>Taffy</option>
   <option>Caramel</option>
   <option>Fudge</option>
  <option>Cookie</option>
</select>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...