Lisboeta Posted March 11, 2015 at 01:40 PM Report Share #579150 Posted March 11, 2015 at 01:40 PM Boa tarde pessoal, tudo bem? Gostaria de tirar uma dúvida, tenho o seguinte código em PHP e AJAX num ficheiro: <form id="form_marcas"> <table width="100%"> <input type="hidden" name="id_insertmarcas" value=""> <tr> <td> <label>Pré-Visualização</label> </td> </tr> <tr> <td> <div style="float:left"><img style="width: 408px;height: 285px;" id="logoPreview" src="../../folders/img/n_a.jpg" height="285px" class="img-thumbnail"></div> </td> </tr> <tr> <td> <div class="image_uplaod" style="margin-top:5px"> <label for="file">Imagem</label> <!-- FORM UPLOAD --> <form id="form_upload" > <div class="form-group"> <input class="form-control" type="text" name="upload_marcas" id="upload_marcas"> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">Carregar</button> </div> </form> </div> </td> </tr> <tr> <td> <div class="nomemarca"> Nome da Marca: <input type="text" name="nome_marca" id="nomeInsert"> </div> </td> </tr> </table> </form> O código em $.AJAX <script> $('#bt_inserir').on('click',function(){ $.ajax({ url: "/folders/imports/functions.php", data: $('#form_marcas, #form_upload').serialize() + "&action=insert_marca", type: 'post', success: function(){ setTimeout(function(){ $('#alert_success').fadeIn(); setTimeout(function(){ $('#alert_success').fadeOut(); }, 5000); window.location.href='insert_marcas.php'; }, 1000); $('#alert_success').show(); } }); }); </script> a minha duvida é, a form que esta dentro da form acusa o method "GET", no ajax esta type: POST e um reconhece POST e outro nao. Pois quando faço submit dos formularios, insere na BD so que se for <input type="text"> o $_POST funciona e o URL fica assim. E quando o <input type="file"> faço $_FILES['(id_input)']['name'] retorna o valor NULL e não insere na BD e o URL mantém-se igual so que onde diz "&upload_marcas=caminho" tem o valor por exemplo "&upload_marcas=ficheiro.png" insert_marcas.php?id_insertmarcas=&upload_marcas=caminho&nome_marca=LOOL A query é esta <input type="text"> $query_insert = (mysqli_query($conn, "INSERT INTO tabela (nome, imagem) VALUES ('" . $_POST['nome_marca'] . "' , '" . $_POST['upload_marcas'] . "')")); <input type="file"> $query_insert = (mysqli_query($conn, "INSERT INTO tabela (nome, imagem) VALUES ('" . $_POST['nome_marca'] . "' , '" . $_FILES['upload_marcas']['name'] . "')")); e já não sei o que fazer mais. Já pesquisei no google e nos exemplos que me apresenta não corresponde aquilo que tenho. Ou senão o que tenho pode estar também mal. LOL Com os melhores cumprimentos, Lisboeta Link to comment Share on other sites More sharing options...
fpfcarvalho Posted March 11, 2015 at 11:06 PM Report Share #579185 Posted March 11, 2015 at 11:06 PM Boa noite, upload de ficheiros via ajax não é assim tão linear. Assim só estás a apanhar o nome e não a fazer upload do ficheiro. Eu uso este -> https://github.com/blueimp/jQuery-File-Upload Form dentro de um form? Não é a melhor opção nem sei se será sequer a correcta. Mas dá uma vista de olhos no blueimp fileupload, não é complicado de implementar e tens muitas opções que te podem dar jeito. Uma dica, ao fazer o upload do ficheiro, coloca-o numa directoria temporária e no retorno do sucesso do upload, guarda o caminho do ficheiro num input type="hidden" ou algo do género para depois apanhares no submit final do formulário. No teu ficheiro php, quando receberes o caminho do ficheiro na pasta temporária, só fazes o "rename()" do ficheiro se os dados forem inseridos correctamente na BD. Se não forem, não é necessário colocar o ficheiro na pasta final uma vez que só iria ocupar espaço e não iria servir para nada porque não existe registo com a imagem. Cumprimentos, Carvalho Link to comment Share on other sites More sharing options...
Lisboeta Posted March 12, 2015 at 12:16 AM Author Report Share #579187 Posted March 12, 2015 at 12:16 AM (edited) Boa noite Carvalho, Tudo bem? Antes de mais nada obrigado por ter respondido a minha questão. ;-) Está uma FORM dentro de outra FORM pois um faz o upload do ficheiro de imagem só e o primeiro faz a inserção de dados (neste caso é o nome da marca e o nome do ficheiro). Mas eu quero obter o nome do ficheiro so que retorna-me NULL, porquê me acontece isso? É por estar a form dentro de outra?? O correcto é estar separada? O upload não está a funcionar pois estava a fazer por partes 1º estava a buscar o nome do ficheiro e depois fazer o upload... mas como tive esta dúvida parei. https://blueimp.github.io/jQuery-File-Upload/index.html O link que você usa é o mesmo que este ou é este? Com os melhores cumprimentos, Lisboeta Edited March 12, 2015 at 12:20 AM by Lisboeta Link to comment Share on other sites More sharing options...
ruicosta.web Posted March 12, 2015 at 11:35 AM Report Share #579205 Posted March 12, 2015 at 11:35 AM Nunca esquecendo que o form que envia ficheiros tem de ter este atributo: enctype="multipart/form-data" Link to comment Share on other sites More sharing options...
Lisboeta Posted March 12, 2015 at 07:00 PM Author Report Share #579244 Posted March 12, 2015 at 07:00 PM (edited) Boas Carvalho, tenho uma dúvida perante o plugin que me aconselhou, como é que mudo o caminho de destino dos ficheiros carregados através do plugin? é neste sitio (UploadHandler.php), certo? function __construct($options = null, $initialize = true, $error_messages = null) { $this->response = array(); $this->options = array( 'script_url' => $this->get_full_url().'/', 'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/', 'upload_url' => $this->get_full_url().'/files/', 'user_dirs' => false, 'mkdir_mode' => 0755, 'param_name' => 'files', // Set the following option to 'POST', if your server does not support // DELETE requests. This is a parameter sent to the client: 'delete_type' => 'DELETE', 'access_control_allow_origin' => '*', 'access_control_allow_credentials' => false, 'access_control_allow_methods' => array( 'OPTIONS', 'HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE' ), 'access_control_allow_headers' => array( 'Content-Type', 'Content-Range', 'Content-Disposition' ), // Enable to provide file downloads via GET requests to the PHP script: // 1. Set to 1 to download files via readfile method through PHP // 2. Set to 2 to send a X-Sendfile header for lighttpd/Apache // 3. Set to 3 to send a X-Accel-Redirect header for nginx // If set to 2 or 3, adjust the upload_url option to the base path of // the redirect parameter, e.g. '/files/'. 'download_via_php' => false, // Read files in chunks to avoid memory limits when download_via_php // is enabled, set to 0 to disable chunked reading of files: 'readfile_chunk_size' => 10 * 1024 * 1024, // 10 MiB // Defines which files can be displayed inline when downloaded: 'inline_file_types' => '/\.(gif|jpe?g|png)$/i', // Defines which files (based on their names) are accepted for upload: 'accept_file_types' => '/.+$/i', // The php.ini settings upload_max_filesize and post_max_size // take precedence over the following max_file_size setting: 'max_file_size' => 1, 'min_file_size' => 1, // The maximum number of files for the upload directory: 'max_number_of_files' => null, // Defines which files are handled as image files: 'image_file_types' => '/\.(gif|jpe?g|png)$/i', // Use exif_imagetype on all files to correct file extensions: 'correct_image_extensions' => false, // Image resolution restrictions: 'max_width' => null, 'max_height' => null, 'min_width' => 1, 'min_height' => 1, // Set the following option to false to enable resumable uploads: 'discard_aborted_uploads' => true, // Set to 0 to use the GD library to scale and orient images, // set to 1 to use imagick (if installed, falls back to GD), // set to 2 to use the ImageMagick convert binary directly: 'image_library' => 1, // Uncomment the following to define an array of resource limits // for imagick: /* 'imagick_resource_limits' => array( imagick::RESOURCETYPE_MAP => 32, imagick::RESOURCETYPE_MEMORY => 32 ), */ // Command or path for to the ImageMagick convert binary: 'convert_bin' => 'convert', // Uncomment the following to add parameters in front of each // ImageMagick convert call (the limit constraints seem only // to have an effect if put in front): /* 'convert_params' => '-limit memory 32MiB -limit map 32MiB', */ // Command or path for to the ImageMagick identify binary: 'identify_bin' => 'identify', 'image_versions' => array( // The empty image version key defines options for the original image: '' => array( // Automatically rotate images based on EXIF meta data: 'auto_orient' => true ), // Uncomment the following to create medium sized images: /* 'medium' => array( 'max_width' => 800, 'max_height' => 600 ), */ 'thumbnail' => array( // Uncomment the following to use a defined directory for the thumbnails // instead of a subdirectory based on the version identifier. // Make sure that this directory doesn't allow execution of files if you // don't pose any restrictions on the type of uploaded files, e.g. by // copying the .htaccess file from the files directory for Apache: //'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/thumb/', //'upload_url' => $this->get_full_url().'/thumb/', // Uncomment the following to force the max // dimensions and e.g. create square thumbnails: //'crop' => true, 'max_width' => 80, 'max_height' => 80 ) ), 'print_response' => true ); if ($options) { $this->options = $options + $this->options; } if ($error_messages) { $this->error_messages = $error_messages + $this->error_messages; } if ($initialize) { $this->initialize(); } } Edited March 12, 2015 at 07:12 PM by Lisboeta Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now