muraliniceguy97
muraliniceguy97

Reputation: 381

Simple jquery ajax post php not working

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;"
   }
?>

Upvotes: 0

Views: 982

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

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";
    }
?>

Upvotes: 3

Related Questions