0

I'm maiking simple form with image upload option. I have problem with getting access to my uploaded file through jQuery in my PHP code.

How I can check uploaded file name, size in PHP?

HTML:

    <form id="conversion_form" method="post" action="#" enctype="multipart/form-data">
            <input type="text" id="prize_name" size="25" value="">
<textarea rows="8" cols="75" name="lista_losowanie" id="lista_losowanie">
            <input id="file_img" type="file" name="image">
            <div id="uploadPreview"></div>
            </div>
            <p><input id="button_draw" class="btn btn-lg btn-success" type="submit" value="Losowanie" /></p>
            </form>

This is my Ajax, sending prize_name works good, but I have problem with my uploaded image. How I can send it in Ajax and receive in my PHP?

AJAX:

$('#button_draw').click(function(e) {
e.preventDefault();

    var formData = new FormData();
    // let's just take the first image
    var file = $('#file_img')[0].files[0];


    // but you also need to add the other fields to formData
    var lista = $(this).closest('form').find('#lista_losowanie').val();
    var prize_name = $(this).closest('form').find('#prizename').val();

    formData.append('prize_img', file);
    formData.append('lista', lista);
    formData.append('prize_name', prize_name);

    console.log(formData);
    alert (formData);


            $.ajax({
            context: this,
            url: './inc/new_draw.php',
            data: formData,
            type: 'POST',
            success: function(response){
            //odpowiedź serwera

            //Trzeba sparsować zwrot
            var json = JSON.parse(response);

            if(json.odp == 1){

            }

            if(response == 2){

            }

            },
            error: function(x,n,o){
            }
           });



  });

PHP:

<?php

include ("config.php");

$prize_name = mysqli_real_escape_string($con, $prize_name);
$prize_img = mysqli_real_escape_string($con, $prize_img);

//HOW I CAN GET ACCESS TO UPLOADED IMAGE? HOW I CAN CHECK FILE SIZE ETC. THIS BELOW DOESNT WORK.

        $file_size = $prize_img['size'];
        $file_name = $prize_img['name'];
        $file_type = $prize_img['type'];

        echo $file_size;

        if ($prize_name == NULL) {
            $problem = TRUE;
            $problem_code = 1;
            echo json_encode($dodano);
        }
?>
Michał Lipa
  • 968
  • 2
  • 12
  • 22
  • read this please [Handling file upload](http://php.net/manual/en/features.file-upload.php) and check the post method upload – zeidanbm Mar 08 '15 at 09:35
  • Duplicate? http://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php/23981045#23981045 – bloodyKnuckles Mar 08 '15 at 09:46
  • Is this for production, or for a school assignment? If not for school, then you may wish to look at http://stackoverflow.com/questions/28608548/krajee-file-input-widget-upload-method-throws-exception/28609251#28609251 – cssyphus Mar 08 '15 at 16:06

1 Answers1

0

The Ajax method does support file upload, but only in newer browsers. For that you could use the XmlHttpRequest2 object and in your case ideally with a FormData object which will contain all the data (+ image) you want to submit, see this Article.

If you want to go with this, you can get the file via the HTML5 File API, quick example:

var formData = new FormData();
// let's just take the first image
var file = $('#fileinput').files[0];

// but you also need to add the other fields to formData
var lista = $(this).closest('form').find('#lista_losowanie').val();
var prize_name = $(this).closest('form').find('#prizename').val();

formData.append('prize_img', file);
formData.append('lista', lista);
formData.append('prize_name', prize_name);

// now you pass the formData object as data
$.ajax({
    context: this,
    url: './inc/new_draw.php',
    data: formData,
    // ....
});

As you can see, files is an array - so if you would use multiple select on your file input field, you could simply iterate through that array to get all selected images.

On the PHP side, if you use FormData, you will need to use the $_FILES array. See here: PHP $_FILES array.

From my example above, you would access the array like this (also added extension):

$size = $_FILES['prize_img']['size']
$name = $_FILES['prize_img']['name']
$type = $_FILES['prize_img']['type']
$extension = pathinfo($name, PATHINFO_EXTENSION);

With the XHR2 you could also do cool stuff such as tracking the progress of your uploaded file (progress bar). If you need compatibility for older browsers, there is an approach using iframes: example.

Avinor
  • 846
  • 1
  • 8
  • 19
  • Yep, but I'm wondering how to use $_FILE array with data from AJAX. My code doesnt work. `//AJAX var prize_img = $(this).closest('form').find('#file_img').val();` `//PHP $prize_img = mysqli_real_escape_string($con, $prize_img); $file_size = $_FILES['$prize_img']['size'];` – Michał Lipa Mar 08 '15 at 09:50
  • Did you try using e.g. `prize_img = $(this).closest('form').find('#file_img').files[0];` (instead of `val()` you use `files` which is an array)? However this only works if your browser supports the HTML5 File API. – Avinor Mar 08 '15 at 09:56
  • Just to sort out any misunderstanding: If you submit a file to `PHP`, it will not be inside the `$_POST` array. Instead, you can access the file with the `field name` you provided directly in the `$_FILES` array, see my edited answer. – Avinor Mar 08 '15 at 10:14
  • Thanks for your help. Now I got problem with sending through AJAX my file. This `HTML 5 File Api` doesnt work for me. This code doesnt work: `var lista = $(this).closest('form').find('#lista_losowanie').val(); var prize_name = $(this).closest('form').find('#prizename').val(); var file = $('#file_img').files[0]; var formData = new FormData(); formData.append('prize_img', file); $.ajax({ context: this, url: './inc/new_draw.php', data: {'lista': lista, 'prize_name': prize_name, 'prize_img': prize_img},` – Michał Lipa Mar 08 '15 at 11:09
  • I've edited my answer, it's because you need to put all fields into the `FormData` object and then pass that object for the ajax `data` parameter. – Avinor Mar 08 '15 at 11:29
  • I use your code, but now whole script doesnt work not only a image upload. I got 0 errors in console, 0 post data. I edited my question (ajax code). – Michał Lipa Mar 08 '15 at 13:55
  • Ok. We will get this working. First, for the line `var lista = $(this).closest('form').find('#lista_losowanie').val();` I do not see any field in the form that has this id? Second, can you add some `console.log()` to see what happens inside your JS? E.g. after all the `appends` you could do a `console.log(formData);`. Another question, why do you set the Ajax `context` to the button? It should have no impact, just asking. Last question: Which browser are you using? – Avinor Mar 08 '15 at 14:47
  • Thanks :) var lista is ok, I got that in my new html code. The whole code doesnt work after var file. I changed var file to `var file = $('#file_img')[0].files[0];` now alerts and consol logs works. I added `alert(formData) `and `consol.log(formData)` after appends. Alert gives me `[object formData]` and in consol log I got `NULL FormData`. Hmm no idea why Ajax context to button, just wanted to work after click. I'm using new Chrome. I have edited my Ajax code in question once again. – Michał Lipa Mar 08 '15 at 15:12
  • Do you have more than one element with the `id="file_img"`? Ok so what is happening now, is the ajax request sent? Regarding `context` I recommend you to read the jQuery docs, I think you don't need it in this case but it really depends on what you want to do (and as said, should have no impact on the functionality at all).Browser is fine. – Avinor Mar 08 '15 at 15:55