I have an admin panel where I have an option to add a user into database. I made a script so when you click the Add User link it will load the form where you can introduce the user infos. The thing is, I want to load in the same page the code that is run when the form is submited.
Here's the js function that loads the file:
$( ".add" ).on( "click", function() {
$(".add-user-content").load("add-user-form.php")
});
and here's the php form
<form id="formID" action="add-user-form.php" method="post">
<p>Add Blog Administrator:</p>
<input type="text" name="admin-user" value="" placeholder="username" id="username"><br>
<input type="password" name="admin-pass" value="" placeholder="password" id="password"><br>
<input type="email" name="admin-email" value="" placeholder="email" id="email"><br>
<input type="submit" name="add-user" value="Add User">
</form>
<?php
include '../config.php';
$tbl_name="blog_members"; // Table name
if(isset($_POST['add-user'])){
$adminuser = $_POST['admin-user'];
$adminpass = $_POST['admin-pass'];
$adminemail = $_POST['admin-email'];
$sql="INSERT INTO $tbl_name (username,password,email) VALUES('$adminuser','$adminpass','$adminemail')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
}
?>
Maybe I was not that clear, I want this code
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
to be outputted in the same page where I loaded the form because right now it takes me to the add-user-form.php when I click the submit button.
Thanks for your help!
if you do this the code will be redirected on post to your page:
<form name="formID" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
you should add a validation so it doest show the form if you receive $_POST['add-user']
You have to submit your for via ajax.
Alternatively you don't need to load form html, just hide the form and on add user button click show the form.
Check this code. Hope that helps you :-
// Add User Button
<div class="color-quantity not-selected-inputs">
<button class="add_user">Add User</button>
</div>
// Append form here
<div class="add_user_form"></div>
// for posting response here
<div class="result"></div>
Script for processing form and appending user form
<script>
$(function(){
$( ".add_user" ).on( "click", function() {
$(".add_user_form").load("form.php")
});
$(document).on("submit","#formID", function(ev){
var data = $(this).serialize();
console.log(data);
$.post('handler.php',data,function(resposne){
$('.result').html(resposne);
});
ev.preventDefault();
});
});
</script>
form.php
<form id="formID" action="" method="post">
<p>Add Blog Administrator:</p>
<input type="text" name="admin-user" value="" placeholder="username" id="username"><br>
<input type="password" name="admin-pass" value="" placeholder="password" id="password"><br>
<input type="email" name="admin-email" value="" placeholder="email" id="email"><br>
<input type="submit" name="add-user" value="Add User">
</form>
handler.php
<?php
include '../config.php';
$tbl_name="blog_members"; // Table name
if(isset($_POST['add-user'])){
$adminuser = $_POST['admin-user'];
$adminpass = $_POST['admin-pass'];
$adminemail = $_POST['admin-email'];
$sql="INSERT INTO $tbl_name (username,password,email) VALUES('$adminuser','$adminpass','$adminemail')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
die;
}
?>
What you are looking for is to submit the form using AJAX rather than HTML.
Using the answer Submit a form using jQuery by tvanfosson
I would replace your
<input type="submit" name="add-user" value="Add User">
with
<button id="add-user-submit">Add User</button>
and then register an onClick-handler with
$( "#add-user-submit" ).on( "click", function() {
$.ajax({
url: 'add-user-form.php',
type: 'post',
data: $('form#formID').serialize(),
success: function(data) {
$(".add-user-content").append(data);
}
});
});
to add the actual submit functionality.
Related
I have a page with a POST form, when I submit the form the details are updated in a database.
And I have another page where I use AJAX TAB, which means I load the first page with AJAX, when I do this and use the Form, the details are not updated in the database.
I would appreciate help.
<?php
if( isset($_POST['newcst']) )
{
/*client add*/
//getting post from user add form
$c_name = $_POST['c_name'];
$c_adress = $_POST['c_adress'];
$c_idnum = $_POST['c_idnum'];
$c_phone = $_POST['c_phone'];
$c_mail = $_POST['c_mail'];
echo $c_num;
//insert client into SQL
$wpdb->insert('se_clients',array(
'c_name' => $c_name,
'c_adress' => $c_adress,
'user_id'=>$cur_id,
'c_num'=>$c_idnum,
'c_phone'=>$c_phone,
'c_mail'=>$c_mail,
));
}
?>
<html>
</head>
<body>
<div id="newcst">
<form action="" method="post">
<label>Full name:</label>
<input type='text' name='c_name' /><br><br>
<label>ID: </label>
<input type='text' name='c_idnum' /><br><br>
<label>PHONE:</label>
<input type='text' name='c_phone' /><br><br>
<label>ADRESS: </label>
<input type='text' name='c_adress' /><br><br>
<label>EMAIL: </label>
<input type='text' name='c_mail' /><br><br>
<input name="newcst" type="submit" value="create">
</form>
</div>
</body>
</html>
Ajax tab:
$(document).ready(function() {
$("#nav li a").click(function() {
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$("#nav li a").removeClass('current');
$(this).addClass('current');
$.ajax({ url: this.href, success: function(html) {
$("#ajax-content").empty().append(html);
}
});
return false;
});
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$.ajax({ url: 'invoice', success: function(html) {
$("#ajax-content").empty().append(html);
}
});
});
hover(), click(), bind(), on() and others works only after reloading page.
So you can use live()
or
$(document).on('click', 'element', function () {
...
});
I found the solution, you need to add the PHP code that is responsible for entering data to the database on the main page that contains the AJAX and not the page with the form itself.
My problem is that after clicking on submit button the page will go to php file any way my html code is like this
<form action="register.php" method="post">
<input type="text" name="name" id="name"><div id="adiv"></div>
<input type="submit" value="submit" id="button">
</form>
and my jquery code goes like this
$('#name').focusout(function(){
if($('#name').val().length==0){
$('#adiv').html("please enter name")
}
});
$('#button').click(function(){
if($('#name').val().length==0){
$('#adiv').html("please enter your name")
}
});
but after clicking submit button it redirects to php file and doesn't show any error and store blank data in the database.
Because your input type is submit you can either change the type to button or add event.preventDefault() to avoid automatic passing of form
use event.preventDefault()
$('#button').click(function(e) {
e.preventDefault();//this will stop form auto submit thus showing your error
if ($('#name').val().length == 0) {
$('#adiv').html("please enter your name")
}
});
Or
<input type="submit" value="submit" id="button">
change to
<input type="button" value="submit" id="button">//also prevent form auto submit thus will show the error
Well you need to stop the code to execute after error has been detected. For example you can simple use return false or return:
$('#name').focusout(function() {
if ($('#name').val().length == 0) {
$('#adiv').html("please enter name")
}
});
$('#button').click(function() {
if ($('#name').val().length == 0) {
$('#adiv').html("please enter your name")
return false;//add this
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="register.php" method="post">
<input type="text" name="name" id="name">
<div id="adiv"></div>
<input type="submit" value="submit" id="button">
</form>
I strongly recommend never to assign validation to a submit button click.
Instead assign the submit event handler of the form.
I also added trim and removed the content of the error from the code.
$(function() {
$('#name').focusout(function() {
var empty = $.trim($('#name').val()).length == 0;
$('#adiv').toggle(empty);
});
$('#form1').on("submit",function(e) {
$('#name').focusout();
if ($('#adiv').is(":visible")) {
e.preventDefault()
}
});
});
#adiv { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="register.php" method="post" id="form1">
<input type="text" name="name" id="name">
<div id="adiv">please enter name</div><br/>
<input type="submit" value="submit" id="button">
</form>
Please check this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<input type="text" name="name" id="name">
<div id="adiv"></div>
<input type="button" value="submit" id="button">
</form>
<script>
$(document).ready(function(){
$('#button').on('click',function(){
if($('#name').val() == ''){
$('#adiv').text("Please enter name!!");
}else{
$('#adiv').text($('#name').val());
}
})
})
</script>
try this..:D
function validateFunction(){
if(document.getElementByID('name').value.length==0){
document.getElementByID('adiv').innerHTML = "please enter your name";
return false;
}
return true;
}
<input type="submit" value="submit" id="button" onclick="return validateFunction();" />
$('your-form').on('submit', function(e) {
e.preventDefault();
//your code bere
});
preventDefault stop the normal submit behaviour of your browser so that you can trigger any event you want
I have a form for user to update their info using jquery + Ajax. Everything is working great so far, but WHen i change input type="email" to input type="text" in the fullname section of the form and click update. It got error??? It won't run the php file in ajax. I don't see any connection which causes this error? Anyone please sugguest why? But if I change input type in the fullname section back to "email". It works! This is so weird!
Here is my form:
<div id="changeuserinfo_result"></div>
<form role="form" method="post">
<div class="form-group">
<label>Fullname</label>
<input type="text" class="form-control" id="changename" name="changename" value="<?php echo $_SESSION['name'] ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="changepass" name="changepass" value="<?php echo $_SESSION['pass'] ?>">
</div>
<button class="btn btn-default" id="changeuserinfo">Update</button>
</form>
Here is my jquery code:
$(document).ready(function(){
$('#changename').focus();
$('#changeuserinfo').click(function(){
var changename = $('#changename');
var changepass = $('#changepass');
var changeuserinfo_result = $('#changeuserinfo_result');
changeuserinfo_result.html('loading...');
if(changename.val() == ''){
changename.focus();
changeuserinfo_result.html('<span class="errorss"> * Empty fullname</span>');
return false;
}
else if(changepass.val() == ''){
changepass.focus();
changeuserinfo_result.html('<span class="errorss">* Empty password</span>');
return false;
}
else {
var UrlToPass = {changename:changename.val(),changepass:changepass.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'changeuserinfo.php',
success: function(responseText){
if(responseText == 1){
$('#changeuserinfo_result').html('<span style="color:green"> Update OK</span>');
}
else{
$('#changeuserinfo_result').html('<span class="errorss"> Update fail. Try again</span>');
}
}
});
}
});
});
You have no closing tags on your inputs.
It should be <input type="text"... />
Also set the doctype of the page to HTML5.
<!DOCTYPE HTML>
....
</html>
I can't submit the form after disable the submit button.
I make a jquery code to prevent multiple submit it's work but the form doesn't send the POST request.
jQuery:
$(document).ready(function() {
var enblereg = function(e) {
$(e).removeAttr("disabled");
}
$("#goRegister").click(function() {
$(this.form).submit();
var reg = this;
$('#reg').submit();
$(this).attr("disabled", true);
setTimeout(function() { enblereg(reg) }, 2000);
});
});
php:
<?php if (isset($_POST['goRegister'])) { echo "send";} ?>
<form action="?" method="POST" id="reg">
<h6>Full Name: <?php echo $fnamerr; ?></h6>
<input type="text" name="fname" value="<?php echo $fullname;?>">
<h6>Email: <?php echo $emailerr; ?></h6>
<input type="text" name="email" value="<?php echo $email;?>">
<h6>Re-enter Email: <?php echo $aemailerr; ?></h6>
<input type="text" name="aemail" value="<?php echo $aemail;?>">
<h6>password: <?php echo $passworderr; ?></h6>
<input type="password" name="password">
<h6>Re-enter password: <?php echo $apassworderr; ?></h6>
<input type="password" name="apassword">
<h6>Birthday: <?php echo $bdayerr;?></h6>
<?php include ("/incs/birthdayinc.php");?>
<h6>Gender: <?php echo $gendererr; ?></h6>
<input type="radio" name="gender" value="female"><font size="1"><b>Female</b></font>
<input type="radio" name="gender" value="male"><font size="1"><b>Male</b></font><br>
<input type="submit" name="goRegister" id="goRegister" value="Register">
</form>
without the jQuery the post work, I tried to solve it with "ONCLICK":
this.form.submit() - doesn't work
what should I need to add in jQuery to submit the form before disable the submit button ?
I think the jQuery code for the process would be like this
$(this.form).submit();
This would submit the form for you. If it doesn't actually trigger the event. Then you can capture the form and submit it directly using the id of it.
id="reg"
So, it would be
$('#reg').submit();
Do this... The form has id of #reg. So simply use $('#reg').submit();
$("#goRegister").click(function() {
var reg = this;
$('#reg').submit();
$(this).attr("disabled", true);
setTimeout(function() { enblereg(reg) }, 2000);
});
EDIT
Updated for ajax submit
$("#goRegister").click(function() {
var reg = $(this);
var form = $('#reg').serialize();
var url = "Whereveryouareposting.php";
//Submit ajax form
$.post(url,form,function(data){
//This is where you could send back error messages or success from the server
// To dictate wether to hide the button, or display errors.
// Ie On success....do this...
$(this).attr("disabled", true);
setTimeout(function() { enblereg(reg) }, 2000);
// On error, send a message packet with the errors, and loop through it to attach error
//messages to fields
});
});
I created login from that when clicking submit button sends variables to login_success.php page.but I want to make that when I click submit button login form will be close. I can close form using Jquery
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".loginform").hide();
});
});
</script>
But this time form does not sends request to .php file. I made it like addin script to .php file and then redirected to index.html site.It also good but I can see reflection.How can I combine them?
this is my form
<div class="loginform">
<form action="php/login.php" method="post" id="login">
<fieldset class="loginfield">
<div>
<label for="username">User Name</label> <input type="text" id="username" name="username">
</div>
<div>
<label for="password">Password</label> <input type="password" id="password" name="password">
</div>
</fieldset>
<button type="submit" id="submit-go" ></button>
</form>
</div>
Edit
I used function as NAVEED sad .I installed FireBug in firefox and I can see that my form validation works normal.It sends and request to login.php But I cant make any change on my form.It does not close or $arr values not shown on div tags.
You should use JSON/AJAX combination:
Downlod jQuery
If your form look like this:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<div id='errors'></div>
<div class='loginform' id='loginform'>
<form action="php/login.php" method="post" id="login">
Username:<input type="text" id="username" name="username">
Password:<input type="password" id="password" name="password">
<button type="submit" id="submit-go" value='Login'></button>
</form>
</div>
Your jQuery Code in ajax.js file to submit the form and then get data from 'php/login.php' in JSON and fill the required DIVs. If login is id of the form.
jQuery('#login').live('submit',function(event) {
$.ajax({
url: 'php/login.php',
type: 'POST',
dataType: 'json',
data: $('#login').serialize(),
success: function( data ) {
for(var id in data) {
jQuery('#' + id).html(data[id]);
}
}
});
return false;
});
your login.php file as described in form action attribute:
$username = $_POST['username'];
$password = $_POST['password'];
if( $username and $password found in database ) {
// It will replace only id='loginform' DIV content
// and login form will disappear
$arr = array ( "loginform" => "you are logged in" );
} else {
// It will replace only id='errors' DIV content
$arr = array ( "errors" => "You are not authenticated. Please try again" );
}
echo json_encode( $arr );
More Detail:
How to submit a form in ajax/json:
General jquery function for all forms
Try submit method
$("button").click(function(){
$("form.loginform").submit().hide();
});
PS You do know that applying onclick handler to all <button> elements on the page is bad idea, right?
$(document).ready(function(){
$("button").click(function(){
$(".loginform").hide();
return false;
});
});