Ajax does not send image to folder with PHP

Asked

Viewed 56 times

0

I am unable to send the image to a folder, using Ajax and PHP, the file name sends correctly, it is only the file even if it does not write to the folder, the folder already has permission chmod 777.

What I need to do in ajax so PHP can save the image to the folder?

$(document).ready(function () {

    $('#form_cadastro').validate({ // initialize the plugin
        rules: {
            Nome: {
                required: true,
            },
            SobreNome: {
                required: true,
            }
        },    
    messages: {
        required: "Campo obrigatório",
        remote: "Please fix this field.",
        email: "Por favor insira um email válido",
        url: "Please enter a valid URL.",
        date: "Please enter a valid date.",
        dateISO: "Please enter a valid date (ISO).",
        number: "Por favor digite apenas números.",
        digits: "Please enter only digits.",
        equalTo: "Please enter the same value again.",
        maxlength: $.validator.format( "Não insira mais do que {0} caracteres." ),
        minlength: $.validator.format( "Digite pelo menos {0} caracteres." ),
        rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ),
        range: $.validator.format( "Please enter a value between {0} and {1}." ),
        max: $.validator.format( "Please enter a value less than or equal to {0}." ),
        min: $.validator.format( "Please enter a value greater than or equal to {0}." ),
        step: $.validator.format( "Please enter a multiple of {0}." )
    },  
        submitHandler: function (form) { // for demo
 $(".resultado_form_cadastro").html('<div class="spinner"></div>');
var form = $('#form_cadastro');


var Logomarca = $('#Logomarca').prop('files')[0];


var form_data = new FormData();



    form_data.append('Logomarca', Logomarca);
    //alert(form_data);
    $.ajax({
        url: 'form_cadastro.php',

        dataType: 'text',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'POST',

        success: function(php_script_response){
            //alert(php_script_response); // display response from the PHP script, if any
// pegando os dados

        }

     })            .done(function(data){
                $('.resultado_form_cadastro').fadeOut('slow', function(){
                    $('.resultado_form_cadastro').fadeIn('slow').html(data);

                });
            })
            .fail(function(){
                alert('Ajax Submit Failed ...');
            });
            return false; // for demo
        }
    });
});

Html form

<form method="post" action="javascript:;" id="form_cadastro" enctype="multipart/form-data">

<div class="form-group row">
                    <div class="col-sm-6">
                        <label for="Logomarca">Logomarca</label>
                        <input type="file" class="form-control" id="Logomarca"  >
                    </div>
                    <div class="col-sm-6">
                        <label for="funcionamento">Horário de Funcionamento</label>
                        <input type="text" class="form-control" id="funcionamento" placeholder="Horário de Funcionamento">
                    </div>
                </div>

</form

PHP

$file_name_logomarca = $_FILES['logomarca']['name'];
        $file_size_logomarca =$_FILES['logomarca']['size'];
        $file_tmp_logomarca =$_FILES['logomarca']['tmp_name'];
        $file_type_logomarca=$_FILES['logomarca']['type'];  
        if($file_size_logomarca > 2097152){
            $errors[]='File size must be less than 2 MB';


        $desired_dir="uploads";
        if(empty($errors)==true){

            if(is_dir("$desired_dir/".$file_name_logomarca)==false){
                move_uploaded_file($file_tmp_logomarca,"$desired_dir/".$file_name_logomarca);
            }else{                                  //rename the file if another one exist
                $new_dir="$desired_dir/".$file_name_logomarca.time();
                 rename($file_tmp_logomarca,$new_dir) ;             
            }
            mysql_query($query);            
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
  • It’s not AJAX that writes it’s PHP. What code are you using in the back end (PHP)?

  • @Valdeirpsr put the PHP code also in question

  • Alter form_data.append('Logomarca', Logomarca); for form_data.append('logomarca', Logomarca);

  • so it is not recording and also does not receive the name of the image. just as I did it takes the name and does not save the image form_data.append('Logo', Logo);

1 answer

1


Problem in the Javascript

In the PHP, both variable names, how many index names are case-sensitive, so you should take care of those differences between upper and lower case.

You can do the following test to confirm:

<?php

$abc = "Valdeir";
$abC = "Valdeir";

$abcd = [
    "Nome"   => "Valdeir",
    "github" => "https://github.com/valdeirpsr"
];

var_dump(
    isset($abc), //true
    isset($ABC), //false
    isset($aBc), //false
    isset($abC), //true

    isset($abcd['nome']),   //false
    isset($abcd['GitHub']), //false
    isset($abcd['Nome']),   //true
    isset($abcd['github'])  //true
);

Demonstration: https://ideone.com/EpqaPV

Therefore, you should change the name on the index (from FormData) for tiny (as it is in your PHP) or change in your PHP and leave as your Javascript, for example:

First Way (Javascript):

var Logomarca = $('#Logomarca').prop('files')[0];
var form_data = new FormData();
form_data.append('logomarca', Logomarca);

Second Way (PHP):

$file_name_logomarca = $_FILES['Logomarca']['name'];
$file_size_logomarca =$_FILES['Logomarca']['size'];
$file_tmp_logomarca =$_FILES['Logomarca']['tmp_name'];
$file_type_logomarca=$_FILES['Logomarca']['type'];

Alternatives

If it doesn’t work, I leave two alternatives:

1. Use the code below to check for errors with the submitted file.

if ($_FILES['Logomarca']['error'] != UPLOAD_ERR_OK) {
    die( "Código do erro: " . $_FILES['Logomarca']['error'] );
}

2. Sometimes "upload" does not work due to the settings of PHP, in this case it is necessary to configure the options according to the answer /a/15641/99718


Analysis and example

Analyzing the code and adding a more complete example.

When analyzing your code, I realized that the size of "upload" needs to be - at least - 2097152 bytes (or 2MB), however, this value is also reported as the maximum.

That is, since this is the minimum and maximum value at the same time, the "upload" will not work due if(empty($errors)==true){, I believe you forgot to close that condition if($file_size_logomarca > 2097152){.

<?php

$file_name_logomarca = $_FILES['logomarca']['name'];
$file_size_logomarca = $_FILES['logomarca']['size'];
$file_tmp_logomarca  = $_FILES['logomarca']['tmp_name'];
$file_type_logomarca = $_FILES['logomarca']['type'];

if($file_size_logomarca > 2097152){
    $errors[]='File size must be less than 2 MB';
}

$desired_dir="uploads";

if(empty($errors)==true){

    if(is_dir("$desired_dir/".$file_name_logomarca) == false){
        move_uploaded_file($file_tmp_logomarca, "{$desired_dir}/{$file_name_logomarca}");
    }
    else{
        $new_dir="{$desired_dir}/{$file_name_logomarca}".time();        
        rename($file_tmp_logomarca,$new_dir) ;             
    }

}else{
    print_r($errors);
}

if(empty($error)){
    echo "Success";
}
  • I did with First Mode and it didn’t work to record the image, only the name of the image you took. Also did not return any error with the code you sent

  • php is right because when I upload without using Ajax, direct PHP works

  • Could you use my code for what you said? See if it works!

Browser other questions tagged

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