Skip to content Skip to sidebar Skip to footer

Why Is This Code Showing Anomalous Behaviour? (form Not Submitted)

I'm trying to submit a form using PHP and Ajax. But the problem is that sometimes it inserts one value, sometimes 2, sometimes all, and now it is inserting nothing. Why is it happe

Solution 1:

You may have entered a ' quote and it killed your sql statement. This is called sql injection. To prevent sql injection you can use pdo prepared statements. You will also want to hash passwords to prevent people from stealling them if they get access to your database. Hashing password is a one way encryption that is easy to check.

$pdo = new PDO("mysql:host=$db_host;dbname=$DB_name", $user, $pass);
$sql = "INSERT INTO signup(name, username, phone, password) VALUES(':name', ':username', ':phone', ':pass')";
if ($con = $pdo->prepare($sql)) {
    $con->execute([
        ':name' => $_POST["name"],
        ':username' => $_POST["username"],
        ':phone' => $_POST["username"],
        ':pass' => $_POST["password"]
    ]);
}

As far as the html and javascript goes. Catch the submitted form with jquerys .submit() function.

$('form').submit(function(e){
        e.preventDefault();
        $.post('submit.php',$(this).serialize(),function(response){
            alert('complete');
        }).error(function(){
            alert('wrong');
        });
    });

This makes sure than any submit event triggers the ajax.

Solution 2:

Since you are using a form with a submit button, when you click the button it will submit the form. You may be having a conflict between the AJAX action and the form submit. Try preventing the default action on the button click and see if it works as follows:

$(document).ready(function(){
$("#button").click(function(event){
if($("form").get()[0].checkValidity()){
  $.ajax({
      url: "submitform.php",
      type: "POST",
      data: $("form").serialize(),
      success: function(data){
          alert("well");
      },
      error: function(){
              alert("Error");
              }
          });
      });
    }
    event.preventDefault();
 });

Solution 3:

You assign your onclick to a button element, but there is no button element on your page, your button is an input element. Change that to a button and it may work. I personally would advise using ids, rather than element types, I think it makes things clearer, and will allow you to have more than one element of the same type without breaking your code.

Change

$("button").click(function(){

to

$("#button").click(function(){

and

data: $("form").serialize(),

to

data: $("#signupform").serialize(),

Post a Comment for "Why Is This Code Showing Anomalous Behaviour? (form Not Submitted)"