Shawn Vn
Shawn Vn

Reputation: 297

AJAX works fine but PHP won't receives data

This is one of the weirdest problems that I've seen
Ajax sends datas correctly (I guess) but Php won't receives them
I've tried to change url to current page and it returns me empty and the success functions returns me the source code !

    <div class="test">
        <h3>test</h3>
    </div>
   $(document).ready(function () {
       $("div").click(function () {
           let folderName=$(this).children("h3").text();
          $.ajax({
              type:"POST",
              url:"post.php",
              data: {id:folderName},
              success:function (data) {
                  alert(data)
              }
          });
          });
       });
 var_dump($_POST);

Upvotes: 1

Views: 77

Answers (1)

Shivendra Singh
Shivendra Singh

Reputation: 3006

If you are sending the ajax request in current page which contain the html code. In response you will get source code of that html page.

To resolved this issue add the Ajax request functionality on top of page.

post.php will be like.

<?php
//Start ajax request
if($_POST['id']){
        echo $_POST['id'];
        exit;
}
?>
<!-- Start HTML COde --->
<script>
$(document).ready(function () {
   $("div").click(function () {
       let folderName=$(this).children("h3").text();
      $.ajax({
          type:"POST",
          url:"post.php",
          data: {id:folderName},
          success:function (data) {
              alert(data)
          }
      });
      });
   });

</script>
<div class="test">
    <h3>test</h3>
</div>

Upvotes: 1

Related Questions