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.
Related
I'm getting my multiple forms using a while loop (fetch data in the database).
<form id="form" class="form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test1">
<input type="text" class="form-control" name="car_type">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>
<form id="form" class="form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test2">
<input type="text" class="form-control" name="car_type" value="test2">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>
Here's my ajax (It only works in the 1st form but the rest not working):
$(document).ready(function(){
$(".form").submit(function(e) {
e.preventDefault();
$("#buttona").html('...');
$("#buttona").attr("disabled", "disabled");
sendInfo();
});
});
Function for ajax:
function sendInfo() {
$.ajax({
type: 'POST',
url: '../process.php',
data: $(".form").serialize(),
success: function(data){
if(data == 'Success') {
$('#text_errora').html('added');
}else {
$('#text_errora').html('not aadded');
}
}
})
return false;
}
How can I set or how ajax will recognize the button I click/submit to process the form?
You don't close your <form> tag.
You use the same id twice.
You select anything with class form, not ID form.
Actually, I am amazed it works even one time.
Try this (no need to touch the JavaScript), your form should submit, but the button changing might not work (you use identical IDs there too; tip: an id has to be unique within the entire HTML DOM).
<form class="form form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test1">
<input type="text" class="form-control" name="car_type">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>
Using "this" keyword inside submit handler, you will receive a reference to the form to which the clicked button belongs.
$(document).ready(function(){
$(".form").submit(function(e) {
e.preventDefault();
var form_to_submit = this;
$("#buttona").html('...');
$("#buttona").attr("disabled", "disabled");
sendInfo(form_to_submit);
});
});
function sendInfo(form_to_submit) {
$.ajax({
type: 'POST',
url: '../process.php',
data: $(form_to_submit).serialize(),
success: function(data){
if(data == 'Success') {
$('#text_errora').html('added');
}else {
$('#text_errora').html('not aadded');
}
}
})
return false;
}
I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
I heard this is possible with ajax, but i have no idea how in this case i already tried to look on the internet..
if you have a type="submit" inside a form, it will submit the form by default. Try to use <input type="button" instead. Then you can use ajax on the button action, that will run without refreshing the page.
Here's an example of how to use ajax:
function sendAjax() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
$(".result").html(JSON.stringify(data))
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="button" onclick="sendAjax()" value="callAjax" />
<div class="result"></div>
</form>
Add
return false;
to your jQuery-function at the end. With this you can avoid the submit.
Then you need to add an ajax-function, which sends the data from your form to the php-script you already use.
This is just an example:
$.ajax({
url: "YOUR-PHP-SCRIPT"
}).done(function (content) {
// ADD HERE YOUR LOGIC FOR THE RESPONSE
}).fail(function (jqXHR, textStatus) {
alert('failed: ' + textStatus);
});
So you have to do $.ajax post request to the php. Something like this:
<script>
$('.form-control').click(function() {
$.post(url, {data}, function(result) {
footerPreview();
}, 'json');
});
</script>
So footerPreview will be called when your php returns result.
//add in javascript
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
$("button.form-control-generate").show();
}
you can create an index.php:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" id="tm">
<option val=""></option>
<option val="©">©</option>
<option val="™">™</option>
<option val="®">®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" id="cn" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit" id="generate">
Generate
</button>
</form>
<div class="output" id="output">
</div>
<script type="text/javascript">
$('#generate').on('click', function(e){
e.preventDefault();
var companyname = $('#cn').val();
var trademark = $('#tm').val();
$.ajax({
url: 'process.php',
type: 'post'.
data: {'company':companyname,'trademark':trademark},
dataType: 'JSON',
success: function(data){
$('#output').append("<div id='footer_date'>"+data.trademark + " " + data.date + " " + data.company + " </div>");
},
error: function(){
alert('Error During AJAX');
}
});
})
</script>
and the process.php:
<?php
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["company"];
$date = date("Y");
$array = array(
'trademark' => $trademark,
'company' => $company,
'date' => $date
);
echo json_encode($array);
?>
Be sure that the index.php and the process.php will be under the same folder.. ex.public_html/index.php and public_html/process.php
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.
This is my registration form located in login.html:
<form action="Registar.php" method="post">
<input type="text" name="user" placeholder="Username (Sem espaços)" maxlength="25">
<input type="text" placeholder="Email" name="email" maxlength="31"/>
<input type="text" name="nome" placeholder="Nome" maxlength="31"/>
<input type="text" name="morada" placeholder="Morada" maxlength="120"/>
<input type="hidden" name="action" value="login">
<input type="number" name="telefone" placeholder="Telefone" maxlength="15"/>
<button type="submit" class="btn btn-default" name="submit">Signup</button>
</form>
It goes to "Registar.php" and runs the verification's i want like if the fields are empty or if the username already exists and show's that verification's in a jquery dialog.
Heres my Jquery script:
function alerta(msg,link){
var dialog = $('<div>'+msg+'</div>');
$(function() {
$( dialog ).dialog({
modal: true,
buttons: {
Ok: function() {
window.location = link;
}
}
});
})
};
The thing is it shows the dialog on the blank page of "Registar.php" and since i scripted some nice styles and overlays for my jquery dialog i want to show the jquery dialog verification messages in login.html and have that page in the background/overlay of the dialog.
Is there any way to do that but still running the action form to an external php script?
Thanks in advance!
One way to achieve this would be to use AJAX instead of sending the form via POST. Here's an example:
HTML
<form id="myForm" action="" method="post">
//your form content
</form>
JQuery
$('#myForm').on('submit', function(e) {
e.preventDefault(); //stop form submission
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: "Registar.php",
data: formData,
success: function(result) {
//result is the value returned from Registrar.php
console.log(result);
//show the modal
}
});
});
JSFiddle
Using the jQuery form plugin, I just want to submit the visible fields (not the hidden ones ) of the form.
HTML:
<div class="result"></div>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<div style="display:none;">
<input type="text" value="" name="name_1" />
</div>
<input type="submit" value="Submit Comment" />
</form>
I cannot find a way to submit only the visible fields using any of the methods below:
ajaxForm:
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
ajaxSubmit:
$('#myForm').ajaxSubmit({
target: '.result',
success: function(response) {
alert("Thank you for your comment!");
}
});
There is another method formSerialize but found no way to use it with the 2 methods mentioned above (usable with $.ajax however).
How to submit only the visible fields using any of the two methods ?
$("#myForm").on("submit", function() {
var visibleData = $('#myForm input:visible,textarea:visible,select:visible').fieldSerialize();
$.post(this.action, visibleData, function(result) {
alert('Thank you for your comment!');
});
// this is needed to prevent a non-ajax submit
return false;
});