I'm trying to pass the input of an HTML form to a PHP script with jQuery, but all that happens is a refresh of the page. The PHP script called by this form returns a formatted div which contains all the post data. How can I display this data in the page without reloading it?
jQuery
$("form#submissionform").submit(function(){
var formData = new FormData($(this));
$.ajax({
url: 'handlers/upload.php',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data){
$("#submissionform").html(data);
}});
});
HTML
<form id="submissionform" method="post" enctype="multipart/form-data">
<p>Title: <p><br><input style="width:360px" type="text" name="songtitle"><br>
<p>Artist: </p><br><input style="width:360px" type="text" name="artist"><br>
<p>YouTube Link(s): </p><br><input style="width:360px" type="text" name="ytlinks" cols="50"><br>
<p>Other Info </p><br><textarea style="width:100%" name="otherinfo" rows="4" cols="50" placeholder="Bitte alle zusätzlichen Informationen hier eintragen"></textarea><br>
<p>Select file to upload:</p>
<input type="file" name="fileToUpload" id="fileToUpload">
<br><br>
<button>Send Form</button>
</form>
Firstly make an id on your button.If you use submit it will refresh your page.
<button id="btnSubmit">Submit</button>
Then
$("#btnSubmit").click(function(){
var formData = new FormData($(this));//Here I'd like to suggest you send the data using variable .I'm giving one exmple then do like that
<p>Title: <p><br><input style="width:360px" type="text" name="songtitle" id="songtitle"><br>
var songTitle = $("#songtitle").val().trim();
In similar way you can do.
<p>Artist: </p><br><input style="width:360px" type="text" name="artist" id="artist"><br>
var artist = $("#artist").val().trim();
var formData = {
artist : artist,
songTitle : songTitle
}
$.ajax({
url: 'handlers/upload.php',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data){
$("#submissionform").html(data);
}});
});
(...) but all that happens is a refresh of the page. (...)
In order to prevent page refreshing, you have to prevent default form submission. If the <button> inside a form has no type attribute specified or if the attribute is dynamically changed to an empty or invalid value, it's treated as type=submit, which - naturally - will submit the form as a HTTP POST request (reloading page).
The following code should work for you:
index.html:
<html>
<body>
<form id="submissionform" method="post" enctype="multipart/form-data">
<p>Title: <p><br><input style="width:360px" type="text" name="songtitle"><br>
<p>Artist: </p><br><input style="width:360px" type="text" name="artist"><br>
<p>YouTube Link(s): </p><br><input style="width:360px" type="text" name="ytlinks" cols="50"><br>
<p>Other Info </p><br><textarea style="width:100%" name="otherinfo" rows="4" cols="50" placeholder="Bitte alle zusätzlichen Informationen hier eintragen"></textarea><br>
<p>Select file to upload:</p>
<input type="file" name="fileToUpload" id="fileToUpload">
<br><br>
<!-- The button has no "type" attribute specified, so it's treated as type="submit" : -->
<button>Send Form</button>
</form>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$("form#submissionform").submit(function(event){
// prevent default form submission:
event.preventDefault();
var data = new FormData($(this)[0]);
$.ajax({
url: 'handlers/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
});
</script>
</body>
</html>
handlers/upload.php:
<?php
$data = $_POST;
foreach ($data as $key => $value) {
echo $key . " " . $value . "\n";
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$res = move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
echo $res;
?>
Note: In my case, I have uploads folder inside handlers folder.
References:
event.pReventDefault()
button type attribute
Related
let me first explain what I aim to do, then display my code.
What I want to do is make a page which basically updates a user's details in the database, I did this part first and everything works perfectly here, through AJAX. Next I wanted to update the profile picture of the user as well through AJAX, so I made a normal file upload PHP page to make sure that my PHP code was working correctly and it was. Now I just needed to perform the upload via AJAX, and this is where I get stuck. I keep getting an error message from the PHP page which states undefined index: file.
Please feel free to ask any questions, and thank you for the responses.
Here is my HTML form:
<form action="upload.php?upload&type=profile" method="post" enctype="multipart/form-data">
<label for="profile">Profile Picture</label><br />
<img id="preview" width="200" height="200" src="<?php echo $user->getProfile(); ?>" alt="Profile Picture Preview" /><br />
<br />
<input type="file" name="file" id="file" onchange="loadImage(this);" /><br />
<label for="username">Username</label><br />
<input type="text" name="username" id="username" value="<?php echo $user->getUsername(); ?>" /><br />
<label for="email">Email Adress</label><br />
<input type="text" name="email" id="email" value="<?php echo $user->getEmail(); ?>" /><br />
<label for="bio">Biography</label><br />
<textarea name="bio" id="bio" cols="40" rows="5"><?php echo $user->getBio(); ?></textarea><br />
<label for="password">New Password</label><br />
<input type="password" name="password" id="password" /><br />
<label for="oldPass">Current Password</label><br />
<input type="password" name="oldPass" id="oldPass" /><br />
<label for="first">First Name</label><br />
<input type="text" name="first" id="first" value="<?php echo $user->getFirstName(); ?>" /><br />
<label for="last">Last Name</label><br />
<input type="text" name="last" id="last" value="<?php echo $user->getLastName(); ?>" /><br />
<br />
<input type="submit" name="update" value="Save" id="update" /> <input type="button" name="reset" value="Reset Fields" onclick="resetFields()" />
</form>
Here is my js file containing the AJAX:
$(document).ready(function() {
$("#update").click(function() {
profile = "pictures/default.jpg";
username = $("#username").val();
email = $("#email").val();
bio = $("#bio").val();
newPass = $("#password").val();
oldPass = $("#oldPass").val();
first = $("#first").val();
last = $("#last").val();
// First an ajax request to upload the image as it requires separate request
$.ajax({
type: "POST",
url: "upload.php?upload&type=profile",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(resp) {
alert(resp);
},
error: function (resp) {
alert(resp);
}
});
// Now the updates in the profile
$.ajax({
type: "POST",
url: "update.php",
data: "mode=details&profile="+profile+"+&username="+username+"&email="+email+"&bio="+bio+"&password="+newPass+"&oldPass="+oldPass+"&first="+first+"&last="+last,
success: function(resp) {
// resp contains what is echoed on update.php
alert(resp);
}
});
return false;
});
});
Finally, here is my PHP Code:
include "base.php";
// Kick user off this page if they are not logged in
if (!isset($user)) {
echo "<meta http-equiv='refresh' content='0.1;url=index.php'>";
exit();
}
if (isset($_GET['upload'])) {
switch ($_GET['type']) {
case "profile": {
$dir = "pictures/";
$maxFileSize = 2000000; // 2mb
$extensions = array("jpg", "jpeg", "png", "gif");
$currentPath = pathinfo($_FILES['file']['name']);
$fileType = $currentPath['extension'];
$targetFile = $dir.$user->getUsername()."Profile.".$fileType;
}
break;
default: {
echo "<meta http-equiv='refresh' content='0.1;url=index.php'>";
exit();
}
break;
}
$upload = true;
// Check the file size
if ($_FILES['file']['size'] > $maxFileSize) {
echo "The file is too large.";
$upload = false;
}
// Limit file types
if (!in_array($fileType, $extensions)) {
echo "This file type is not allowed.";
$upload = false;
}
// Check if file upload is allowed and upload if it is
if ($upload) {
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
echo basename($_FILES['file']['name']);
} else {
echo "There was an error during file upload.";
}
}
}
Your code has a few issues. For one since your button was located within a Form and you were only associating a click on that button then the form was submitting itself as normal and pretty much confusing jquery. In order to capture the form properly in jquery you need to run it as a submit instead and add the e.preventDefault(); so that your code in ajax runs instead of the actual form submitting on the page.
You need to add e.preventDefault(); so that your form does not submit itself since you have form tags. Also change from click to submit
$("form").submit(function(e) {
e.preventDefault();
profile = "pictures/default.jpg";
username = $("#username").val();
email = $("#email").val();
bio = $("#bio").val();
newPass = $("#password").val();
oldPass = $("#oldPass").val();
first = $("#first").val();
last = $("#last").val();
// First an ajax request to upload the image as it requires separate request
$.ajax({
type: "POST",
url: "upload.php?upload&type=profile",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(resp) {
alert(resp);
},
error: function (resp) {
alert(resp);
}
});
// Now the updates in the profile
$.ajax({
type: "POST",
url: "update.php",
data: "mode=details&profile="+profile+"+&username="+username+"&email="+email+"&bio="+bio+"&password="+newPass+"&oldPass="+oldPass+"&first="+first+"&last="+last,
success: function(resp) {
// resp contains what is echoed on update.php
alert(resp);
}
});
return false;
});
If you are dealing with multiple forms on a page, or dynamically created forms then you will want to use
$(document).on('submit', 'form', function(e) {
...
});
Even better give your form a class for dynamic data
$(document).on('submit', '.myform', function(e) {
...
});
My code here works fine except image uploading. It inserts all data in database .
<input type="file" name="image2" class="file" id="imgInp"/>
But after adding file type input in php it is showing
Notice: Undefined index: image2 in C:\xampp\htdocs\upload\submit.php on line 18
How can I add image uploading function in my existing code.
<div id="form-content">
<form method="post" id="reg-form" enctype="multipart/form-data" autocomplete="off">
<div class="form-group">
<input type="text" class="form-control" name="txt_fname" id="lname" placeholder="First Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_lname" id="lname" placeholder="Last Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_email" id="lname" placeholder="Your Mail" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="txt_contact" id="lname" placeholder="Contact No" required />
</div>
// here is the problem
<input type="file" name="image2" class="file" id="imgInp"/>
//here is the problem
<hr />
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
// submit form using $.ajax() method
$('#reg-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize() // it will serialize the form data
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...'); });
});
</script>
submit.php
<?php
$con = mysqli_connect("localhost","root","","table" ) or die
( "unable to connect to internet");
include ("connect.php");
include ("functions.php");
if( $_POST ){
$fname = $_POST['txt_fname'];
$lname = $_POST['txt_lname'];
$email = $_POST['txt_email'];
$phno = $_POST['txt_contact'];
$post_image2 = $_FILES['image2']['name']; // this line shows error
$image_tmp2 = $_FILES['image2']['tmp_name'];
move_uploaded_file($image_tmp2,"images/$post_image2");
$insert =" insert into comments
(firstname,lastname,email,number,post_image) values('$fname','$lname','$email','$phno','$post_image2' ) ";
$run = mysqli_query($con,$insert);
?>
You can use FormData, also I suggest you can change the elements id of the form, now all of them have ('lname') Try this with your current:
In yout HTML, put an ID to your file input
<input type="file" name="image2" id="name="image2"" class="file" id="imgInp"/>
And change the id of the other input.
In your JavaScript:
var frmData = new FormData();
//for the input
frmData.append('image2', $('#image2')[0].files[0]);
//for all other input
$('#reg-form :input').each(function(){
if($(this).attr('id')!='image2' ){
frmData.append($(this).attr('name'), $(this).val() );
}
});
$.ajax( {
url: 'URLTOPOST',
type: 'POST',
data: frmData,
processData: false,
contentType: false
}).done(function( result ) {
//When done, maybe show success dialog from JSON
}).fail(function( result ) {
//When fail, maybe show an error dialog
}).always(function( result ) {
//always execute, for example hide loading screen
});
In your PHP code you can access the image with $_FILE and the input with $_POST
FormData() works on the modern browsers.If you want for older browser support use malsup/form plugin
Your Form
<form method="post" action="action.php" id="reg-form" enctype="multipart/form-data" autocomplete="off">
Javscript
<script type="text/javascript">
var frm = $('#reg-form');
frm.submit(function (ev) {
var ajaxData = new FormData(frm);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: ajaxData,
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
In php extract($_POST) to get all input data and $_FILE for files
I'm following what this post mentioned to upload a file. A little difference is I added one more text input field on the form. The image file is uploaded to server successfully but it seems the value in input field doesn't get passed to PHP for database update. The database function is fired and database record added but missing the value from the form.
Can anyone point me out what I missed? Thanks.
$.validate({
form: '#frmSlide',
modules: 'file, html5',
validateOnBlur: false,
errorMessagePosition: 'top', // Instead of 'element' which is default
scrollToTopOnError: false, // Set this property to true if you have a long form
onSuccess: function($form) {
var file_data = $('#a_imgfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'slide_upd.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
alert(data);
}
});
}
});
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSlide">
<div class="form-group">
<label class="col-sm-4 control-label" for="imgfile">Image file</label>
<div class="col-sm-8">
<input type="file" id="a_imgfile" data-validation="required mime size" data-validation-allowing="jpg, png, gif" data-validation-ratio="1:1" data-validation-max-size="1M" data-validation-error-msg="An image file is mandatory." />
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-md-offset-4" id="image-holder">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="seq">Sequence</label>
<div class="col-sm-8">
<input class="form-control server" name="a_seq" id="a_seq" type="number" min="1" max="4" value="" placeholder="Enter display sequence of this slide" data-validation-error-msg="Only 1 to 4 is allowed." />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button name="btnUpd" id="btnUpd" type="submit" class="clsUpd btn btn-primary"><i class="fa fa-floppy-o"></i> Update</button>
</div>
</div>
</form>
<?php
$image_name = $_FILES['file']['name'];
$image_size = $_FILES['file']['size'];
$image_temp = $_FILES['file']['tmp_name'];
move_uploaded_file($image_temp, 'img/'.$image_name);
$seq = $_POST['a_seq'];
addSlide($seq);
?>
function addSlide($seq) {
$seq = (int)$seq;
mysql_query("INSERT INTO slide (seq, lastchgat)
VALUES ('$seq', now())") or die(mysql_error());
}
The a_seq is not appended to the form_data.
add var a_seq = $('#a_seq').val();
form_data.append('a_seq', a_seq);
Should be good to go
I think this will fix your problem
$.validate({
form: '#frmSlide',
modules: 'file, html5',
validateOnBlur: false,
errorMessagePosition: 'top', // Instead of 'element' which is default
scrollToTopOnError: false, // Set this property to true if you have a long form
onSuccess: function($form) {
//var file_data = $('#a_imgfile').prop('files')[0];
//var form_data = new FormData();
//form_data.append('file', file_data);
//------ instead of three lines i just did this and works fine for me -------
var formData=new FormData($('#frmSlide')[0]);
$.ajax({
url: 'slide_upd.php', // point to server-side PHP script
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function(data) {
alert(data);
}
});
}
});
i'm trying to display a success /error message when a user login to my website through a hidden div, that is displayed by on click event jQuery. Looks like whatever i try, nothing works. Already searched over and over but can't find a solution. Any help please?
My current code:
$(document).on('submit', '#loginform',function(e){
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'portal/login',
type: 'POST',
dataType:"json",
data:formData,
contentType: false,
processData: false,
success: function(data) {
if(data.status == 1) {
console.log(data.status);
$('.login_result.success').show();
} else {
$('.login_result.error').show();
}
}
});
});
$('.modaltrigger').on('click',function() {
$('#loginmodal').fadeIn(500);
});
So i'm using Ajax to validate the user login, and then at success i want to fadeIn the .login_result
EDIT
My HTML code:
<div id="loginmodal" style="display:none;">
<div id="placeHolder">
<div class="main_logo"><img src="images/logo.jpg"></div>
<form action="portal/login" method="post" class="login" name="loginform" id="loginform">
<input id="user_email" name="user_email" placeholder="Email" type="text">
<input id="user_password" name="user_password" placeholder="Senha" type="password">
<button class="search_button login_button" name="admin_login">Entrar</button>
<span><?php //echo $error; ?></span>
</form>
<div class="login_result success">Login Efetuado com sucesso, Redirecionando!</div>
<div class="login_result error">Login Inválido!</div>
</div>
As always thanks in advance if you can help with this one.
I'm trying to use Ajax to call a script and post the form data at the same time. Everything works as expected except the $POST data which comes back blank when I try to echo or print it. Can anyone shine a light on what I have missed here please?
<form id="guestlist" name="guestlist">
<?php // Collect CLUBS data to pass to guestlist script ?>
<input type="hidden" name="gl_clubname" value="<?php echo $ptitle; ?>" />
<input type="hidden" name="gl_clubnumber" value="<?php echo $phoneno_meta_value; ?>" />
<input type="hidden" name="gl_clubemail" value="<?php echo $email_meta_value; ?>" />
<?php // Collect USERS data to pass to guestlist script ?>
<input type="hidden" name="gl_name" value="<?php echo $fullname;?>" />
<input type="hidden" name="gl_email" value="<?php echo $email;?>" />
<input type="hidden" name="gl_dob" value="<?php echo $birthday;?>" />
<input type="hidden" name="gl_propic" value="<?php echo $profile_url;?>" />
<div id="clubcontactleft">
<textarea id="clubmessage" name="gl_message" placeholder="Your message" rows="4" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/userreview.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 94px; width:250px; margin-bottom:15px;"></textarea>
<input type="text" name="gl_when" placeholder="Enquiry Date" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/calendaricon.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
<input type="text" name="gl_phonenumber" placeholder="Phone Number" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/phonecall.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
</div>
<div class="guestlistbutton">Send Message</div>
</form>
<script type="text/javascript">
$(document).ready(function($){
$(".guestlistbutton").on('click',function(event) {
event.preventDefault();
$("#clubcontactform").empty();
var url = "http://www.xxxxxx.com/wp-content/themes/xxxxxx/guestlist.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#guestlist").serialize(), // serializes the form's elements.
success: function(data)
{
$('#clubcontactform').append(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
Here is the php file that it pulls in
<?php
echo 'Pulling in guestlist.php<br/>';
$gl_message = $_POST['gl_message'];
print_r($gl_message);
echo $gl_message;
?>
Thanks!
Every thing seems to be correct only you forget to include the jquery file. please include and try once. If still persist the issue will create the Jsfiddle
I checked your code in my local machine and I got the following error "Caution provisional headers are shown". If you have the same message in your browser console, this information can help you: "CAUTION: provisional headers are shown" in Chrome debugger
Also, I see that js work perfectly. Problem in your url address. Try send your form to itself, just write html part and php part of code in one file.
<div>
<form id="Get_FRm_Data">
/*
Some field using.....
/*
</form>
<button type="button" name="submit" class="submit_act">Submit</button>
</div>
<script>
var file_pathname = window.location.protocol + "//" + location.host + "/foldername/";
$(document).on("click", ".submit_act", function ()
{
var $this_val=$(this);
$this_val.html("Loading...").prop("disabled",true);
var $data_ref = new FormData($("#Get_FRm_Data")[0]);
$data_ref.append("action", "fileaction_name");
$pathname = file_pathname + "filename.php";
$.ajax({
url: $pathname,
type: 'POST',
data: $data_ref,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function (result, status)
{
console.log(result);
if (status == "success")
{
$this_val.html("Submit").prop("disabled",false);
}
}
});
});
</script>
<?php
if (isset($_POST['action']))
{
$action = $_POST['action'];
if($action=="fileaction_name")
{
print_r($_POST);
}
}
?>