Trouble serializing form with jQuery - javascript

I cannot for the life of me figure out why my form will not serialize when using jQuery prior to posting via AJAX.
Whenever I debug the javascript 'formData' results in "".
I've tried this with the form id's hardcoded and it still results in the blank serialization, tried .get(0) at the end of the $(this) selector and tried without underscores in names and to no avail.
When debugging the selector contains the inputs as children, and I've serialized forms before where the inputs are nested in other elements without problems.
The reason I'm dynamically selecting the form with $(this) and not hardcoding the event handlers is that this will be part of the application where we will bolt on additional forms so I'd like it to be concise and maintainable.
Any insight is greatly appreciated.
My code is below:
HTML/PHP view (using CodeIgniter)
<div class="tabs-content">
<section role="tabpanel" aria-hidden="false" class="content active" id="details">
<div class="login-form">
<p class="lead">To change basic personal details such as name and email address use this form.</p>
<form action="<?php echo base_url() ?>ajax/update_details" method="POST" name="updateDetailsForm" id="updateDetailsForm">
<div class="row">
<div class="small-12 columns">
<label>First Name
<input type="text" placeholder="e.g. John" name="first_name" value="<?php echo $first_name ?>" />
</label>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<label>Surname
<input type="text" placeholder="e.g. Smith" name="last_name" value="<?php echo $last_name ?>" />
</label>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<label>Email
<input type="email" placeholder="e.g. me#example.com" name="email" value="<?php echo $email ?>" />
</label>
</div>
</div>
<input type="submit" class="button small" value="Update" />
</form>
</div>
</section>
<section role="tabpanel" aria-hidden="true" class="content" id="password">
<div class="login-form">
<p class="lead">You can use the form below to update your account password.</p>
<p>Passwords must be between 8 and 50 characters in length.</p>
<form action="<?php echo base_url() ?>ajax/update_password" method="POST" name="updatePasswordForm" id="updatePasswordForm">
<div class="row">
<div class="small-12 columns">
<label>Old Password <small>Required</small>
<input type="password" name="oldpw" />
</label>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<label>New Password <small>Required</small>
<input type="password" name="newpw1" />
</label>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<label>Confirm New Password <small>Required</small>
<input type="password" name="newpw2" />
</label>
</div>
</div>
<input type="submit" class="button small" value="Update Password" />
</form>
</div>
</section>
</div>
Javascript
$('form').on('submit', (function (e) {
e.preventDefault();
var url = $(this).attr('action');
$(this).html(loadingHTML);
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: url,
data: formData,
done: function (data) {
$(this).html(data);
}
});
}));

Swap lines
var formData = $(this).serialize();
$(this).html(loadingHTML);

Related

checkValidity() not showing any html5 error notifications when fields are empty and posting with Ajax

I have a form that posts using Ajax, I also want to set an HTML5 required attribute on some input fields, but this stops working as expected with Ajax.
So I did the following:
$("body").on("click",".register-button",function(e){
e.preventDefault();
if($('#registerform')[0].checkValidity()){
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
}else{
}
});
This way the form is not posted when empty, but I also don't get any notifications that fields are empty like I would get when only using HTML to post.
I also tried logging the validity like so:
$("body").on("click",".register-button",function(e){
e.preventDefault();
$check = $('#registerform')[0].checkValidity();
console.log($check);
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
});
Which shows false in my console when empty. So the code works, why are the HTML5 notifications not shown? I remember doing something similar in the past and I didn't have to add any custom error messages then, it just worked.
This is my HTML markup:
<form id="registerform" class="register-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="voornaam" placeholder="Voornaam" required>
</div>
<div class="col-md-6">
<input type="text" name="achternaam" placeholder="Achternaam" required>
</div>
<div class="col-md-12">
<input type="text" name="bedrijf" placeholder="Bedrijfsnaam (optioneel)">
</div>
<div class="col-md-6">
<input type="text" name="telefoon" placeholder="Telefoonnummer" required>
</div>
<div class="col-md-6">
<input type="text" name="email" placeholder="E-mail" required>
</div>
<div class="col-md-3">
<input type="text" name="huisnummer" id="billing_streetnumber" placeholder="Huisnummer" required>
</div>
<div class="col-md-3">
<input type="text" name="tussenvoegsel" placeholder="Tussenvoegsel" required>
</div>
<div class="col-md-6">
<input type="text" name="postcode" id="billing_postcode" placeholder="Postcode" required>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-md-6">
<input type="text" name="straat" placeholder="Straatnaam" readonly required>
</div>
<div class="col-md-6">
<input type="text" name="woonplaats" placeholder="Woonplaats" readonly required>
</div>
</div>
</div>
<div class="col-md-6">
<input type="password" name="password" placeholder="Wachtwoord (minimaal 6 tekens)" required>
</div>
<div class="col-md-6">
<input type="password" name="confirmpassword"placeholder="Herhaal wachtwoord" required>
</div>
<div id="registerresult">
</div>
</div>
<button type="button" name="submit" class="register-button">Account aanmaken</button>
</form>
What am I missing?

How to read file posted with FormData through ajax

I am trying to see if a file is correctly posted from my form but everything I try to echo/print shows up empty.
This is my form:
<form id="employeeformadd" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-6">
<div class="card m-b-20">
<div class="card-body">
<input type="hidden" name="id_company" value="<?PHP echo $getbedrijfinfo['id']; ?>">
</div>
</div>
</div>
<div class="col-md-6">
<div class="card m-b-20">
<div class="card-body">
<div class="form-group row">
<label for="example-text-input" class="col-sm-4 col-form-label">Kopie rijbewijs</label>
<div class="col-sm-8">
<form action="#">
<div class="form-group">
<input id="copy_driverslicense" type="file" class="filestyle" data-input="false" data-buttonname="btn-secondary">
</div>
</form>
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-sm-4 col-form-label">Kopie paspoort</label>
<div class="col-sm-8">
<form action="#">
<div class="form-group">
<input type="file" class="filestyle" data-input="false" data-buttonname="btn-secondary">
</div>
</form>
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-sm-4 col-form-label">Kopie medische geschiktheidsverklaring</label>
<div class="col-sm-8">
<form action="#">
<div class="form-group">
<input type="file" class="filestyle" data-input="false" data-buttonname="btn-secondary">
</div>
</form>
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-sm-4 col-form-label">Diploma</label>
<div class="col-sm-8">
<form action="#">
<div class="form-group">
<input type="file" class="filestyle" data-input="false" data-buttonname="btn-secondary">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
And this is my jquery:
$("body").on("click","#addemployeebtn",function(){
var form = $(this);
var formdata = false;
if (window.FormData){
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url : 'includes/addemployee.php',
data : formdata ? formdata : form.serialize(),
cache : false,
contentType : false,
processData : false,
type : 'POST',
success : function(data, textStatus, jqXHR){
// Callback code
}
});
});
And in my php script I have tried these things:
echo = $_FILES['filename'];
echo $_POST['file'];
print_r($_FILES);
echo $_FILES['file'];
echo $_FILES['files']['name'][0];
But they are all empty when I echo/print them.
If I look in the networktab I see the form is posted so my javascript works.
I think the problem is that you're binding click event to a button $("body").on("click","#addemployeebtn",function(){ BUT referencing $(this) object as a form by doing var form = $(this);.
So its either you bind a submit event to the form id or reference the form object form the form id var form = $('#employeeformadd');.
Also, you need to remove all the sub forms you have inside the main form <form action="#"> and remember to remove their closing tags too </form>.
Most Importantly:
Add name="fieldname" to your file field like this <input id="copy_driverslicense" type="file" class="filestyle" data-input="false" data-buttonname="btn-secondary" name="photo1">
at the first you should replace $("body").on("click","#addemployeebtn",function() with
$("body").on("submit","#employeeformadd",function()
so when you write var form = $(this); the form object refer to #employeeformadd form not #addemployeebtn submit button
and second you should give name to each input file for example
so in php you can access it by write $_FILES['diploma'];
and finally you should remove unnecessary form tag in your html for example

Validate form fields before confim modal and submit form

I'm trying to use Bootstrap Modal as my confirm dialog before form submit. However I want to validate first my form before showing the Modal. How can I do that?
This is what I've tried so far:
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('show');
});
$(".btn btn-custom").click(function(e) {
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#reservationForm").submit();
$("#"+modal_id).modal('hide');
});
});
</script>
<form class="form" method="POST" action="unit-reservation.php" id="reservationForm">
<div class="form-horizontal">
<div class="control-group">
<label class="control-label"><b>Firstname (*):</b></label>
<div class="controls">
<input type="text" name="customerfname" required />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Middlename (*):</b></label>
<div class="controls">
<input type="text" name="customermname" required />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Lastname (*):</b></label>
<div class="controls">
<input type="text" name="customerlname" required />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Email Address (*):</b></label>
<div class="controls">
<input type="email" name="customeremailaddress" required />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Address:</b></label>
<div class="controls">
<input type="text" name="customeraddress" required />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Telephone Number:</b></label>
<div class="controls">
<input type="tel" name="customertelnumber" />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Mobile Number:</b></label>
<div class="controls">
<input type="number" step="any" min="0" name="customermobilenumber" required /
</div>
</div>
</div>
<input type="hidden" value="<?php echo $user; ?>" name="user_id">
<button id="<?php echo $code; ?>" class="btn btn-custom btn-show-modal" data-toggle="modal">Reserve Now</button>
</form>
<div class="modal hide fade" id="dialog-example_<?php echo $code; ?>">
<div class="modal-header">
<h5>Confirm Reservation</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to reserve unit: <?php echo $code; ?>?</p>
</div>
<div class="modal-footer">
No
Yes
</div>
</div>
The problem is that you submit your form when you click on your modal-button because it has the same class as the modal anchor.
$(".btn-show-modal").click(function(e){ ...
$(".btn btn-custom").click(function(e) {...
You have to add another class to your modal anchor for the submit.
Yes
and call this for your submit click handler:
$(".btn-show-modal").click(function(e){ ...
$(".btn-submit").click(function(e){}
Like this the submit action is only triggered by your modal anchor. You have to be careful if you use classes for css-styling and the same classes for javascript selectors. A better approach is to give those buttons (if only used once) an id so the javascript can access it more quickly. And keep the .btn, .btn-custom for the css only.

Pass form Variables to $_SESSION by AJAX in wordpress

I have several forms on my site that manipulate the data that is held in $_SESSION. I am looking to AJAXify all of these. The main example is below.
FORM:
<form class="form-inline" id="addExerciseForm" role="form" method="post" action=" ">
<div class="form-group">
<input class="hidden" name="ExerciseID" type="text" class="form-control" value="29">
</div>
<div class="form-group lightboxFormText">
<label class="lightboxFromElementLabels" for="exerciseDescription">Description</label>
<textarea class="form-control" name="Description" rows="3"><?php echo the_content(); ?></textarea>
</div>
<br />
<br />
<div class="form-group lightboxFormElements">
<label class="lightboxFromElementLabels" for="exerciseSets">Sets</label>
<input type="text" name="Sets" class="form-control" placeholder="Sets">
</div>
<div class="form-group lightboxFormElements">
<label class="lightboxFromElementLabels" for="exerciseReps">Reps</label>
<input type="text" name="Reps" class="form-control" placeholder="Reps">
</div>
<div class="form-group lightboxFormElements">
<label class="lightboxFromElementLabels" for="exerciseReps">Load</label>
<input type="text" name="Load" class="form-control" placeholder="Load">
</div>
<div class="form-group lightboxFormElements">
<label class="lightboxFromElementLabels" for="exerciseReps">Rest</label>
<input type="text" name="Rest" class="form-control" placeholder="Rest">
</div>
<div class="form-group lightboxFormElements">
<label class="lightboxFromElementLabels" for="exerciseReps">Tempo</label>
<input type="text" name="Tempo" class="form-control" placeholder="Tempo">
</div>
<br />
<br />
<div class="modal-footer">
<div class="form-group">
<input type="hidden" name="action" value="addExercise">
<input type="submit" class="btn btn-success">Add to Collection</input>
</div>
</div>
</form>
Javascript:
jQuery('#addExerciseForm').submit(addExercise);
function addExercise(){
var newExercise = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: addExerciseForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
Function:
function addExercise(){
global $post;
echo $description;
$_SESSION['collection'][$_POST['ExerciseID']] = array(
$description => $_POST['Description'],
$sets => $_POST['Sets'],
$reps => $_POST['Reps'],
$load => $_POST['Load'],
$rest => $_POST['Rest'],
$tempo => $_POST['Tempo']);
$description = $_SESSION['collection'][$exid]['Description'];
$sets = $_SESSION['collection'][$exid]['Sets'];
$reps = $_SESSION['collection'][$exid]['Reps'];
$rest = $_SESSION['collection'][$exid]['Rest'];
$load = $_SESSION['collection'][$exid]['Load'];
$tempo = $_SESSION['collection'][$exid]['Tempo'];
die();
}
add_action('wp_ajax_addExercise', 'addExercise');
add_action('wp_ajax_nopriv_addExercise', 'addExercise');
I understand that I can go straight from jQuery VAR -> session Var however this code is cobbled together from my original $_POST Submit button. The AJAX side of things has got me confused, and throwing in the mix the different way that Wordpress handles things, any assistance will be appreciated.
Using $_SESSION in WordPress isn't the same as a standard php script approach. You have to do things like factoring in when in the sequence of WordPress loading, does the session get set, created, etc.
Have you seen the WP Session Manager? It makes working with sessions in WordPress much more pain-free. Check out https://wordpress.org/plugins/wp-session-manager/

Jquery $.ajax not fired on post

I'm using Jquery ajax to post data, but $.ajax is not fired. the click button is fired.
There's a javascript warning in firebug Empty string passed to getElementById().
Here's my code
$('body').on('click','button.btnsubmitads',function(event) {
event.preventDefault();
$.ajax({
type:"post",
url:base_url+"advertising/newads",
dataType:"json",
data:$("#newadsform").serialize(),
contentType: "application/json",
success: function(result) {
if(result.status){
console.log('oke');
} else {
console.log('ga oke');
}
},
error: function() {}
});
return false;
});
here's my form
<form class="newadsform form-horizontal" action="" method="post" id="newadsform">
<div class="control-group">
<label class="control-label">Listing</label>
<div class="controls">
<select name="idlisting" class="span10" id="idlisting">
<?php foreach($listing->result() as $data){
echo "<option value=\"".$data->idlisting."\">".$data->title."</option>";
}?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Title</label>
<div class="controls">
<input type="text" class="span10" name="title" id="title">
</div>
</div>
<div class="control-group">
<input type="hidden" id="inputimageadvs" name="imagename" value="" />
<input type="hidden" id="inputimagelarge" name="imagenamelarge" value="" />
<input type="hidden" id="inputimagethumb" name="imagenamethumb" value="" />
<label class="control-label">Image:</label>
<div class="controls">
<div class="example span10" style="margin:0;">
<div class="alert alert-success">
Please use PNG or JPEG extension only, and File size not more than 1 Mb (1024 Kb)
</div>
<ul id="uploadadv" class="styled"></ul>
</div>
</div>
<div class="clear"></div>
</div>
<div class="form-actions span10" style="margin:0;">
<button class="btnsubmitads btn btn-primary" type="submit" id="btnsubmitads">
<i class="icon-ok"></i> Submit
</button>
<button class="btn" type="reset" id="reset">Reset</button>
</div>
</form>
Looks like you have Ads Block Installed.
Last day I've same problem.
try to change
url:base_url+"advertising/newads
with another word that not contain ads or advertising word

Categories

Resources