I have a Script which load data from MySQL and then i generate a div for each result set. In each div i load several data and generate a form. The problem I have, is that the script is submitting the data from the first form.
Here the code:
<script>
function getitems(){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: 'action_type=view&'+$("#userForm").serialize(),
success:function(html){
$('#userData').html(html);
}
});
}
function userAction(type,id){
id = (typeof id == "undefined")?'':id;
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
var userData = '';
if (type == 'add') {
userData = $("#addForm").find('#userForm'+id).serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&id='+id;
}
$.ajax({
type: 'POST',
url: 'userAction.php',
data: userData,
success:function(msg){
if(msg == 'ok'){
getitems();
$('.form')[0].reset();
}else{
alert('Hubo un problema, intentar de nuevo!');
}
}
});
}
</script>
And the form:
<form class="form" id="userForm<?php echo $r['id']; ?>">
<div class="form-group col-xs-7">
<label>Descripcion</label>
<input type="text" class="form-control" name="item_prt" id="item_prt"/>
</div>
<div class="form-group col-xs-3">
<label>Precio</label>
<input type="text" class="form-control" name="precio_prt" id="precio_prt"/>
</div>
<input type="text" class="form-control" name="idserv_prt" id="idserv_prt" value="<?php echo $orden;?>" />
</form>
I need to difference each form, because all are generated dinamically from mysql result. So, if I submit the first form, it works ok, but when I submit other one, It submit the first form too.
All works OK if i hace only one form.
Thanks!
You need to add the form ID as following :
...
if (type == 'add') {
userData = $("#addForm").find('#userForm'+id).serialize()+'&action_type='+type;
// ----------------------------------------^
}else{
...
and when you call the userAction() function just add the second parameter wish is the ID :
Related
I am working with two forms where if user submitted first form the data is inserted using ajax to database and user is redirected to second form(Both Forms are in same file).
When user which is present on second form presses back button the value on the input type text for form1 one to be fetched from db which is stored when user submitted the first form.
My doubt is how can we pass value from ajax call to input type text
Here is my code which i have done uptill now
//Form 1
<form id="titlechange">
<div id="step1">
<input type="text" name="tbl_title" id="title" value="" class="form-control">
<input type="text" name="tbl_description" id="description" value="" class="form-control">
<button type="button" onclick="addTitle()" name="firstsubmit" class="update-btn" >Next</button>
</div>
</form>
//Form 2
<form id="detailsubmit">
<div id="step2">
<div class = "data"> //input type hidden retreived after submitting from 1 inside class data
<input type="hidden" value="<?php echo $insertData ?>" class="form-control">
</div>
<input type="text" name="city" id="city" value="" class="form-control">
<input type="text" name="state" id="state" value="" class="form-control">
<button type="button" onclick="addTitle()" name="firstsubmit" class="update-btn" >Next</button>
<button type="button" onclick="editModeForStep1()" name="firstsubmit" class="update-btn" >Back</button>
</div>
</form>
Ajax Call for back button
function editModeForStep1()
{
var formData = new FormData($('#detailsubmit')[0]);
formData.append('action', 'retreive');
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
enctype: 'multipart/form-data',
url: 'ClientData.php',
data: formData,
success:function(msg){
//what should be written here for displaying value received from `ClientData.php` to value attribute of input type text in form 1
$('#step1').addClass('in active');
alert('success');
}
});
}
ClientData.php
if(isset($_POST["action"]) && $_POST["action"]=="retreive"){
$insertData = $_POST['insertdata'];
$slideOne = $objMaster->getSlideForEdit($insertData);
foreach($slideOne as $key=>$value)
{
echo $title = $value['title'];
echo $description = $value['description'];
}
}
First, let's change ClientData.php to return data in a more usable form.
if(isset($_POST["action"]) && $_POST["action"]=="retreive"){
$insertData = $_POST['insertdata'];
//select first row of results for getSlideForEdit by adding `[0]`
$slideOne = $objMaster->getSlideForEdit($insertData)[0];
//notice array keys match form1 form elements ID
//notice there is no need for a loop here
echo json_encode(
array(
'title' => $slideOne['title'],
'description' => $slideOne['description']
)
);
//if you want to update EVERYTHING from $slideOne, you can just do
//echo json_encode($slideOne);
//instead of the above json_encode()
}
Now our return will contain JSON data instead of plain strings. We can update your success method to update those input boxes.
...
data: formData,
//set dataType to json because we are receiving json from the server
dataType: 'json',
success:function(msg){
$('#step1').addClass('in active');
//if you don't set dataType to json you can also do
//msg = JSON.parse(msg);
//loop through returned array.
$.each(msg, function(index, value) {
//select element by index e.g `#title`, set value
$('#' + index).val(value);
});
alert('success');
}
This solution will dynamically update any input on your page as long as you return a key=>value pair for it from your server.
I have a form that posts data to a server side page where the data is inserted into a mysql database and then a row count of the database is performed and the result returned to the form page where it is then displayed.
I am using an ajax to fetch the row count data and I'm wondering if it is possible to delay the Ajax call until the data has been inserted into the database so I can get an accurate row count that would include the data just submitted? The current code works but only shows a row count before the form has been submitted. I have to reload the page to get a true result.
Form.php
<form class="form-inline" action="" id="myform" form="" method="post">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name"></label>
<div class="col-md-8">
<input id="name" name="name" type="text" placeholder="name" class="form-control input-lg" required>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit1"></label>
<div class="col-md-4">
<button id="submitButtonId" name="submit1" class="btn btn-primary btn-xl">Submit</button>
</div>
</div>
</form>
<div id="count"></div>
</div>
The jquery
<script>
//Post data from form
$(document).ready(function(){
$("#submitButtonId").on("click",function(e){
e.preventDefault();
var formdata = $(this.form).serialize();
$.post('server.php', formdata,
function(data){
//Reset Form
$('#myform')[0].reset();
});
return false;
});
});
</script>
<script>
//Fetch Rowcount from server.php
$(document).ready(function(){
$.ajax({
url: 'data.php',
dataType: "json",
success: function (data) {
$("#count").html(data.count);
}
});
});
</script>
Server.php
<?php
//Connect to db
include_once("db_conx.php");
if( isset($_POST['name']) ){
$name= mysqli_real_escape_string($db_conx,$_POST['name']);
//Update Database
$stmt = $db_conx->prepare('INSERT INTO myTable set name=?');
$stmt->bind_param('s',$name);
$stmt->execute();
}
//Count Rows
$sql="SELECT name FROM myTable";
$query = mysqli_query($db_conx, $sql);
// Return the number of rows in result set
$rowcount=mysqli_num_rows($query);
// send output
$my_data=array(count=>"$rowcount");
echo json_encode($my_data,true);
?>
Call the ajax that fetches the row count inside the response of the first ajax post.
<script>
//Post data from form
$(document).ready(function(){
$("#submitButtonId").on("click",function(e){
e.preventDefault();
var formdata = $(this.form).serialize();
$.post('server.php', formdata,
function(data){
//Reset Form
$('#myform')[0].reset();
fetchRowCount();
});
return false;
});
});
function fetchRowCount() {
$.ajax({
url: 'data.php',
dataType: "json",
success: function (data) {
$("#count").html(data.count);
}
});
}
</script>
you can call the count row function after the post like this:
$.post('server.php', formdata,
function(data) {
//Reset Form
$('#myform')[0].reset();
$.ajax({
url: 'data.php',
dataType: "json",
success: function(data) {
$("#count").html(data.count);
});)
});
If I've understand correctly from the code, I see that the Fetch Rowcount is executed on $(document).ready.
It means that once (and everytime) the page is loaded, it is executed.
So it happens this:
1) the page is loaded
2) the Fetch rowcount is executed
3) You submit
4) you have to reload the page to go to point 2.
So the solution is to execute the row fetch as a callback function after the submit is executed, not on document ready.
I have two forms on my page.
One is in the footer and is a contact page, but the other is my main form called "product-form". I am doing some validation in PHP:
foreach( $_POST as $field => $val ) {
if ($val == '') {
echo $field . "- no val <br>";
}
}
The issue is that I am seeing fields being validated that are in my footer form...
Here is my AJAX:
$('body').on('submit', '.product-form', function(e){
e.preventDefault();
var thisForm = $(this);
$.ajax({
url : '/wp-content/themes/theme/page-templates/template-parts/template-logic/send-form.php',
type : 'POST',
data : thisForm.serialize(),
before : $(".error-message").remove(),
success : function(data) {
}
});
});
How is this submitting the data from two forms?
Both forms have their tags properly closed off, with different class's too.
Have to use WordPress for this project, normally much more at home with Laravel validation so this is a bit of a throwback!
Requested form HTML:
Form I want:
<form method="post" class="product-form">
<li class="object field">
<label for="full name">Your full name <span>*</span></label>
<input class="req" autocomplete="off" type="text" name="full name" id="full name" placeholder="e.g. John Doe">
</li>
</form>
And the footer form:
<form class="footer-form small">
<li>
<button class="object button large" type="submit">Get in touch</button>
</li>
</form>
Please change it like this:
$( ".product-form" ).submit(function( e) {
e.preventDefault();
var thisForm = $(this);
$.ajax({
url : '/wp-content/themes/theme/page-templates/template-parts/template-logic/send-form.php',
type : 'POST',
data : thisForm.serialize(),
before : $(".error-message").remove(),
success : function(data) {
}
});
});
I have a registration form and I want to display all of the registrants. I want to output whatever records are in the database and then once the form is submitted to register another display that record as well.
I can successfully register the records and display them using ajax however It does not load the last registered record until you reload/comeback to the page. I want the last record to just join its brethren right after the form submits. I appreciate anything you can suggest.
home.php
<form id="register-student" method="post" action="process_student_registration.php" class="basic-form not-toggled">
<h2>Enter Student Info to Register</h2>
<fieldset id="student-name-group" class="form-group">
<div class="split">
<fieldset id="student-firstname-group">
<label for="student-first-name">First Name:</label>
<input id="student-first-name" type="text" name="student_first_name">
</fieldset>
</div>
<div class="split">
<fieldset id="student-lastname-group">
<label for="student-last-name">Last Name:</label>
<input id="student-last-name" type="text" name="student_last_name">
</fieldset>
</div>
</fieldset>
<fieldset class="submit-button">
<div id="loading" class="hidethis"><img id="loading-image" src="../../images/ajax-loader.gif" alt="Loading..." /></div>
<button id="register-student-button" type="submit" class="btn btn-success" name="register-student-button">Register Student</button>
</fieldset>
</form>
<script>
$(document).ready(function() {
var students = $.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "fetch_students.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#registered-students").html(response);
//alert(response);
}
});
});
</script>
<div id="registered-students"></div><!--End # registered-students-->
fetch_students.php
<?php
//Fetch the Students
//First lets make sure the user is allowed
require_once('../auth/agency_session.php');
//App Functions
require_once('../../includes/functions/app_functions.php');
//Agents Home Page
require_once('../../db_config.php');
$db_connect = connectDB($mysqli);
$agency_id = $_SESSION['ID'];
//Here we display all the students the agent has registered
//First check the connection
if(!mysqli_connect_errno()){
if($stmt = $db_connect->prepare("SELECT student_id, student_first_name, student_last_name, student_email FROM students WHERE agency_id = ?")){
//Bind Parameters
$stmt->bind_param('i', $agency_id);
//Execute
$stmt->execute();
//Store Results
$stmt->store_result();
//Get the rows
$num_rows = $stmt->num_rows;
//Bind the results
$stmt->bind_result($student_id, $student_first_name, $student_last_name, $student_email);
if($stmt->num_rows < 1){
echo'<h3>No Students Registered</h3>';
}
else{
//Fetch the values
echo'<h3>Registered Students</h3>';
echo'<ul class="grid">';
while($stmt->fetch()){
echo '<li id="'.$student_id.'" class="col">'.$student_first_name.' '.$student_last_name.'<span>'.$student_email.'</span></li>';
}//End While
echo'</ul>';
}//End else
}//End if no prepare statment happens
}//End if No connection
?>
process_student_registration.php
jQuery(document).ready(function($){
// Get the form and place it into a variable
var form = $('#register-student');
//Creating an Event Listener for the submit buttom on the contact form
$(form).submit(function(event){
$('.form-group').removeClass('.has-error');//Remove the error class on the things that have the error class
$('.error-message').remove();//Remove the error messages completeley
//Serialize the Form Data (Converts the data the user has entered into a key/value string that can be sent with an AJAX request)
var formData = $(form).serialize();
//Submit the form using AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
dataType :'json',
encode:true
//.done refers to a successful completion of the form
})
.done(function(data){
//Log the data into the console so that we can be sure what is happening
console.log(data);
//If we do have errors create the
if(!data.successmessage){
if(data.errors){
$('.error').remove();
$('.error-message').remove();
$('#register-student').addClass('form-has-error'); // add the form-has-error-class
$('#register-student-button').after('<p class="error">Please check the errors above.</p>');
$(form).removeClass('success');
$('.submit-success').remove();
if(data.errors.student_first_name){
$('#student-firstname-group').addClass('has-error'); // add the error class to show red input
$('#student-firstname-group').append('<div class="error-message"><p>' + data.errors.student_first_name + '</p></div>'); // add the actual error message under our input
}
if(data.errors.student_last_name){
$('#student-lastname-group').addClass('has-error'); // add the error class to show red input
$('#student-lastname-group').append('<div class="error-message"><p>' + data.errors.student_last_name + '</p></div>'); // add the actual error message under our input
}
}
} else if(data.successmessage){
//Remove the errors stuff
$('.error').remove();
$('.error-message').remove();
$('#register-student').removeClass('form-has-error'); // add the form-has-error-class
$('#blocking').removeClass('hidethis').addClass('showthis');
$('#loading').removeClass('hidethis').addClass('showthis');
$('.submit-success').remove();
//Add the success stuff
$(form).addClass('success');
setTimeout(function(){
$('#blocking').removeClass('showthis').addClass('hidethis');
$('#loading').removeClass('showthis').addClass('hidethis');
$('#register-student').append('<div class="submit-success"><p>' + data.successmessage + '</p></div>');
$(form).find('input, :text').val('');
//Run the Get operation on the database to add newly added records to the list
}, 5000);
//Clear the form upon successful completion
}
//.fail referes to an unsuccessful completion of the form
})
.fail(function(data){
//If there is a failed submission lets log the errors
console.log(data);
});
//Stop the broweser from submitting the form
event.preventDefault();
});
});
I had a similar issue... you are processing from two different php file:
process_student_registration.php and fetch_students.php
I believe your problem might be solved if you do all the processing from one file:
You are only passing two pieces of data. Rather than collecting the data from a form you can collect the data through inputs and go straight to the jQuery.
Your Collection HTML would look like this: NOTICE the dashes replaced with underscores.
<h2>Enter Student Info to Register</h2>
<input type="hidden" id="processStudent" value="process_student_registration.php">
<fieldset id="student-name-group" class="form-group">
<div class="split">
<fieldset id="student_firstname_group">
<label for="student_first_name">First Name:</label>
<input id="student_first_name" type="text" name="student_first_name">
</fieldset>
</div>
<div class="split">
<fieldset id="student_lastname_group">
<label for="student_last_name">Last Name:</label>
<input id="student_last_name" type="text" name="student_last_name">
</fieldset>
</div>
</fieldset>
<fieldset class="submit_button">
<div id="loading" class="hidethis"><img id="loading_image" src="../../images/ajax_loader.gif" alt="Loading..." /></div>
<button id="register_student_button" type="submit" class="btn btn_success" name="register_student_button">Register Student</button>
</fieldset>
<div id="registered-students"></div>
Your jQuery...
<script>
$(document).ready(function() {
$( "#register-student-button" ).click(function(){
var url = $('#processStudent').val();
var student_first_name = $('#student_first_name').val();
var student_last_name = $('#student_last_name').val();
var postit = $.post( url, {student_first_name:student_first_name,student_last_name:student_last_name});
postit.done(function( data ) {
alert('Student has been processed');
$('#registered-students').html(data);
});
});
});
Your PHP...
<?php
$student_first_name = $_POST['student_first_name'];
$student_last_name = $_POST['student_last_name'];
// PROCESS REGISTRATION HERE AS YOU ARE
// FETCH STUDENTS HERE AS YOU ARE
?>
I have figured out a solution. Basically I run the script to display records fomr the database on once on page load. Then I took basically the same script again and run it once more upon successful completion of the form. This way we only scan the database for new records as we need to. Not sre if it the most elegant or efficient way but she work like a charm.
So in my process_student_registration.php I added this to the success message.
//Run the Get operation on the database to add newly added records to the list
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "fetch_students.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#registered-students").html(response);
//alert(response);
}
I have been searching through examples for days trying to troubleshoot my simple email signup form. I am trying to just submit an email to a database without leaving or reloading the current page. I am able to insert new data to my database, but not through my Ajax function. I am starting to think that my Ajax function is not being called, because even with the event.preventDefault(); function, my page is redirected to the .php file. I have listed my script below which currently resides in the <head></head> section of my HTML.
<script type="text/javascript">
$(document).ready(Function() {
$("#submitbtn").click(function(event) {
event.preventDefault();
var form = $(this),
emailcode = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method');
/* responseMsg = $('#signup-response') */
if ( formData.length===0 ) {
function(msg){
alert('Invalid Email');
}
return false;
} else {
//send data to server
$.ajax({
url: formUrl,
type: formMethod,
data: emailcode,
success:function(data){
alert('Email Saved');
}
return false;
});
};
});
});
HTML
<form class="col-lg-5 form-group pull-right well" id="emailform" action="collector.php" method="POST" style="padding-top:6px;">
<label for="email-input">Sign up to receive updates</label>
<input type="email" class="form-control" id="emailcode" placeholder="Email" name="emaildata" autofocus></input>
<button type="submit" id="submitbtn" class="btn btn-success" style="width:60%">Sign Up</button>
</form>
PHP
$emailcode = $_POST['emailcode'];
//Fetching from your database table.
$query = "INSERT INTO EmailCollector (EmailID, EmailCode, Active)
VALUES (NULL,'$emailcode', 0)";
$result = mysql_query($query);
mysql_close();
?>
A quick thing i noticed.
form = $(this) //it is holding submit button, not the form
emailcode = form.serialize(),
formUrl = form.attr('action'), //there is no attribute `action` to select because form is holding submit button
formMethod = form.attr('method'); //similarly, there is no attribute method
change your form selector to:
form = $('#emailForm')