-1

what i am trying is to fetch a data from my php page using javascript,but it seems that the javascript is not working properly.in this when click my submit button the datas should be sent to the action page,but i dont want to go to the php page and the result in php page should be displayed in the intial page(in this at div id:result)

view of the page enter image description here

this is my index page,this is just example view

register.html

    <!DOCTYPE>
<html>
<head>
<title>REGESITER</title>
<script src="script/jquery-1.11.2.min.js" type="text/javascript"></script>
<script>
    $("sub").click( function() {

        $.post($("#myform").attr("action"),
        $("#myform :input").serializeArray(),
        function (data) {
            $("#res").empty();
            $("#res").html(data);
        });

  $("#myform").submit( function() {
    return false;
  });
});</script>
</head>
<body>



<form id="myform" action="helper.php"  method="post">

FIRSTNAME:<input type="text" name="txtfname" id="fname">
<br><br>
LASTNAME:<input type="text" name="txtlname" id="lname">
<br><br>
AGE:<input type="text" name="txtage" id="age">
<br><br>
<button id="sub">SUBMIT</button> 


</form>

<div id="res">Result</div>
</body>
</html>

this is my php file,from where the echoed result is to fetched

helper.php

<?
       $fname=$_POST['txtfname'];

       $lname=$_POST['txtlname'];

       $age=$_POST['txtage'];

   $con=mysql_connect('localhost','root','');

    if ($con)
    {
      $db=mysql_select_db('register',$con);
    }



   if ($db)
   {      
       $q1=mysql_query("insert into regdb(firstname,lastname,age) values('$fname','$lname','$age')",$con);

      echo"inserted into database";

      }
      else
      {
          echo "error in query";
      }
      ?>
vyshagh s
  • 18
  • 2

1 Answers1

1

complete working html code:-

     <!DOCTYPE>
<html>
<head>
<title>REGESITER</title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$( document ).ready(function() {
        $( "#sub" ).click(function(event) {

             $.post('helper.php',
             $("#myform :input").serializeArray(),
             function (data) {
                 $("#res").empty();
                 $("#res").html(data);
             });


     });
});
        </script>
</head>
<body>



<form id="myform" action=""  method="post">

FIRSTNAME:<input type="text" name="txtfname" id="fname">
<br><br>
LASTNAME:<input type="text" name="txtlname" id="lname">
<br><br>
AGE:<input type="text" name="txtage" id="age">
<br><br>
<input type="button" id="sub" value="Enter" />


</form>

<div id="res">Result</div>
</body>
</html>
Gaurav Srivastava
  • 3,232
  • 3
  • 16
  • 36