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>