php - sending forum in background without page reload -
i have php forum sends information database , sends page stuck little problem. when submit forum page reloads. don't want. accomplish need forum reload in background. have looked way none of them me task. here code bellow.
//this php file runs fourm <?php header("location: localhost:8888"); $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "mydb"; // create connection $conn = new mysqli($servername, $username, $password, $dbname); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } $value = $_post['firstname']; $sql = "insert myguests (firstname) values ('$value')"; if ($conn->query($sql) === true) { echo "<a href=https://twitter.com/angela_bradley>my twitter</a>"; } else { echo "error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?> //this fourm <form action="demo.php" method="post" /> <p>input 1: <input type="text" name="firstname" /></p> <input type="submit" value="submit" /> </form>
try move insert query code separate file. lets example register.php
, should return simple text success else error message. in way, can check data in ajax success callback.
$servername = "localhost"; $username = "root"; $password = "root"; $dbname = "mydb"; // create connection $conn = new mysqli($servername, $username, $password, $dbname); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } $value = $_post['firstname']; $sql = "insert myguests (firstname) values ('$value')"; if ($conn->query($sql) === true) { echo "success"; } else { echo "error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
if want return json, can update php code below.
header('content-type: application/json'); if ($conn->query($sql) === true) { $message = "success"; } else { $message = "error: " . $sql . "<br>" . $conn->error; } $result = '{"message": ' + $message + '}'; echo json_encode($result);
add id form identify through dom
<form id="target" action="demo.php" method="post" /> <p>input 1: <input type="text" name="firstname" /></p> <input id="submit" type="submit" value="submit" /> </form>
using $.submit
triggered when user submit , json data generated using serialize
, $.post
ajax post.
add before body end surrounded script tag
<script type="text/javascript"> $( "#target" ).submit(function( event ) { event.preventdefault(); var jqxhr = $.post( "register.php", $(this).serialize(), function(data) { alert( "success" ); }) .done(function() { alert( "second success" ); }) .fail(function() { alert( "error" ); }) .always(function() { alert( "finished" ); }); }); </script>
reference: http://api.jquery.com/jquery.post/
Comments
Post a Comment