skip to Main Content

I have this ajax post to the server to send some data to an SQL db :

        $.ajax({
            method: "POST",
            url: "https://www.example.com/main/public/actions.php",
            data: {
                name: person.name,
                age: person.age,
                height: person.height,
                weight: person.weight
            },
            success: function (response) {
            console.log(response)
            }

        })

in the server i get this data with php like this :

<?php

include "config.php";

if(isset ( $_REQUEST["name"] ) ) {

$name = $_REQUEST["name"];
$age = $_REQUEST["age"];
$height = $_REQUEST["height"];
$weight = $_REQUEST["weight"];

$sql = "INSERT INTO persons ( name, age, height, weight )
        VALUES ( '$name', '$age', '$height', '$weight' )";

if ($conn->query($sql) === TRUE) {
    
  echo "New person stored succesfully !";
    
  exit;
  }else {
  echo "Error: " . $sql . "<br>" . $conn->error;
  exit;
  }
    
};

?>

I also have this input :

<input id="myFileInput" type="file" accept="image/*">

and in the same directory as actions.php i have the folder /images

How can i include an image ( from #myFileInput ) in this ajax post and save it to the server using the same query in php ?

I have searched solutions in SO but most of them are >10 years old,i was wondering if there is a simple and modern method to do it,i’m open to learn and use the fetch api if its the best practice.

3

Answers


  1. via ajax FormData you can send it . refer here . Note : data: new FormData(this) – This sends the entire form data (incldues file and input box data)

    URL : https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/

    $(document).ready(function(e) {
        $("#form").on('submit', (function(e) {
            e.preventDefault();
            $.ajax({
                url: "ajaxupload.php",
                type: "POST",
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData: false,
                beforeSend: function() {
                    //$("#preview").fadeOut();
                    $("#err").fadeOut();
                },
                success: function(data) {
                    if (data == 'invalid') {
                        // invalid file format.
                        $("#err").html("Invalid File !").fadeIn();
                    } else {
                        // view uploaded file.
                        $("#preview").html(data).fadeIn();
                        $("#form")[0].reset();
                    }
                },
                error: function(e) {
                    $("#err").html(e).fadeIn();
                }
            });
        }));
    });
    
    Login or Signup to reply.
  2. You should use the formData API to send your file (https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData)

    I think what you are looking for is something like that:

    var file_data = $('#myFileInput').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);                   
    $.ajax({
        url: 'https://www.example.com/main/public/actions.php',
        contentType: false, 
        processData: false, // Important to keep file as is
        data: form_data,                         
        type: 'POST',
        success: function(php_script_response){
            console.log(response);
        }
     });
    

    jQuery ajax wrapper has a parameter to avoid content processing which is important for file upload.

    On the server side, a vrey simple handler for files could look like this:

    <?php
    
        if ( 0 < $_FILES['file']['error'] ) {
            echo 'Error: ' . $_FILES['file']['error'];
        }
        else {
            move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
        }
    
    ?>
    
    Login or Signup to reply.
  3. If you are not averse to using the fetch api then you might be able to send the textual data and your file like this:

    let file=document.querySelector('#myFileInput').files[0];
    
    let fd=new FormData();
        fd.set('name',person.name);
        fd.set('age',person.age);
        fd.set('height',person.height);
        fd.set('weight',person.weight);
        fd.set('file', file, file.name );
    
    let args={// edit as appropriate for domain and whether to send cookies
        body:fd,
        mode:'same-origin',
        method:'post',
        credentials:'same-origin'
    };
    
    let url='https://www.example.com/main/public/actions.php';
    
    let oReq=new Request( url, args );
        
    fetch( oReq )
        .then( r=>r.text() )
        .then( text=>{
            console.log(text)
        });
    

    And on the PHP side you should use a prepared statement to mitigate SQL injection and should be able to access the uploaded file like so:

    <?php
    
        if( isset(
            $_POST['name'],
            $_POST['age'],
            $_POST['height'],
            $_POST['weight'],
            $_FILES['file']
        )) {
        
            include 'config.php';
            
            $name = $_POST['name'];
            $age = $_POST['age'];
            $height = $_POST['height'];
            $weight = $_POST['weight'];
            
            
            $obj=(object)$_FILES['file'];
            $name=$obj->name;
            $tmp=$obj->tmp_name;
            move_uploaded_file($tmp,'/path/to/folder/'.$name );
            #add file name to db????
            
            
    
            $sql = 'INSERT INTO `persons` ( `name`, `age`, `height`, `weight` ) VALUES ( ?,?,?,? )';
            $stmt=$conn->prepare($sql);
            $stmt->bind_param('ssss',$name,$age,$height,$weight);
            $stmt->execute();
            
            $rows=$stmt->affected_rows;
            $stmt->close();
            $conn->close();
            
            exit( $rows ? 'New person stored succesfully!' : 'Bogus...');
        };
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search