-
-
Save joaomosantos/814f0105ef8c70d0f350805ff583c054 to your computer and use it in GitHub Desktop.
PHP+AJAX+RETURN(JSON)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function() { | |
$("#myform").submit(function() { | |
$.ajax({ | |
method: "post", | |
dataType: "json", | |
url: "home.php", | |
data: $("#myform").serialize(), | |
success: function(data) { | |
console.log(data); | |
} | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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