How to read file posted with FormData through ajax - javascript

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

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?

Pass form results to another form into a form value

I have two forms on a page the "top form" searches for movies and I'm trying to get the data found from the top form and pass it as a value to the bottom form so it can get entered into a database.
I am unable to do this but, I can get the results to be displayed on the page. Here is my code:
TOP FORM DATA
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<?php
$squery="";
if(isset($_GET["squery"]))
{
$squery=$_GET["squery"];
}
?>
<div class="col-xs-8 col-xs-offset-2">
<form action="#" method="GET" class="form-horizontal">
<div class="form-group">
<label for="newMovieName" class="col-sm-3 control-label">Search what movie?</label>
<div class="col-sm-9"> <input type="text" name="squery" class="form-control"><br />
<input type="submit" value="Submit" class="btn btn-success"></div></div>
</form>
<script type="text/javascript" charset="utf-8">
var api_key = '6969696969696969696969696969696';
$(document).ready(function(){
$.ajax({
url: 'http://api.themoviedb.org/3/search/movie?api_key=' + api_key + '&query=<?php echo $squery; ?>',
dataType: 'jsonp',
jsonpCallback: 'testing'
}).error(function() {
console.log('error')
}).done(function(response) {
var i=0;
// for (var i = 0; i < response.results.length; i++) {
$('#search_results').append('<li>' + response.results[i].title + '</li>');
// }
$('#search_results_title').append(response.results[i].title);
$('#search_results_release').append(response.results[i].release_date);
$('#search_results_overview').append(response.results[i].overview);
$('#search_results_poster').append('https://image.tmdb.org/t/p/w185' + response.results[i].poster_path);
$('#search_results_votes').append(response.results[i].vote_count);
});
});
</script>
TOP FORM RESULTS
Here is where the results are displayed from the form above BUT, I would like these results to be displayed as a value in the form below.
<h3>Results</h3>
<p id="error"></p>
<ul id="search_results_title"></ul>
<ul id="search_results_release"></ul>
<ul id="search_results_overview"></ul>
<ul id="search_results_poster"></ul>
<ul id="search_results_votes"></ul>
BOTTOM FORM DATA
Here is the bottom form that SHOULD get submitted to the database with the "Results" that are above as the value.
<form class="form-horizontal" role="form" action="processmovie.php" method="get" enctype="text/plain">
<div class="form-group">
<label for="newMovieName" class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="newMovieName" name="movie_name" placeholder="Movie Title" required value="">
</div>
</div>
<div class="form-group">
<label for="movieYear" class="col-sm-3 control-label">Year</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="movieYear" name="movie_year" placeholder="Year" required>
</div>
</div>
<div class="form-group">
<label for="movieBio" class="col-sm-3 control-label">Storyline</label>
<div class="col-sm-9">
<textarea type="email" class="form-control" id="movieBio" name="movie_bio" rows="4" placeholder="Enter Storyline" required></textarea>
</div>
</div>
<div class="form-group">
<label for="newImage" class="col-sm-3 control-label">Movie Cover URL</label>
<div class="col-sm-9">
<input type="text" id="newImage" class="form-control" name="movie_img" placeholder="Enter URL" required>
</div>
</div>
<div class="form-group">
<label for="movieRating" class="col-sm-3 control-label">Rating</label>
<div class="col-sm-9">
<select id="movieRating" name="movie_rating" class="form-control" required>
<option value="G">G</option>
<option value="PG">PG</option>
<option value="PG-13">PG-13</option>
<option value="R">R</option>
<option value="NR">NR (Not Rated)</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-success">Add Movie</button>
</div>
</div>
</form>
I tried to use a variaty of code to try and get the value here is an example: <?php echo $_GET['search_results_title'];?>
I've also found examples like this: How to pass the value of a form to another form? but, my forms are on the same page and not different ones.
As I said in my comment, you would just want to change your ajax call to something like this:
$.ajax({
url: 'http://api.themoviedb.org/3/search/movie?api_key=' + api_key + '&query=<?php echo $squery; ?>',
dataType: 'jsonp',
jsonpCallback: 'testing'
}).error(function() {
console.log('error')
}).done(function(response) {
var i=0;
$('#newMovieName').val(response.results[i].title);
$('#movieYear').val(response.results[i].release_date);
$('#movieBio').val(response.results[i].overview);
$('#newImage').val('https://image.tmdb.org/t/p/w185' + response.results[i].poster_path);
});
(I'm not sure about the relationship you have between response.results[i].vote_count and movieRating)
Here is a fiddle sort of showing the result, though I can't exactly replicate your code there because of the ajax calls

Trouble serializing form with jQuery

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);

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.

How to empty ajax loaded form?

How can we empty a ajax loaded form using pure JavaScript or jQuery.
I have tried document.forms[0].reset(); and $('#new-staff-form')[0].reset(); both didn't work it returns undefined.
Update
<div class="box col-md-12 new-staff">
<form id="new-staff-form" method="post">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" name="f_name" placeholder="First name"/>
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" name="l_name" placeholder="Last name"/>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label for="user_name">User name</label>
<input id="user_name" type="text" name="user_name" placeholder="User name"/>
</div>
<div class="col-md-6">
<button id="user-avail" class="btn btn-primary">Check available</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary pull-left">Save</button>
</div>
</div>
</form>
</div>
Javascript:
$('#new-item').click(function(){ // works fine until I load new html form using ajax with same ids and class
$('#new-staff-form')[0].reset();
$('.new-staff').slideToggle(); // show new form
});
$('.edit-item').click(function(){ // ajax call this loads everything correctly
var id = $(this).data('staf_id'); //item to delete
$.ajax({
url:url_view_staff+id,
type:'get'
}).done(function(data){
edit_item_id = id;
$('.new-staff').html(data).slideDown();
}).fail(function(data){
$('#errors').html(data.responseText);
$('.valid-error').slideDown();
});
});
JavaScript:
document.getElementById("myForm").reset();
Jquery :
$('#form_id')[0].reset();
Make sure your form id is valid.
FIDDLE
$('#configreset').click(function(){
$('#configform')[0].reset();
});

Categories

Resources