AJAX file upload giving undefined file error - javascript

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) {
...
});

Related

Return mysql fetch data and insert into form field value

i have a list of clients on a page, each client has an icon to click on to edit the client details.
<i class="fas fa-user-edit gray openModal" data-modal="modal2" client="'.$client['id'].'"></i>
Everything is good up to this point. click the icon the proper modal opens and it triggers the js file just fine. (I did alot of console logs to ensure). The client variable in my jquery file holds fine and i'm able to get it passed to the php file.
in the php file i'm able to pull the information into an array and i was able to just echo the $client['firstName'] and have it show in the console.
when i moved to getting that information and parse it as the Json is when i got lost. Can someone please help me take my result and load into my form fields. The code i have now may be totally off because i've been playing with different code from different searches.
form (shortened to two fields for ease of example)
<form id="form" class="editClient ajax" action="ajax/processForm.php"
method="post">
<input type="hidden" id="refreshUrl" value="?
page=clients&action=view&client=<?php echo $client['id'];?>">
<input type="hidden" name="client" value="<?php echo $client['id'];?>">
<div class="title">
Client Name
</div>
<div class="row">
<!-- first name -->
<div class="inline">
<input type="text" id="firstName" name="firstName" value="<?php echo $client['firstName']; ?>" autocomplete="nope" required>
<br>
<label for="firstName">First Name<span>*</span></label>
</div>
<!-- last name -->
<div class="inline">
<input type="text" id="lastName" name="lastName" value="<?php echo $client['lastName']; ?>" autocomplete="nope" required>
<br>
<label for="lastName">Last Name<span>*</span></label>
</div>
</form>
javascript/jquery file
$('.openModal').on('click', function() {
//$('body, html, div').scrollTop(0);
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
var data = result.rows;
$("#firstName").val(data[0]);
}
})
});
php file
<?php
include('../functions.php');
$sql = 'SELECT * FROM clients WHERE id="'.$_POST['id'].'"';
$result = query($sql);
confirmQuery($result);
$data = fetchArray($result);
echo json_encode(['response' => $data, 'response' => true]);
?>
UPDATED ----------
Here is my final js file that allowed my form values to be set.
$('.openModal').on('click', function() {
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
$("select#primaryContact").append( $("<option>")
.val(result[0].primaryContact)
.html(result[0].primaryContact)
);
$("select#primaryContact").append( $("<option>")
.val("")
.html("")
);
if (result[0].email !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].email)
.html(result[0].email)
);
}
if (result[0].phoneCell !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneCell)
.html(result[0].phoneCell)
);
}
if (result[0].phoneHome !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneHome)
.html(result[0].phoneHome)
);
}
$("input#firstName").val(result[0].firstName);
$("input#lastName").val(result[0].lastName);
$("input#address").val(result[0].address);
$("input#city").val(result[0].city);
$("input#zip").val(result[0].zip);
$("input#email").val(result[0].email);
$("input#phoneCell").val(result[0].phoneCell);
$("input#phoneHome").val(result[0].phoneHome);
$("input#phoneFax").val(result[0].phoneFax);
$("input#source").val(result[0].source);
$("input#referBy").val(result[0].referBy);
$("input#client").val(result[0].id);
}
})
});

Add image uploading function inside this existing ajax code

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

Submit text-data AND file to php script with jquery

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

WordPress is giving me 404 page not found for functions.php?

<script>
$(document).ready(function(){
$("#agentsubmit").click(function(){
var ajaxurl = '<?php echo site_url();?>/wp-admin/admin-ajax.php';
$.ajax({
type: "POST",
dataType : "json",
url : ajaxurl,
data : {
action :'join_mailinglist_callback',
'email': email
},
success:function(data){
// your success call
$(".alert-message").html(data);
}
});
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<form class="agnet-contact-form" name="contact_form" method="post" action=" " id="agnet-contact-form1">
<div class="col-xs-6 col-sm-6 col-md-6">
<input type="text" name="full_name" placeholder="Name" required>
<input type="text" name="phone_number" placeholder="Phone" required>
<input type="text" name="email_address" placeholder="Email" id="contactemail" required>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<textarea name="message" placeholder="Message" required></textarea>enter code here
<input type="submit" class="agent_submit" name="submit" id="agentsubmit" value="submit now">
</div>
</form>
Here is code which I wrote in functions.php which is action of ajax.
/* send mail using ajax*/
add_action('wp_ajax_join_mailinglist', 'join_mailinglist_callback');
add_action('wp_ajax_nopriv_join_mailinglist', 'join_mailinglist_callback');
function join_mailinglist_callback() {
$email = $_POST['email'];
if(!empty($email)) {
$yourEmail = 'fc#abc.com';
$subject = 'contacting Us';
$success = mail($yourEmail, $subject, $email);
if(!empty($success)) {
echo 'Email sent successfullly.';
} else {
echo 'Email Does not send sorry please try again.';
}
}
die();
}
This code gave me error NetworkError: 404 Not Found - http://localhost/wordpress/functions.php
I have used jquery and also include min.js file in my code.And pass the url of admin ajax but alert is not working in a response I have tried out.
What is the reason for that and how solve it.
If email sent successfully give response and it will write on Div that Email sent successfully Otherwise it says that Email don't send from the functions.php file
Refer to wp_ajax.
The code in for ajax function is wrong try this :
<script>
$(document).ready(function(){
$("#agentsubmit").click(function(){
var ajaxurl = '<?php echo site_url();?>/wp-admin/admin-ajax.php';
$.ajax({
type: "POST",
dataType : "json",
url : ajaxurl,
data : {
action :'join_mailinglist',
'email': email
},
success:function(data){
// your success call
$(".alert-message").html(data);
}
});
});
});
</script>

Getting form $_POST data from Ajax/Jquery in php

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

Categories

Resources