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";
        }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog