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" />
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>
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
HTML Form:
<form enctype="multipart/form-data" method="post" name="fileinfo" id="myForm">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus id="userid" name="userid" placeholder="email" required size="32" maxlength="64" /><br />
<label>File to stash:</label>
<input type="file" name="fileToUpload[]" id="fileToUpload[]" required />
<input type="file" name="fileToUpload[]" id="fileToUpload[]" required />
<input type="submit" id="save" value="Stash the file!" />
</form>
I have used formdata to the best of my knowledge but I am not sure if I have done it right.
Javascript Code:
<script type="text/javascript">
$('#save').click(function(event){
event.preventDefault();
var fd = new FormData(document.querySelector("form"));
var ins = document.getElementById('fileToUpload[]').files.length;
console.log(ins);
if (ins != 0) {
fd.append("fileToUpload[][]", document.getElementById('fileToUpload[]').files[0]);
fd.append("Email", $('#userid').val());
for (var pair of fd.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
console.log(data);
}
});
}
else{
console.log("Nothing attached ");
}
})
</script>
In my upload.php file i am just trying to print the names. but i Am always getting count value as 3 whatever be the number of files uploaded on the front end, even if I don't upload any files at all, it gives the value 2.
<?php
$count = count($_FILES['fileToUpload']['name']);
echo $count;
for ($i = 0; $i < $count; $i++) {
echo 'Name: '.$_FILES['fileToUpload']['name'][$i].'\r\n';
}
?>
I am doing this for the first time. I have no idea where I am going wrong. Thanks in advance.
PFB my Html code :
<form id="form" enctype="multipart/form-data">
<label>File One</label>
<input type="file" name="file[]" id="file[]">
<br/>
<label>File Two</label>
<input type="text" id="name" name="name">
<input type="file" name="file[]" id="file[]">
<br/>
<label>File Three</label>
<input type="file" name="file[]" id="file[]">
<input type="submit" id="submit" name="submit" value="Submit">
</form>
I am trying to submit this form using ajax as below :
<script type="text/javascript" >
$(function() {
$('#form').submit(function(event) {
var name = $("#name").val();
var file[] = $("#file[]").val();
var dataString = 'name='+name+'&file[]='+file[];
$.ajax({
type: "POST",
url: "k.php",
data: dataString,
success: function(data123){
alert(data123);
}
});
return false;
});
});
</script>
But its not working. i:e the below line :
var file[] = $("#file[]").val();
var dataString = 'name='+name+'&file[]='+file[];
Any help would be highly useful.
I need to submit multiple photos along with text fields using ajax function but I am stuck in this issue from the past many days.
For uploading files using ajax, you need to do some extra work using the FormData object.
Check out http://blog.teamtreehouse.com/uploading-files-ajax for an example of how to do this.