Skip to content

Instantly share code, notes, and snippets.

@rashivkp
Created September 11, 2016 19:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rashivkp/ef581ea4f4d4e7fba90086ea2c6bb5d2 to your computer and use it in GitHub Desktop.
Save rashivkp/ef581ea4f4d4e7fba90086ea2c6bb5d2 to your computer and use it in GitHub Desktop.
php ajax sample json response
<?php
if (isset($_POST['name'])) {
header('Content-type: application/json');
if ($_POST['name'] != 'hi') {
$array = ['result' => 'fail', 'data' => '100'];
} else {
$array = ['result' => 'success', 'data' => '100'];
}
die(json_encode($array));
}
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<form action="" method="post">
<input type="text" name='name' value='hi'>
<input type="submit" name='apply' value='submit'>
<div id="thankyou_message" style="display:none">Success</div>
</form>
<script type="text/javascript">
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (response) {
console.log(response);
if(response.result == 'success') {
document.getElementById("thankyou_message").style.display = "inline";
} else {
document.getElementById("thankyou_message").style.display = "none";
}
}
});
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment