Skip to content

Instantly share code, notes, and snippets.

@joaomosantos
Created August 15, 2017 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joaomosantos/814f0105ef8c70d0f350805ff583c054 to your computer and use it in GitHub Desktop.
Save joaomosantos/814f0105ef8c70d0f350805ff583c054 to your computer and use it in GitHub Desktop.
PHP+AJAX+RETURN(JSON)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form id="myform" method="post">
<input type="text" id="nome" name="nome" placeholder="nome">
<input type="submit" value="enviar">
</form>
<script src="js/vendor/jquery-2.2.4.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
$(function() {
$("#myform").submit(function() {
$.ajax({
method: "post",
dataType: "json",
url: "home.php",
data: $("#myform").serialize(),
success: function(data) {
console.log(data);
}
});
});
});
<?php
$array = array("mensagem" => null, "retorno" => false);
try {
$conn = new PDO("mysql:host=localhost;dbname=ajax", "root", "");
$conn -> exec("set names utf8");
} catch(PDOException $e) {
$array["mensagem"] = "Error: " . utf8_encode($e -> getMessage());
$array["retorno"] = false;
echo json_encode($array);
exit();
}
$stmt = $conn -> prepare("INSERT INTO tabela (nome) VALUES (?)");
$stmt -> bindParam(1, $_POST["nome"]);
$stmt->execute();
$array["mensagem"] = "Usuário cadastrado com sucesso!";
$array["retorno"] = true;
echo json_encode($array);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment