Skip to content

Instantly share code, notes, and snippets.

@VoloshchenkoAl
Created June 24, 2016 07:29
Show Gist options
  • Save VoloshchenkoAl/4d85798201fed7d7fdadf344481dca8d to your computer and use it in GitHub Desktop.
Save VoloshchenkoAl/4d85798201fed7d7fdadf344481dca8d to your computer and use it in GitHub Desktop.
<?php
if(isset($_POST) && is_array($_POST) && count($_POST) > 0){
$ajaxResp = [];
if(isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$ajaxResp['status'] = 1;
$ajaxResp['email'] = $_POST['email'];
echo json_encode($ajaxResp);
} else {
$ajaxResp['status'] = 0;
$ajaxResp['error'] = "very bad!";
echo json_encode($ajaxResp);
}
header('Content-Type: application/json');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<form action="" id="myFirstOwnFormWithAJAXRequest">
<p><input type="text" id="myFirstOwnFormWithAJAXEmail" name="email" placeholder = "email"></p>
<p><input type="submit" id="myFirstOwnFormWithAJAXSubmit" value="sent request"></p>
</form>
<script>
var sendingDateFromform = function(e){
var inputEmail = $('#myFirstOwnFormWithAJAXEmail');
var inputEmailVal = inputEmail.val();
try{
if(typeof inputEmailVal === 'string' && inputEmailVal.length > 0){
$.post('/', $(this).serializeArray())
.done(function(data){
if( typeof data == 'object' ){
var formAjax = $('#myFirstOwnFormWithAJAXRequest');
if(data.status == 1){
formAjax.empty();
formAjax.prepend("<div>" + data.email + "</div>")
} else{
alert(data.error);
}
} else{
console.log("problems with BK");
}
})
.fail(function(er){console.log(er)});
} else{
alert("Your form looks like open space");
}
}catch(er){console.log(er);}
e.preventDefault();
};
$(document).ready(function(){
$('#myFirstOwnFormWithAJAXRequest').submit(sendingDateFromform);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment