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
Related
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,
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>
I am building a site, on which you can upload posts, just like facebook.
Everything works great except that at the moment you upload a post and after you uploaded it you can upload images to that post.
I would like to be able to upload the images to the post and then upload the post with the pictures. Here is my attempt:
The database image table
+-------------------------------------------------+
| image_id | user_id | image_name | post_id |
| 1 | 1 | bla | 2 |
+-------------------------------------------------+
The view
<script>
$(function () {
$("#imageUpload").submit(function (e) {
e.preventDefault();
var formData = new FormData($('#imageUpload')[0]);
$.ajax({
url: 'post/create', //Trying to call the controller
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
});
</script>
<form action="<?php echo Config::get('URL');?>post/create" method="post" id="imageUpload" enctype="multipart/form-data">
<input type="text" name="post_text" placeholder="Post something" />
<input type="file" name="images[]" multiple required />
<input type="submit" value='post' autocomplete="off" />
</form>
The controller
public function create()
{
PostModel::createPost(strip_tags($_POST['post_text']));
PostModel::uploadPostImages($_POST['post_id']);
}
I leave out the model, as the functions there work fine.
How can I get the post id to use it in the image table before posting the post?
I would be beyond thankful for any kind of help!!
UPDATE
<script>
$("#imageUpload").submit(function (e) {
var fd = new FormData();
var imagefile= document.getElementById('imagefile');
var files = imagefile.files;
for (var i = 0; i < files.length; i++)
{
var file = files[i];
fd.append('imagefile[]', file, file.name);
}
fd.append("post_text", document.getElementById('post_text').value);
fd.append("post_id", document.getElementById('post_id').value);
$.ajax({
url: 'post/create',
type: 'POST',
data: fd,
cache: false,
contentType: false,
processData: false
});
return false;
});
});
</script>
<form action="<?php echo Config::get('URL');?>post/create" method="post" id="imageUpload" enctype="multipart/form-data">
<input type="text" name="post_text" id="post_text" placeholder="Post something" />
<input type="file" name="images[]" id="imagefile" multiple required />
<input type="hidden" name="post_id" id="post_id" value="post_id" />
<input type="submit" value='post' autocomplete="off" />
</form>
You cannot directly upload image via jquery ajax. Moreover you are allowing multiple files to be uploaded via ajax. Here is your code. It will let you upload multiple images with the input text value too.
$("#imageUpload").submit(function (e) {
var fd = new FormData();
var imagefile= document.getElementById('imagefile');
var files = imagefile.files;
for (var i = 0; i < files.length; i++)
{
var file = files[i];
fd.append('imagefile[]', file, file.name);
}
fd.append("post_text", document.getElementById('post_text').value);
fd.append("post_id", document.getElementById('post_id').value);
$.ajax({
url: 'post/create', //Trying to call the controller
type: 'POST',
data: fd,
cache: false,
contentType: false,
processData: false
});
return false;
});
});
Your updated html
<form action="<?php echo Config::get('URL');?>post/create" method="post" id="imageUpload" enctype="multipart/form-data">
<input type="text" name="post_text" id="post_text" placeholder="Post something" />
<input type="file" name="images[]" id="imagefile" multiple required />
<input type="hidden" name="post_id" id="post_id" value="<?=$_GET['post_id']?>" />
<input type="submit" value='post' autocomplete="off" />
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>
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;
}
?>