How to upload the file without submitting the form? - php

I am trying to upload a file with ajax and php without page refresh and for submit.
my code is able to run and alert the valid message if I just do the preg_match, but when I add the rest of the validation which need to use the $_FILES[$filrec]["tmp_name"], it won't alert me the valid message.
What is wrong here? isn't it possible to upload the file without submitting the form with the following method?
There are bunch of different suggestions and examples with more complicated javascript or jquery methods, but I am trying to simply the ajax and leave the rest for PHP. is that possible with my bellow ajax function ?
Javascript :
var fileselected = $("#browse").val().replace(/C:\\fakepath\\/i, '');
setTimeout(function() {
$.ajax({
type: 'POST',
url: "ajax/extval.php",
data: {fileprs: fileselected},
dataType: 'json',
cache: false,
success: function(resuval) {
// file validation result
if (resuval === "valid"){
alert ("valid")
PHP :
<form id="upload" method="post" class="<?php echo $orvalue."<separator>".$user_id ?>" action="" enctype="multipart/form-data">
<div id="formcontent">
<label class="required" for="unitprice" title="Unit price"><input type="text" id="unitprice" name="unitprice" />Unit price</label>
<label class="required" for="qty" title="How many pcs"><input type="text" id="qty" name="qty" />Quanity</label>
<label class="required" for="express" title="Express within China"><input type="text" id="express" name="express" />Express</label>
<label class="required" for="linkURL" title="Insert a full URL http:\\"><input type="text" id="linkURL" name="linkURL" />Link</label>
<label for="yourdesc" title="Describe your need clearly"><textarea id="yourdesc" name="yourdesc"></textarea>Description<li><font size="-2">You can type 400 letters only, you typed :</li><li id="lettercounter"></li>letters</font></label>
<label for="formsubmit" class="nocontent"><input type="button" id="submitButton" href="#" class="progress-button" value="Add to order" /><strong>Note:</strong> Items marked <img src="../../images/required.jpg" alt="Required marker" width="20" height="20" /> are required fields</label>
</div>
</form>
PHP :
$filrec =mysql_real_escape_string($_POST['fileprs']);
if(preg_match("/\.(gif|png|jpg|JPG|jpeg|bmp|BMP)$/", $filrec))
{
$fileType = exif_imagetype($_FILES[$filrec]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
$allin = "valid";
echo json_encode($allin);
}
Appreciated

You can use the following PHP code to get the file received from Ajax:
$data = split(",",file_get_contents('php://input'));
$img_data = base64_decode($data[1]);
file_put_contents( 'uploads/' . $_SERVER['HTTP_X_FILENAME'],
$img_data );

You can use Following Ajax POST Request this will help you
<script>
$(document.body).on('click','.postDefects',function(){
var form_data = new FormData();
var defect = $(this).closest('tr').find( "input[name='defect_id']" ).val();
var txt_defect=$("#text_defect").val();
var upload_defect = document.getElementById("upload_defect").files[0];
form_data.append("upload_defect",upload_defect);
form_data.append("defect_id",defect_id);
form_data.append("txt_defect",txt_defect);
console.log(form_data);
$.ajax({
url:"postsample_defects.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading..</label>");
},
success:function(data)
{
$('#uploaded_image').html(data);
}
});
});
</script>

Related

Ajax file upload with Input texts - $_POST & File is empty

Hi I have problem for no reasons. I need help. I am trying to upload files and text input to my db and I am using ajax and PHP code for that. I have looked through many StackOverflow posts and stuffs but still unable to fix this.
HTML:
<form method = "POST" enctype = "multipart/form-data" id="myform">
<label class="form-label text-start">Enter your Name</label>
<input class="form-control" name="name" type="text" id="myname" placeholder="John">
<label class="form-label">Title</label>
<input class="form-control" type="text" name="name" id="title" placeholder="Operator">
<label class="form-label">Your Cute Photo (format: jpg and png only, less than 500kb)</label>
<input class="form-control" name="file" id="imgfile" type="file">
</form>
JQuery/Javascript:
var file_data = $('#imgfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', $('#name').val());
form_data.append('title', $('#title').val());
$.ajax({
type: 'POST',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
url: 'save_data.php',
data: {form_data},
success: function(data){
//alert(php_script_response);
alert(data)
window.location = 'account.php';
}
});
Error:
Undefined index name
Undefined index title
Undefined index file
PHP:
$name = $_POST['name'];
$title = $_POST['title'];
$file = $_FILE...
//all the other PHP codes
JQuery version
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
There are two elements in your form with the same name so it is a lottery which is used when you request it. Admittedly you were using the element ID rather than the names so probably perfectly OK. With FormData you can supply a reference to the form itself as the argument and that should take care of the rest for you. You can supply that formdata object directly as the data parameter in the ajax request. I'm not a user of jQuery so had to mix your jQuery with some vanilla js but you should see the idea.
const form = document.forms.usrupload;
form.bttn.onclick = () => {
var form_data = new FormData(form);
$.ajax({
type: 'POST',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
url: 'save_data.php',
data: form_data,
success: function(data) {
alert(data)
window.location = 'account.php';
}
});
}
label {
display: block;
width: 100%;
margin: 1rem;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
`label` elements should be associated with an input in one of two ways:
Using the `for="elemID"` or by wholly encompassing the input element as below
-->
<form name="usrupload" method="POST" enctype="multipart/form-data">
<label class="form-label text-start">Enter your Name
<input class="form-control" name="name" type="text" placeholder="John" />
</label>
<label class="form-label">Title
<input class="form-control" type="text" name="title" placeholder="Operator" />
</label>
<label class="form-label">Your Cute Photo (format: jpg and png only, less than 500kb)
<input class="form-control" name="file" type="file" />
</label>
<input type='button' name='bttn' value='Submit' />
</form>
The error is on
data: {form_data},
To change to
data: form_data,

handle posted formData object with files and other inputs in php

I need to handle inputs from form post and I have no idea, how to do it in php, because when I write for example $_POST["header"], it var_dumps null.
I am creating formData object and inserting all inputs from form. Then posting it with ajax.
Can you please help me? I need to handle "header", "content", "password" and files.
<form method="post" enctype="multipart/form-data" id="uploadFiles">
<label for="newsHeader" id="headerLabel">Nadpis</label>
<input type="text" name="newsHeader" id="newsHeader">
<label for="content" id="contentLabel">Text novinky</label>
<textarea name="content" id="content"></textarea>
<label for="files" id="filesLabel">Fotky</label>
<input type="file" name="files" id="files" accept="image/jpeg" multiple>
<label for="password" id="passwordLabel">Heslo pro upload</label>
<input type="text" name="password" id="password">
<button type='submit' id='uploadFilesSubmit'>NAHRÁT</button>
</form>
$("#uploadFiles").submit(function(event){
event.preventDefault();
var formDataObj = new FormData(),
header = $("#newsHeader").val(),
content = $("#content").val(),
password = $("#password").val();
formDataObj.append("header", header);
formDataObj.append("content", content);
formDataObj.append("password", password);
$.each($("#files")[0].files, function(i, file) {
formDataObj.append('file', file);
});
console.log(Array.from(formDataObj));
$("#uploadFilesSubmit").html("<div class='buttonSubmitIcon'><i class='fas fa-sync'></i></div>");
$.ajax({
method: "POST",
url: "uploadNews.php",
data: {
formDataObj: formDataObj
},
dataType: 'json',
contentType: false,
processData: false,
success: function(results){
}, error: function(){
}
});
});
In uploadNews.php I have this:
exit(json_encode(var_dump($_POST["header"])));
It always returns "Undefined index: header", same as content or count($_FILES["file"]["name"])
All I want is to get somehow to posted values.. Thank you very much
You just to pass the actual formDataObj variable via your $.ajax. This is not the correct syntax to pass FormData via ajax => formDataObj: formDataObj
A FormData itself is an object which stores your data so what you are doing is making another object on top of it when you pass it via data
You can now var_dump(header) or var_dump($_FILES["file"]["name"]) to see everything coming to your PHP file.
Live Demo: (Change you jQuery code to this below and it will just work fine)
$("#uploadFiles").submit(function(event) {
event.preventDefault();
var formDataObj = new FormData(),
header = $("#newsHeader").val(),
content = $("#content").val(),
password = $("#password").val();
formDataObj.append("header", header);
formDataObj.append("content", content);
formDataObj.append("password", password);
$.each($("#files")[0].files, function(i, file) {
formDataObj.append('file', file);
});
$("#uploadFilesSubmit").html("<div class='buttonSubmitIcon'><i class='fas fa-sync'></i></div>");
$.ajax({
method: "POST",
url: "uploadNews.php",
data: formDataObj, //just pass the form Data object.
dataType: 'json',
contentType: false,
processData: false,
success: function(results) {
},
error: function() {
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" id="uploadFiles">
<label for="newsHeader" id="headerLabel">Nadpis</label>
<input type="text" name="newsHeader" id="newsHeader">
<label for="content" id="contentLabel">Text novinky</label>
<textarea name="content" id="content"></textarea>
<label for="files" id="filesLabel">Fotky</label>
<input type="file" name="files" id="files" accept="image/jpeg" multiple>
<label for="password" id="passwordLabel">Heslo pro upload</label>
<input type="text" name="password" id="password">
<button type='submit' id='uploadFilesSubmit'>NAHRÁT</button>
</form>

Sending file together with form data via ajax post in php

Here is what I'm trying to do.
I'm uploading a file on the form and send the data via ajax.
Here is my code:
<form enctype="multipart/form-data" name="addcert_form" id="addcert_form" method="post" >
<input type='hidden' id="staffid" name="staffid" value="<?php echo $staffid; ?>" />
<label for="certNumber"><?php echo("Certification Number"); ?></label>
<input type="text" class="form-control certNumber" id="certNumber" name="certNumber" >
<div class="form-group" style="margin-bottom: 0px;margin-left: 15px;">
<label for="file-upload"><?php echo('File Upload'); ?></label>
<input type='hidden' id="file-upload-hidden" name="file-upload-hidden" />
<input type="file" name="file-upload" id="file-upload" accept="application/pdf">
</div>
</form>
$(document).on('change', "#cert-upload", function() {
var ajaxurl = generalObj.ajax_url;
var form = $("#addcert_form");
var params = form.serializeArray();
var formData = new FormData();
var file_data = $('#file-upload').prop('files')[0];
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
formData.append('file-upload', file_data);
$.ajax({
url: ajaxurl + "rzvy_staff_ajax.php",
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (res) {
if(res=="file-uploaded"){
swal.fire(generalObj.updated, generalObj.cert-upload_changed, "success");
//location.reload();
}
}
});
});
However, when I see the information, I'm only getting the file info.
I have tried doing $_POST, and $_FILES, however, I'm not getting the information from the form. How can I get all of the information from the form when I upload the file?
Thank you,
Kevin
Here is what I found out. The data was coming over, I should have used both $_FILES and $_POST

AJAX Form refreshing page when using move_uploaded_file()

I've built a simple form that posts data using jQuery AJAX to a PHP endpoint.
Everything works fine and the data is all being posted correctly.
The problem I am having is once the file is added to the input and submitted, the page refreshes. It doesn't refresh if I don't add the file, and doesn't refresh if I take the file input out altogether. Only when the file is successfully moved.
I need the page not to refresh, hence the use of AJAX in the first place.
Form:
<form id="form-send">
<div class="c-form-group grid-2">
<label for="first_name">First Name</label>
<input class="c-form-control" type="text" id="first_name" name="first_name" placeholder="Joe" value="Joe">
</div>
<div class="c-form-group grid-2">
<label for="file">Add File</label>
<input class="c-form-control c-form-control--file" type="file" id="file" name="file">
</div>
<div class="c-btn-group">
<button id="send" class="c-btn c-btn--primary" type="submit">Submit</button>
</div>
</form>
Ajax:
$("#form-send").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: '/send-form.php',
cache: false,
processData: false,
contentType: false,
data: new FormData(this),
success: function(data) {
console.log(data);
},
error: function(response) {
console.log('An error ocurred.');
},
});
})
Endpoint:
<?php
$uploadDir = 'uploads/';
// If post
if (isset($_POST)) {
// Request Values
$firstname = $_REQUEST['firstname'];
$file = $_REQUEST['file'];
// Upload to folder
if(!empty($_FILES["file"]["name"])){
// File path config
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $uploadDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
echo "Success: File uploaded.";
} else {
echo "Error: Something went wrong.";
}
} else{
echo "Error: File is not the correct format.";
}
}
}
?>
As the ajax call is asynchronous, you have to prevent the form from submitting, and then when a result is returned, you check if it matches the condition and submit the form with the native submit handler, avoiding the preventDefault() in the jQuery event handler :
$("#form-send").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: '/send-form.php',
cache: false,
processData: false,
contentType: false,
data: new FormData(this),
success: function(data) {
console.log(data);
},
error: function(response) {
console.log('An error ocurred.');
},
});
});
You can remove the form tag that is responsible for refreshing the page. Else, you can change button to
<button id="send" class="c-btn c-btn--primary" type="button">Submit</button>
This is how I am able to achieve in one of my projects.Hope it helps
AJAX CALL:
var form_data = new FormData();
form_data.append('title',title);
form_data.append('body',body);
form_data.append('link',link);
$.ajax
({
url: 'blog_insert.php',
dataType: 'text',
cache : false,
contentType : false,
processData : false,
data: form_data,
type: 'post',
success: function(php_script_response)
{
$("#success-message").css('display','active').fadeIn();
var title = $('#title').val(' ');
var body = $('.nicEdit-main').html('');
//$('#sortpicture').prop(' ')[0];
var link = $('#link').val('');
}
});
HTML
Blog posted successfully
<div class="form-group">
<label for="exampleFormControlInput1">Blog Title</label>
<input type="text" class="form-control" required="" name="title" id="title" placeholder="Enter your blog title">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Write your blog body here</label>
<textarea class="form-control" name="body" id="body" ></textarea>
</div>
<div id="dropzoneFrom" class="dropzone">
<div class="dz-default dz-message">Test Upload</div>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Reference Link</label>
<input type="text" class="form-control" id="link" name="link" placeholder="Post a reference link">
</div>
<button type="submit" id="submit-all" class="btn btn-primary" name="submit" >Post</button>

Working with input type file AJAX/PHP

I have got this html/php in my index.php
if (isset($_POST['UploadMSub'])) {
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)) {
if ($fileP_error===0) {
if ($fileP_size<=2097152) {
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
$_SESSION['fileP']=$fileP;
$_SESSION['fileP_name']=$fileP_name;
$_SESSION['fileP_tmp']=$fileP_tmp;
$_SESSION['fileP_size']=$fileP_size;
$_SESSION['fileP_error']=$fileP_error;
$_SESSION['fileP_extension']=$fileP_extension;
$_SESSION['fileP_new_name']=$fileP_new_name;
}
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" type="text" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
And this ajax
$(".UploadMSub").click(function() {
var text=$(".Text").val();
var file=$("#Nameupload").val();
$.ajax({
type: "GET",
url: '../connect.php',
data: "Text=" + text+"&&file="+file,
success: function(data)
{
alert(data);
}
});
return false;
});
connect.php
if (isset($_GET['Text'])) {
$Text=htmlspecialchars($_GET['Text'],ENT_QUOTES);
$file=htmlspecialchars($_GET['file'],ENT_QUOTES);
echo $Text." ".$_SESSION['fileP_new_name'];
}
But when i submit form it returns(alerts)
"Undefine index ''fileP_new_name'"
Is there any other way of getting all information about file in my connect.php?
The problem is,
When you hit the submit button, the form doesn't get submitted, which means none of your session variables are set when you hit the submit button. Instead jQuery script runs straight away when you hit the submit button, and that's why you're getting this error,
Undefine index: fileP_new_name
From your question,
Is there any other way of getting all information about file in my connect.php?
So the solution is as follows. You have to change few things in your code, such as:
Add a name attribute in your <textarea> element, like this:
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
Instead of returning false from your jQuery script, use preventDefault() method to prevent your form from being submitted in the first place, like this:
$(".UploadMSub").click(function(event){
event.preventDefault();
// your code
});
If you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
Set the following options, processData: false and contentType: false in your AJAX request. Refer the documentation to know what these do.
So your code should be like this:
HTML:
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
jQuery/AJAX:
$(".UploadMSub").click(function(event){
event.preventDefault();
var form_data = new FormData($('form')[0]);
$.ajax({
url: '../connect.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data){
alert(data);
}
});
});
And on connect.php, process your form data like this:
<?php
if(is_uploaded_file($_FILES['Upload_f']['tmp_name']) && isset($_POST['new_post'])){
// both file and text input is submitted
$new_post = $_POST['new_post'];
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)){
if ($fileP_error===0) {
if ($fileP_size<=2097152){
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
// your code
//echo $fileP_new_name;
}
?>

Categories