简体   繁体   中英

save data in database without redirection in php

I have a simple form, and I want to save the data in my database without redirection. I am using php, ajax and jquery for my page. I don't know if I did something wrong but after I hit the submit button the form data appears on the address bar. the data is stored in the database successfully but the page reloads as well. My code is given below.

HTML

<form>
<input type="text" placeholder="Full Name*" required pattern= "[a-zA-Z]+" title="Alphabets only" name="name" id="name">
<input type="email" placeholder="Email*" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" name="email" id="email">
<input type="text" placeholder="Contact*" required pattern="[0-9]\d{9}" title="only 10 digit allowed" name="contact" id="contact">
<textarea placeholder="Enquiry(if any)" name="msg" id="msg"></textarea>
<button type="submit" name="register" id="register_btn">Register</button>
<span id="success"></span>
<span id="error"></span>
</form>

PHP

    include("conn/connect.php");
    if(isset($_POST['email'])){
    $email= mysqli_real_escape_string($connect, $_POST['email']);
    $name= mysqli_real_escape_string($connect, $_POST['name']);
    $contact= mysqli_real_escape_string($connect, $_POST['contact']);
    $msg= mysqli_real_escape_string($connect, $_POST['msg']);
    $sql= "INSERT INTO registration(email, name, contact, msg, added_on) values('$email','$name','$contact','$msg', now())";
    if(mysqli_query($connect, $sql))
    {
        echo '<h4>Registration Complete</h4>';
    }

}

JAVASCRIPT

<script>  
$(document).ready(function(){  
$('#register_btn').click(function(){  
  var name = $('#name').val();  
  var email = $('#email').val();
  var contact = $('#contact').val();
  var msg = $('#msg').val();  
  if(name == '' || email == '' || contact == '')  
  {  
      $('#error').html("<h4>Mandatory field(s) are empty</h4>");
      setTimeout(function(){  
          $('#error').fadeOut("Slow");  
          }, 3000);  
        }  
  else  
      {  
        $('#error').html('');  
        $.ajax({  
           url:"registration.php",  
           type:"POST",  
           data:{name:name, email:email, contact:contact, msg:msg},  
           success:function(data){  
           $("form").trigger("reset");  
           $('#success').fadeIn().html(data);  
           setTimeout(function(){  
              $('#success').fadeOut("Slow");  
             }, 3000);  
           }  
        });  
     }  
   });  
  });  
</script>

You're calling an event on submit button that will refresh your page.

Use event.preventDefault() in your click function.

$(document).ready(function(){  
  $('#register_btn').click(function(event){  
     event.preventDefault();
  });
});

FYI, if your validations stop working then try to do this.

$('#register_btn').click(function(event) {
  //Check form is valid
  if ($(this).closest('form')[0].checkValidity()) {
    // stop form from redirecting to java servlet page
    event.preventDefault();


    $.ajax({
      type: form.attr("method"), // use method specified in form attributes
      url: form.attr("action"), // use action specified in form attributes
      data: form.serialize(), // encodes set of form elements as string for submission
      success: function(data) {
        // get response from servlet and display on page via jQuery 
      }
    });
  }
});

Reference

As Loading.. points out you need event prevent default but in the form submit event, like this:

$('form').on('submit', function(e){
    return false;
});

return false on submit = e.preventDefault + e.sotpPropagation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM