Ajax does not send image to folder with PHP

0

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

What do I need to do in ajax for PHP to write 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";
    }
    
asked by anonymous 22.03.2018 / 14:27

1 answer

1

Problem in JavaScript

In PHP , both variable names, how many index names are case-sensitive a>, so you should take care of these differences between uppercase and lowercase.

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
);

Demo: link

So you should change the name in the index (from FormData ) to lowercase (as it is in your PHP ) or change in your PHP and leave it as your JavaScript , for example:

First JavaScript ):

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

Second Mode ( 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 does not work, I leave two alternatives:

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

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

2. Sometimes the upload does not work due to PHP settings, in this case it is necessary to configure the options according to the response link

Analysis and example

Analyzing the code and adding a more complete example.

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

That is, since this is the minimum and maximum value at the same time, the upload will not work due to if(empty($errors)==true){ , I believe, that you forgot to close the 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";
}
    
22.03.2018 / 15:11