#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2016
    Posts
    109
    Rep Power
    3

    Fetch API issue PHP not catching data


    I am having problem sending file over to the php page. I am not quite sure if I am doing it right.
    I want to catch the value sent over to the the php page but php saying $_FILES['photo']['tmp_name'] is
    undefine index?

    First of all, am i feeding the form data to the fetch correctly? If someone can shine light on this, would be much appreciated.

    index.html page
    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" />
        <title>Fetch API with Php</title>
         
    </head>
    <body>
        <div class="container">
            <h1>Fetch Api + Php</h1>
            <form enctype="multipart/form-data">
                    <input type="file" name="photo" id="photo">
                    <input type="submit" value="Submit" id="submit">
            </form>
            <br><br>
            <div id="output"></div>
        </div>
    
        <script src="app.js"></script>
    </body>
    </html>
    javascript:

    Code:
    // Javascript fetch method
    let submit = document.querySelector('#submit');
        submit.addEventListener('click', getResult);
    
        function getResult(e) {
            e.preventDefault();
            
            var fileField = document.querySelector("input[type='file']");
            formData = fileField.files[0];
    
            console.log(formData);
    
        fetch('fetch.php', {
    
            method: 'POST',
            body:  formData, 
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        })
        .then(function(response){
    
            console.log(response.status);
            if (response.ok){
    
                return response.text();
    
            } else {
    
                if (response.status === 404){
    
                    return Promise.reject('Not found.');
    
                } else if (response.status === 403){
    
                    return Promise.reject('Forbidden');
    
                } else {
                    return Promise.reject('Something is Wrong')
                    } 
            }
    
        })
        .then(function(text){
            document.querySelector('#output').innerHTML = text;
        })
        .catch(function(err){
            document.querySelector('#output').innerHTML = err;
        });
    
    }
    php page:
    PHP Code:
    <?php

    if(isset($_FILES)){

       
    $image_size getimagesize($_FILES["photo"]["tmp_name"]);
       echo 
    $image_size;

    } else {

        echo 
    'Does not work';
    }
  2. #2
  3. Impoverished Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,884
    Rep Power
    9646
    File uploads do not work like regular AJAX requests.

    The Almighty Google
    Last edited by requinix; February 20th, 2018 at 04:47 PM. Reason: not quite the right link
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2016
    Posts
    109
    Rep Power
    3
    Originally Posted by requinix
    File uploads do not work like regular AJAX requests.

    The Almighty Google
    Thank you for your reply Mr requinix. I must say, I been googling endlessly, Google is not being quite helpful on this occasion. If you telling me to google, then I am doomed! I come here only if I am absolutely stuck.
    But Most google result gives example of 'new FormData().
    Code:
            let photo = document.querySelector("#photo");
            name = photo.files[0];
            const formData = new FormData();
            formData.append('data', name);
    But this is what I am stuck. I do not know how this data is passed and the php '$_POST' index is throwing an error as undefined.?
    How to get the values passed to PHP and assigned to variables?
  6. #4
  7. Impoverished Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,884
    Rep Power
    9646
    Ah, I didn't notice you're not using jQuery. I saw a bunch of parentheses and functions and assumed you were...

    I don't know what fetch() is?

    Your new code looks correct: get .files[n] and pass to FormData.append(). You then pass FormData as the "body" in fetch(). However you must remove that header because application/x-www-form-urlencoded is for plain form data and will not work for file uploads. In fact you shouldn't need to set any headers at all.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2016
    Posts
    109
    Rep Power
    3
    Originally Posted by requinix
    Ah, I didn't notice you're not using jQuery. I saw a bunch of parentheses and functions and assumed you were...

    I don't know what fetch() is?

    Your new code looks correct: get .files[n] and pass to FormData.append(). You then pass FormData as the "body" in fetch().
    Well fetch api is suppose to be the new javascript ajax call. I've looked at few youtube videos and all I know this is going to be the future implementation hence I was trying to learn bit about it.
    However, Your suggestions have helped. I think the problem was with the html header. After I've removed the header I was able to get stuff in php. But what is the general header that will work for all data type?

IMN logo majestic logo threadwatch logo seochat tools logo