Skip to content

Instantly share code, notes, and snippets.

@rahuls360
Created April 24, 2018 10:36
Show Gist options
  • Save rahuls360/82d6f0881e2d3da4f04543061d795234 to your computer and use it in GitHub Desktop.
Save rahuls360/82d6f0881e2d3da4f04543061d795234 to your computer and use it in GitHub Desktop.
AJAX PHP form
HTML
<form action="form.php" method="POST">
<input type="text" placeholder="Name" name="name">
<input type="text" placeholder="Email" name="email">
<input type="text" placeholder="Mobile" name="mobile">
<input type="submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="main.js"></script>
JavaScript
$('form').on('submit', function(){
var that = $(this);
var action = that.attr('action');
var method = that.attr('method');
var data = {};
that.find('[name]').each(function(index, value){
var that = $(this);
var name= that.attr('name');
var value= that.val();
data[name] = value;
});
$.ajax({
url: action,
type: method,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
PHP
<?php
if($_POST['name'] != null && $_POST['email'] !=null && $_POST['mobile'] != null){
echo "Nice" ;
}else{
echo "Uh uh";
}
?>
@rahuls360
Copy link
Author

rahuls360 commented Jul 16, 2018

Prevent visitors from spamming the form submit button 9000 times

$('#form1').on('submit', function(){
    $('#form1 input, #form1 select').attr('disabled', true)
    var that = $(this);
    var action = that.attr('action');
    var method = that.attr('method');
    var data = {};

    that.find('[name]').each(function(index, value){
        var that = $(this);
        var name= that.attr('name');
        var value= that.val();

        data[name] = value;
    });
    $.ajax({
        url: action,
        type: method,
        data: data,
        success: function(response){
            $('#form1 .contact-message1').html(response);
	    $('#form1 input, #form1 select').attr('disabled', false);
	    $('#form1').trigger('reset');
        }
    });
    return false;
});

@rahuls360
Copy link
Author

Add form submit message

.contact-message1 {
color: orange;
font-weight: 700;
font-size: 20px;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment