0

I tried to research pretty much everything already, but I didnt find the final solution to fix my code. As you can see in the debug image, the file prop can be read. In PHP, I the result of print_r($_FILES); exit; is an empty array. The problem seems to be event.preventDefault();. The submit has to be prevent but the file still has to be generated.

JS Javascript debu

    $("#cardgeneratorForm").on("submit", function (event) {
        event.preventDefault();

        var artworkimageinput = $('#inputPicture').prop('files')[0];
        var artworkimage = new FormData();
        artworkimage.append('file', artworkimageinput); 

                $.ajax({
                    url: 'generatecard.php',
                    method: 'POST',
                    data: {
                        artworkimage: artworkimage,
                    },
                    cache: false,
                    processData: false,
                    contentType: false,
                    success : function(filename){
                    },
                    fail: function(){
                    }
                }); 

PHP

    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
    move_uploaded_file($_FILES['file']['tmp_name'], 'artwork/' . $_FILES['file']['name']); 
    }

HTML

<form class="cardgeneratorForm" id="cardgeneratorForm" method="post" enctype="multipart/form-data" action="generatecard.php">
                                    <div class="inputPicture-container custom-file col-12">
                                        <input type="file" name="file" class="custom-file-input" accept='.jpg, .jpeg, .png, .webp' id="inputPicture" lang="en">
                                        <label class="custom-file-label" for="inputPicture">Card Picture</label>
                                    </div>

     <button class="btn btn-primary btn-block btn-xs reset-button">
                                            <span><i class="fas fa-redo"></i>Reset</span>
                                        </button>
</form>
2
  • that first 3 lines of code needs to be inside the submit handler Commented Nov 16, 2019 at 11:14
  • you are right, they are, i wrote it a bit complicated actualy since the code is alot bigger and i tried to short it to the relevent code. I edited it! Commented Nov 16, 2019 at 11:43

2 Answers 2

1

Here's how you can do this.

$('#cardgeneratorForm').on('submit',function(e) {
    e.preventDefault();

    var formData = new FormData(this);

    $.ajax({
        method:$(this).attr('method'), //dynamically getting the method of the form
        url: $(this).attr('action'), //dynamically getting the action of the form
        data:formData,
        cache:false,
        contentType: false,
        processData: false,
        success:function(data){
            console.log("success");
            console.log(data);
        },
        error: function(data){
            console.log("error");
            console.log(data);
        }
    });
});

Start uploading immediately upon file selection (optional)

$("#inputPicture").on("change", function() {
    $("#cardgeneratorForm").submit();
});

I removed some extra brackets and now it's working. enter image description here

Hope it helps!!

Sign up to request clarification or add additional context in comments.

8 Comments

This doesnt help, it has the same result. The preventDefault stops it from working. The $_FILES is still empty.
@DappFuture I just edited my answer. Check my answer now. There were some extra brackets in the code which I removed and It's working now. There's nothing wrong with preventDefault here because it is used here to prevent the normal form submission so we can upload the file through AJAX asynchronously.
I tried it but its not working, i dont know why. Still checking. $_FILES / $_FILES['file']['name'] is empty for me.
@DappFuture Just recorded a video tutorial for you so you can follow along and make it work. youtu.be/xF9Xws5LqwE
Thank you for the video i didnt expect that. I m not sure yet what is the problem but i outsourced this part to another ajax call and it works the way you wrote it. But inside my existing ajax call it doesnt work, i still have to figur out. But what i didnt mention is that my ajax call is inside this which could cause the problem: "html2canvas(document.getElementById('card-build'),{backgroundColor: null, scrollX: 0, scrollY: -window.scrollY}).then(function(canvas) {"
|
0

use ajaxform plugin, you can find an example here example ajaxform

<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
        $(document).ready(function() {
         //   document.getElementsByName('userid')[0].value="{{ request.session.user_id }}";
            $(".createnews").click(function(){
                $("#formdata").ajaxForm({target: '#diagshow'});
            });
        });
</script>

5 Comments

I cant use a plugin like this. My code is abit more complex than what i posted, i just need to fix the image upload the way i tried it in my post.
i tried before to upload an image+data with ajax but it didnt until i used this js plugin
My code already includes an image upload and sql insert which works, but the first image upload is through base64 and the second which is just the image from the input isnt working because the php var is empty. $image = $_POST['image']; $location = "card/"; $image_parts = explode(";base64,", $image); $image_base64 = base64_decode($image_parts[1]); file_put_contents($fullfilename, $image_base64);
yes empty var because to send file via form you need a submit button which does works with ajax,
Hm yes the problem seems to be "event.preventDefault();" when i delete it it works. But i dont want the form to be submitted it has to be prevented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.