JQuery Ajax pass value in php to same page

I am a little confused when I try to post a 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 it is at the top of the html tag, but if it is inside the body it will display zero.

+7
source share
2 answers

Here is the working code for you. To send an ajax request to the same page, you can leave the url parameter empty, which you already do. If you are trying to make the script behave differently when $_POST matters, use isset , as I 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> 
+8
source

You have to wrap your code with

 $(document).ready(function(){ // your code here }); 

Thus, it will only work when the browser completes processing the structure of your HTML.

UPDATE

There was a lot of debugging material in your code, try this (it requires Firebug to see the result of the ajax request):

 <script> $(document).ready(function(){ $("select[name='sweets']").change(function () { jQuery.ajax({ type: "POST", data: $("form#a").serialize(), success: function(data) { // Check the output of ajax call on firebug console console.log(data); } }); }); }); </script> 
+1
source

All Articles