christopher's avatar

Article / Image Upload on the same form how to fetch Articles ID

Hello my friends :)

i am currently building a large form with the jquery ajax upload ( https://blueimp.github.io/jQuery-File-Upload/index.html ).

I have a Database Table for my articles and another for my images.

Okay .. If i upload an image in my form via the ajax uploader i cant get the ID of the current article because of course the article is not saved yet.

I have one form inside this form i have the inputs for the article and the ajax upload. I have only one controller method for the form. In this controller i fetch all the data.

How can i solve such a problem ?

I thought maybe i can solve this problem if i "autosave" the article i could get the ID. ( Because first i type some data for my article and then i upload my image ) All on the same form.

Or is there another / better way to solve this ?

0 likes
9 replies
SachinAgarwal's avatar

@hostianer I suggest do not upload the image via ajax. Anyone can load your server with multiple image uploads with that. You instead preview the uploaded image via a simple javascript function. And on submit of the form as post request. You can save article get the ID and save the image.
The simple javascript (with Jquery) function:

$(document).ready(function() {
    function readURL(input, id)
    {

        if (input.files && input.files[0]) {
            var pic_name = input.files[0].name;
            var fileTypes = ['.jpg', '.png', '.jpeg'];
            var pic_size = input.files[0].size / 1024; //in kb
            var dots = pic_name.split('.');

            //get the part AFTER the LAST period.
            var fileType = "." + dots[dots.length - 1].toLowerCase();
            //check for image type
            if (fileTypes.indexOf(fileType) == -1) {
                $('#' + id).val('');
                $('#' + id + '-placeholder').removeAttr('src');
                alert('This is not a image,Please upload image');
            }
            //check for image size
            else if (pic_size > 2048) {  //max size 2 mb
                $('#' + id).val('');
                $('#' + id + '-placeholder').removeAttr('src');
                alert('File size too large\nPlease upload file of size less than 2MB');
            }
            else {
                var reader = new FileReader();
                reader.onload = function(e) {
                    $('#' + id + '-placeholder').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }

        }
        else {
          $('#' + id + '-placeholder').removeAttr('src');
        }
} //end of readURL function

    $("#logo").change(function(){
        var id='logo';
        readURL(this,id);
    });
});

This is for my requirement. You can modify the function as you want.

christopher's avatar

This is only for a Backend so the ajax upload is no problem.

But this does not solve the actual question :)

SachinAgarwal's avatar

@hostianer You cannot get the ID of the article before saving it. So you have to save it first. And If you still want to go with the ajax then I have 2 solutions :

  1. After ajax request for image upload, save the image on the server and store the image name in session.
    Now on submit of the post, 1st save the post and then get the image name from the session and then store it in database. As you will have post id as well.

  2. you can get the next incremental ID from the database. ie., you can get the id the next insert will create (works only for incremental columns) like this:

SHOW TABLE STATUS FROM `DatabaseName` LIKE 'TableName' ;

// or You can get exactly this information by using this query:

SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND   TABLE_NAME   = 'TableName';

But 2nd solution is not so reliable as if 2 persons try to save at same time, then it will mess up things. If you are sure only 1 person at a time is going to post something then only use it.

1 like
christopher's avatar

Yes i think your first solution would fix it. I will try this if i`m home, thank you !

But the next problem would be: There are up to 16 images. 4 images for each season ( winter, summer .. )

Is there a "smarter way" then:

Session::put('winter_1', 'getwinter1');
Session::put('winter_2', 'getwinter2');
Session::put('winter_3', 'getwinter3');
....

With this method i would have 16 lines of code only to set the sessions :)

SachinAgarwal's avatar

@hostianer You can do it with foreach. in less amount of lines ;)

$i = 1;
foreach($images as $image) {    // Assuming you have stored you image names in array $images
    Session::put("winter_.$i",  $image);
    $i++;
}

And there are multiple ways of doing it. :)

othmanus's avatar

I've faced the same situation and my solution was to declare the article_id (in images table) as nullable (assuming that you have a simple hasMany relationships). Then when I upload the image via ajax, I create a hidden input in the article form containing the image id. And then, associate the Image with the actual Article in the store function.

othmanus's avatar

@SachinAgarwal there's always back-end validations (image exists, file exists, etc.). Although, any form is susceptible...

Please or to participate in this conversation.