Goal: I want to Hide "myForm" div when data successfully post to the database and the "section" div will show component when submit button will clicked, its working properly.
Problem / Requirement: Problem is that data not posting to the database, how can i solve this problem to save data to the database and show / hide div after that database operation.
Note: I don't want to reload my page.
HTML Code:
<div id="section" style="display: none;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate culpa reprehenderit animi,
numquam distinctio repellendus debitis fugit unde consequatur eum magni illo minima amet quidem omnis veniam
commodi voluptatum!
</p>
</div>
<div id="myForm">
<form id="testForm" method="post" action="#">
<input id="form_name" type="text" name="name" class="form-control">
<input type="submit" name="submit" class="btn btn-send" value="submit">
</form>
</div>
JavaScript Code:
const sectionDiv = document.getElementById('section');
const form = document.getElementById('myForm');
form.addEventListener('submit', function (e) {
e.preventDefault();
// Please suggest the flow and code for call PHP script from here
form.style.display = 'none';
sectionDiv.style.display = 'block';
});
Please suggest flow and process in above Javascript code for how to pass my data to below PHP script..
PHP Code:
include("db.php");
if (isset($_POST['submit']))
{
$form_name= $_POST['name'];
$query = "INSERT INTO `test` (`xxname`) VALUES ('$form_name')";
if(mysqli_query($conn, $query))
{
echo "asdfghjkl";
}
else
{
echo "ERROR: Could not able to execute $query. " . mysqli_error($conn);
}
}
Thanks for your help in advance..
You have to pass your client request to server side through AJAX, call your server script using AJAX from your javascript code function:
const sectionDiv = document.getElementById('section');
const form = document.getElementById('myForm');
form.addEventListener('submit', function (e) {
e.preventDefault();
let serData = form[0].serialize();
// Add your AJAX Code here
$.ajax({
url: "/form.php", // your PHP script's file name
type: "post",
data: serData, // pass your fields here
success: function(data){
// do your actions here
// you can put your condition here like if( data.status == true ) then success other wise failure
form.style.display = 'none';
sectionDiv.style.display = 'block';
},
error: function (request, status, error) {
// console your error here
console.log(error);
}
});
});
You are using pure javascript. You can send post request to server by using XMLHttpRequest.
form.addEventListener('submit', function (e) {
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", '/your-request-path', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
form.style.display = 'none';
sectionDiv.style.display = 'block';
}
}
xhr.send("your form data");
});
For reference xmlhttprequest you may visit https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send this url.
`$(document).ready(function(){
var data = $('.testForm').serialize();
$(".btn-send").click(function(){
$.ajax({
url: "write path here where you insert data to database",
data: data,
success: function(response){
// write code what you want if operation succes
}});
});
});`
Using the fetch
api for simplicity and brevity - an example piece of code that will make a POST request to the server ( in this instance the same page but change location.href
for the correct endpoint / url ) and use the callback
to perform the DOM manipulation.
The PHP at the top here is to emulate YOUR database insert - you would be advised however to use a prepared statement
rather than embedding user content directly in the SQL as this leaves you vulnerable to SQL Injection.
<?php
# include scripts
require 'db.php';
/*
The PHP endpoint that handles the database insert.
For the purposes of this example it is on the same
page as the HTML form but can as easily be a different
script.
*/
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/*
Only process this piece if there is a POST request with
a particular parameter present in the request. Note that
it makes more sense to test that the parameter that will
be used in any database operations is present as opposed
to the `submit` button which is commonly used for such a
test but serves no purpose beyond this point so is redundant.
*/
if( isset( $_POST['name'] ) ){
/*
As this is an AJAX request we are only interested in
content generated in this piece of code. Anything that
was generated before or after should be discarded.
*/
ob_flush();
/*
Create a "Prepared Statement" to allow the user
supplied data to be handled in a safe manner. Note
that you should not use `mysqli_real_escape_string`
*/
$sql='insert into `test` ( `xxname` ) values ( ? )';
$stmt=$db->prepare( $sql );
/*
The return value from the `prepare` method is a Boolean
so you are able to use that value to "Fork" the program
logic.
*/
if( $stmt ){
/*
The prepared statement has been created by the server
so now you can assign values to the placeholders. This
is done using `bind_param`
Different types of variable can be bound using a different
`type` argument
> i - integers
> s - strings
> d - double
> b - boolean
*/
$stmt->bind_param( 's', $_POST['name'] );
/*
With the variable bound to the placeholder
you can now commit the data to the db
*/
$result=$stmt->execute();
$rows=$stmt->affected_rows;
/*
The return value from `execute` is a boolean.
It will be false if, for some reason, the db
failed to process the request.
To determine if the request succeeded you can use
a combination of $result & $rows if you wish and
inform the user with an appropriate response.
*/
$response = $result && $rows==1 ? 'Whoohoo! Record added - ya dancer!' : 'ERROR: Could not insert record';
exit( $response );
}else{
/*
If you get here it often suggests a syntax error in
the sql. You could use $stmt->error to aid analysis
but not in production code.
*/
exit('bogus');
}
}
/* To prevent the whole page appearing in the AJAX response */
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Submit Form data and hide form</title>
</head>
<body>
<!-- slightly streamlined version of original HTML markup. -->
<div style='display:none;'>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate culpa reprehenderit animi,
numquam distinctio repellendus debitis fugit unde consequatur eum magni illo minima amet quidem omnis veniam
commodi voluptatum!
</p>
</div>
<div>
<form method='post'>
<input type='text' name='name' />
<input type='submit' />
</form>
</div>
<script>
/*
Bind an event handler to the submit ( or regular ) button to fire
an AJAX request to the PHP server.
Binding a FORM with the `submit` event requires a different approach
to that shown in the question. The callback function or event handler
needs to return a boolean and the form will only be submitted if the
function evaluates to true. Hence better binding to the button as we
do not want to send the form in the traditional sense - we need to
fashion our own request without reloading the page.
*/
document.querySelector('form > input[type="submit"]').addEventListener('click', function(e){
// Prevent the form being submitted.
e.preventDefault();
/*
using parent and sibling selectors we can identify
the required DOM elements that will be used in the
show/hide operations.
*/
let container=this.parentNode.parentNode;
let div=container.previousElementSibling;
/*
The `Fetch` api was developed to provide greater
flexibility than the more commonly used `XMLHttpRequest`
which has become the workhorse of many web applications.
To explain it fully you should study the documentation on
MDN - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Google - https://developers.google.com/web/updates/2015/03/introduction-to-fetch
Another little gem is the `FormData` object used here.
MDN - https://developer.mozilla.org/en-US/docs/Web/API/FormData
The fetch call sends the request in this case to the same page ( location.href )
and has various configuration options set - method and body being of interest.
The `body` of the request is the `FormData` object which can be populated
automagically by supplying a reference to the FORM as the argument or manually
by calling the `append` method.
rtfm
*/
fetch( location.href, { method:'post',body:( new FormData( document.querySelector('form') ) ) } )
.then( response=>{ return response.text() } )
.then( text=>{
/* The server response can be read / used here */
console.info( text );
/* perform the show and hide operations... */
container.style.display='none';
div.style.display='block';
})
.catch( err=>{ alert(err) })
});
</script>
</body>
</html>
You can do it many ways. I made this very simple way using Ajax with a single php file. You need to send the data via ajax and need to catch that using PHP. You can try the below code.
Note: Please make sure you have changed the your connection name, password and db name
<!DOCTYPE html>
<html>
<head>
<title>Insert Data from html form to MySQL Database using Ajax and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="message" style="display: none;">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quibusdam quo ex pariatur aliquid vero!
Voluptatibus harum accusamus amet maiores at sit, neque magni nulla ut optio quis culpa nisi nostrum!
</p>
</div>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" placeholder="Name" name="name" />
<input type="submit" name="save" value="Submit" id="btn-save" />
</form>
<script>
const submit = $('#btn-save').click(function (e) {
e.preventDefault();
const name = $('#name').val();
if(!name) return alert('Please enter your name');
$.ajax({
url: 'index.php',
type: 'POST',
data: { name: name },
success: function (data) {
$('.message').show();
$('#myForm').hide();
},
});
});
</script>
</body>
</html>
<?php
$conn = mysqli_connect("localhost", "root", "","mydb");
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If the form data found save and send response
if(isset($_POST['name'])){
$name=$_POST['name'];
$sql = "INSERT INTO `users`( `name`) VALUES ('$name')";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
mysqli_close($conn);
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.