Praveen Sinha
Praveen Sinha

Reputation: 27

something is going wrong in submitting form data through ajax

I am trying to submit a form's data to database using ajax. I am unable to figure out what's going wrong.

The below part is the HTML containing the form data.

HTML->

<form id="myForm" method="post">
    NAME:<input type="text" id="name" name="name">
    PICKUP:<input type="text" id="pick" name="pick">
    DROP:<input type="text" id="drop" name="drop">

    <input type="submit" id="sub" value="Submit"></button>
  </form>
  <div class=".data"></div>

The below part inlcudes the ajax calls. I have included the jquery CDN.

JAVASCRIPT->

$("#myForm").submit( function(){
        var name = $("#name").val();
        var pick = $("#pick").val();
        var drop = $("#drop").val();
        var str = name+"/"+pick+"/"+drop;
        $.ajax({
          type: "POST",
          url: "p_inp.php",
          data: "str="+str,
          success: function(data){
            $(".data").html(data);
          }
        });

    });
    $("#myForm").submit( function(){
    return false;
  });

The following is the PHP file which enters the data into database.

PHP file->

    <?php

    $con = mysqli_connect('localhost','root','pagal.com','next');

    //echo 'HI';
    $str = $_POST['str'];
    $s = explode("/",$str);
    $name = $s[0];
    $pick = $s[1];
    $drop = $s[2];


    $sql = "select count(*) as c from passenger";
    $res = $con->query($sql);
    while($row = $res->fetch_assoc())
    {
        $c = $row['c'];
    }
    $c = $c+1;
    //echo $c;
    $sql = "insert into passenger values('$c','$name','$pick','$drop')";
    if($con->query($sql))
        echo 'Data entered Successfully<br>';
    else echo 'Something Went Wrong<br>';

    $con->close();

?>

Upvotes: 0

Views: 64

Answers (1)

Madhan Varadhodiyil
Madhan Varadhodiyil

Reputation: 2116

Can you try by removing the second submit() function , modifying your first submit function to prevent default.

something like this.

$("#myForm").submit( function(event){
    var name = $("#name").val();
    var pick = $("#pick").val();
    var drop = $("#drop").val();
    var str = name+"/"+pick+"/"+drop;
    $.ajax({
      type: "POST",
      url: "p_inp.php",
      data: "str="+str,
      success: function(data){
        $(".data").html(data);
      }
    });
  event.preventDefault();
});

Upvotes: 1

Related Questions