Upload ajax jquery php

Asked

Viewed 2,783 times

2

I need the image upload to be done with ajax/jquery, following this structure:

Form:

<form>
<input type="text" name="seu_nome" />
<input type="text" name="sua_senha" />
<input type="file" name="file" />

<button type="submit">Enviar</button>
</form>

Ajax/Jquery:

$("#form_"+screen_label).submit(function(){

    var dados = $( this ).serialize();  

    $.ajax({
    type: "POST",                           
    url: "upload.php",              
    data: dados,
    success: function( data ){      
    //ok
}//end success
    });//end method     
    /* .............................................. */

    return false;

});//end submit


o php:

if (isset($_FILES['file']) && !empty($_FILES['file']['name'])) {

    $file_name = $_FILES['file']['name'];
    $file_type = $_FILES['file']['type'];
    $file_size = $_FILES['file']['size'];
    $file_tmp_name = $_FILES['file']['tmp_name'];
    $error = $_FILES['file']['error'];      

    //echo $file_name;
    //echo $titulo;

            /*
            switch($file_type){
                case 'image/png':  $arq ='.png';break;
                case 'image/jpeg': $arq ='.jpg';break;
                case 'image/gif':  $arq ='.gif';break;
                case 'image/bmp':  $arq ='.bmp';break;
                case 'image/PNG':  $arq ='.PNG';break;
                case 'image/JPEG': $arq ='.JPEG';break;
                case 'image/GIF':  $arq ='.GIF';break;
                case 'image/BMP':  $arq ='.BMP';break;

            }
            */

            $destino = 'imgs/';

       move_uploaded_file($file_tmp_name,$destino.$file_name);


    }//end if isset file

Does anyone know what is missing for the upload to happen and the image to be saved in the folder?

  • I believe that Here is the solution to your problem.

1 answer

2


The best solution is to work with Formdata and build what is to be sent to your script PHP in case I switched to a better identification the name for id, I added one to one and then send it to the server, example:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel - Resultados</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
        </script>
    </head>
    <body>
    <form method="post" enctype="multipart/form-data">
        <input type="text" id="seu_nome" />
        <input type="text" id="sua_senha" />
        <input type="file" id="file" />
        <button type="button" id="btEnviar">Enviar</button>
    </form>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#btEnviar').click(function()
            {

                var form_data = new FormData();           

                form_data.append('file', $('#file').prop('files')[0]);                  
                form_data.append('seu_nome', $("#seu_nome").val());
                form_data.append('sua_senha', $("#sua_senha").val());

                $.ajax({
                    url: 'up.php',
                    dataType: 'text', 
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: form_data,  
                    type: 'post',
                    success: function(data){
                        alert(data); 
                    }
                });
            });
        });
    </script>
 </body>
</html>

and in the script

<?php

    if ( isset($_FILES['file']) && !empty($_FILES['file']['name']) )
    {
        $file_name = $_FILES['file']['name'];
        $file_type = $_FILES['file']['type'];
        $file_size = $_FILES['file']['size'];
        $file_tmp_name = $_FILES['file']['tmp_name'];       

        $destino = 'imgs/';

        echo move_uploaded_file($file_tmp_name,$destino.$file_name);    
    }

with these two files you can already send the images and information of the two text boxes to the server and use it the way you want.

This example can also be done by passing the elements at once to Formdata, example:

var form_data = new FormData(document.getElementById("form1"));

and tag <form> the id form1.

  • Hi, This new form_data() is a native object or I will have to add some class or plugin to instantiate it ?

  • And will I have to read the value of each input . val()? I can’t capture the data by Submit name?

  • Hi, the explanation about FormData() is in the link @Neo

  • It has the way to pass the elements that is indicated which form you need to redeem the information var form_data = new FormData(document.getElementById("form1")); I made an edit on the reply...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.