doushan2224 2017-02-02 18:33
浏览 28
已采纳

简单的jquery ajax发布php无法正常工作

Hi iam learning jquery with php. I created very small php and jquery code to getting value but it's not working. I check console but not giving any information i have referred jquery api documentation same process i followed but no use. How can i solve this.

   <script>
   $(document).ready(function(){
       $("#submit").click(function(){
           var term= $("#sterm").val();          
           $.post('oopsdata.php', {nwterm: term}, function(data){
               ("#container").html(data);
           });
       });
   });
   </script>

    <body>
     <form class="" action="" method="post">
        <input type="text" name="" value="" id="sterm">
        <input type="submit" name="" value="Search term" id="submit">
     </form>
     <div id="container">olddata</div>

PHP Code

<?php
   $newterm = $_POST['nwterm'];
   if($newterm == 'bio'){
       echo "Request received This is the new data"
   } else {
       echo "no data received;"
   }
?>
  • 写回答

1条回答 默认 最新

  • dtp791357 2017-02-02 18:45
    关注

    There are few issues with your code, such as:

    • You need to prevent your form from being submitted in the first place. Use jQuery's .preventDefault()
    • Missing $ before ("#container").html(data);

    Based on the above two points, your jQuery code should be like this:

    $(document).ready(function(){
        $("#submit").click(function(event){
           event.preventDefault();
            var term= $("#sterm").val();          
            $.post('oopsdata.php', {nwterm: term}, function(data){
                $("#container").html(data);
            });
        });
    });
    
    • There are two syntax errors in your PHP code. Missing ; in both your echo statements.

    So based on the above point, your PHP code should be like this:

    <?php
        $newterm = $_POST['nwterm'];
        if($newterm == 'bio'){
            echo "Request recieved This is the new data";
        }else{
            echo "no data recieved";
        }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?