<div class="col" style="border-right:none; color: #FFFFFF;">
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<span>
<span class="style2">Enter you email here</span>:
</span>
<input name="email" type="email" id="email" required/>
<input type="submit" value="subscribe" class="submit" style="height:30px;"/>
<?php
if($_POST['email']!="")
{
mysql_connect("localhost","","");
mysql_select_db("");
error_reporting(E_ALL && ~E_NOTICE);
$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
if(!$sql)
die(mysql_error());
mysql_close();
}
?>
</form>
</div>
After the user got subscribed, I want to replace my subscription form and display the echo statement.
This code is running totally fine and is very good too; just want some more advantage with it.. ..
it shows like this
But i want to show it like this
my code now
<div class="col" style="border-right:none; color: #FFFFFF;">
<script>
var form = $('#form1');
$.ajax{
type:form.attr('method'),
url:form.attr('action'),
data:$("#form1").serialize(),
success: function(data){
if(data=="You have been successfully subscribed."){
$(".col").html("<div>Welcome</div>")
}
}
</script>
<form id="form1" method="post" action="index.php">
<span><span class="style2">Enter you email here</span>:</span>
<input name="email" type="email" id="email" required/>
<input type="submit" value="subscribe" class="submit" style="height:30px;"/>
<?php
if($_POST['email']!="")
{
mysql_connect("localhost","","");
mysql_select_db("");
error_reporting(E_ALL && ~E_NOTICE);
$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
if(!$sql)
die(mysql_error());
mysql_close();
}
?>
</form>
</div>
The ajax is used as agent between html and php, The details entered in html form is supplied to php through ajax and the result obtained from php is sent back through ajax.This can be done by php itself, but the use of ajax create a non-flickering page i.e a portion of webpage is updated without a full request.
var form = $('#form1');
$.ajax{
type:form.attr('method'),
url:form.attr('action'),
data:$("#form1").serialize(),
success: function(data){
if(data=="You have been successfully subscribed."){
$(".col").html("<div>Welcome</div>")
}
}
HTML code:
<HTML>
<BODY>
<div class="col">
<form id="form1" action="index.php" method="POST">
<input name="email" type="email" id="email" required/>
<input type="submit" value="subscribe" class="submit" style="height:30px;"/>
</form>
</div>
</body>
</html>
Update ajax code
var form = $('#form1');
$.ajax{
type:form.attr('method'),
url:form.attr('action'),
data:$("#form1").serialize(),
success: function(data){
if(data=="You have been successfully subscribed."){
$(".col").html("<div>Welcome</div>")
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
}
edit your php code like this;
if($result){
<script>
$(".class").hide(); // get input class name
</script>
echo "You have been successfully subscribed.";
}
after you submit the ajax you can simply hide the email input and button
$("#email").hide();
==========================================
<form id="form-search" method="post" onsubmit="return myFunction()" action="<?php echo $_SERVER['PHP_SELF'];?>">
then somewhere in your page
<script>
function myFunction(){
$("#email").hide();
$(".style2").hide();
$(".submit").hide();
return true;
}
</script>
Related
I have the following HTML form in signup.php:
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
I am trying to submit the form using ajax, without page refresh:
<!-- include files -->
<?php include 'assets/config.php';?>
<?php if(isset($_SESSION["CUSTOMER_ID"])){
header('Location: myaccount.php'); } ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('assets/login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
I am posting the form to do_signup_check.php and running a query to see if the user is already registered. echo 1 for a positive result and 0 for a negative result:
Do_Signup_Check.php:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn)); }
if(mysqli_num_rows($check) > 0){
echo '1';
}else{
echo '0';
}
?>
If the result is 0 then the ajax should load my page do_signup.php.
But alas it is not getting this far. It was working and then i switched off the computer and came back to it and now it won't work.
Please can someone show me where I've gone wrong?
if(result == 0){ here result is not using in success function:
you must need to pass resultant variable here:
success: function () {
as:
success: function (result) {
Now, you can use your condition if(result == 0){
Second, i suggest you to pass dataType: 'html' in your ajax request.
Edit:
You are using <?php if(isset($_SESSION["CUSTOMER_ID"])){ line in your code, if you are not using session_start() in your code then this check will not work.
For this line data:{"name":name,"email":email}, i didnt see name and email in your code, where you define these 2 variables which you are using in your ajax params.
i am troubleshooting with update row using AJAX. When i click submit button, the value of poke increases +1 and i need it to update in DB also. Everything needs to work with AJAX.
Currently my code works only +1 to poke input with ajax but DB row still not updating.
HTML:
<?php
$result = $mysqli->query("SELECT * FROM users") or die($mysqli->error);
while ($users = $result->fetch_assoc()) {
?>
<form class="table" name="table" id="table" method="post" enctype="multipart/form-data" autocomplete="off" data-counter="<?php echo $users['id']?>">
<div class="Table-row" id="table">
<div class="Table-row-item" data-header="Header1"><input class="clear" type="text" name="first_name" id="first_name" value="<?php echo $users['first_name'] ?>"></div>
<div class="Table-row-item" data-header="Header2"><input class="clear" type="text" name="last_name" id="last_name" value="<?php echo $users['last_name'] ?>"></div>
<div class="Table-row-item" data-header="Header3"><input class="clear" type="text" name="email" id="email_<?php echo $users['email']?>" value="<?php echo $users['email'] ?>"></div>
<div class="Table-row-item" data-header="Header4"><input class="clear" type="text" name="poke" id="poke_<?php echo $users['id']?>" value="<?php echo $users['poke']?>"></div>
<div class="Table-row-item" data-header="Header5"><input class="poke" type="submit" value="Poke" id="submit" name="submit"></div>
<input class="clear" type="hidden" id="hidden" name="hidden" value="<?php echo $users['email']?>">
</div>
</form>
<?php
} ?>
PHP:
<?php
require 'db.php';
if (isset($_POST['submit'])) {
$poke = $mysqli->escape_string($_POST['poke']);
$email = $mysqli->escape_string($_POST['email']);
$mysqli->query("UPDATE users SET poke='$poke' WHERE email='$email'") or die($mysqli->error);
}
AJAX:
$(document).ready(function () {
$('form').on('submit', function (e) {
var id = $(this).attr('data-counter');
e.preventDefault();
$.ajax({
type: "post",
data: $(this).serialize(),
url: "update.php",
success: function () {
var counter = parseInt($("#poke_"+id).val()); // Use form's inner #poke
counter++;
$("#poke_"+id).val(counter);
alert("form was submited on: " + id);
}
});
return false;
});
});
Not enough info. You need to do more diagnostics.
E.g: Dump the SQL statement to the output so you can check it is what you expect it to be.
And run the SQL in, e.g. phpAdmin to check if it updates.
You may have a problem in the email string, which could be caused by, say, different character encodings between AJAX and the DB. Probably both should use UTF8.
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.
I'm new to jQuery and I keep getting undefined as data when I submit the form. I looked online and tried serialize(), the $.ajax function, $.post function, amongst other methods to no avail.
I'm trying to accomplish a form submit without a page refresh. The code works fine if I comment out the script to remain on the page after form submission.
index2.php
<script>
function newlock() {
$("#new-lock").load("new-lock.php");
}
</script>
<h3>Lock Settings</h3>
<div>
New Lock
</div>
//code in between
<div id="tabs-1">
<div id="new-lock"></div>
</div>
insert_new_lock.php
require "connect.php";
$name = $_POST['name'];
echo $name;
$IP = $_POST['IP'];
echo $name;
$sql="INSERT INTO door_lock (lock_IP, lock_name)
VALUES
('$name','$IP')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
mysql_close($conn);
?>
new-lock.php
<!doctype html>
<html lang="us">
<h2 align = "center"> Please enter information for the new lock </h2>
<table border="0" align= "center">
<form id="newlockform" action="insert_new_lock.php" method="post">
<tr><td>Lock Name:</td> <td><input type="text" name="name"></td></tr>
<tr><td>Lock IP:</td> <td><input type="text" name="IP"></td></tr>
<tr><td><input type="reset" value="Clear"> <input type="submit" name="submitted" value="Submit"></td></tr>
</form>
</table>
</html>
<script>
$("#newlockform").submit(function() {
var name = $("#name").val();
var IP = $("#IP").val();
var dataString = 'name=' + name + '&IP=' +IP;
$.post('insert_new_lock.php', dataString, function(data) {
$("#tabs-1").html(data).fadeIn('100');
$('#name,#IP').val('');
}, 'text');
return false;
});
</script>
Any help would be appreciated! :D
You do not have any id set on your form fields, so
var name = $("#name").val();
is going to return null, which you then submit as an empty string. The form fields should loo like
<input type="text" name="whatever" id="name" />
^^^^^^^^^^^
for your JS code to work.
I'd like to submit a form thanks to AJAX and display the error messages contained in "form_treatment.php" (form verification) without the php redirection to "form_treatment.php" when I submit. What have I to write in the following lign ?
$.post("form_treatment.php",name, ???);
I have a basic form in form.php :
<form method="post" action="form_treatment.php" >
<input type="text" name="user_name" value="Your name..." />
<button type="submit" >OK</button>
</form>
This form is treat in form_treatment.php :
if ( empty($_POST['user_name']) ){
echo 'You have to enter your name.';
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
echo 'Name already used.';
} else {
// Entering the name in the DB
}
}
You can try something like the following:
<form id="myForm" method="post" action="form_treatment.php" >
<span id="message"></span>
<input type="text" name="user_name" value="Your name..." />
<input type="submit" >OK</button>
</form>
And the javascript:
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
$('#message').html(data);
}
});
return false;
});
You can accomplish this by two ways
1st One in the same page
2nd one via AJAX
The first way can be done like this
<?php
if(isset($_POST['sub']) && $_POST['sub'] == 'true'):
if ( empty($_POST['user_name']) ){
echo 'You have to enter your name.';
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
echo 'Name already used.';
} else {
// Entering the name in the DB
}
}
endif;
?>
<form method="post" action="<?php echo $PHP_SELF; ?>" >
<input type="text" name="user_name" value="Your name..." />
<input type="hidden" name="sub" value = "true" >
<button type="submit" >OK</button>
</form>
The 2nd way via ajax
can be done like this
<div id="errors"></div>
<form method="post" id="myFrm">
<input type="text" name="user_name" value="Your name..." id="name" />
<button type="submit" >OK</button>
</form>
<sctipt>
$("#myFrm").submit(function() {
var NameFromForm = $('#name').val();
$.post("form_treatment.php", { "user_name": NameFromForm },
function(data){
$("#errors").html(data);
});
event.preventDefault();
});
</script>
If you need any explanation leave a comment