Upload does not reach PHP via AJAX with . serialize()

Asked

Viewed 1,414 times

0

I’m implementing a posting system on my future website where it requires uploading images. But when making the request with AJAX the PHP script returns an error stating that the name "img-post" of the variable $_FILES is missing. So I checked with a var_dump and found that the variable is empty.

On the client side I’m using the function .serialize() to pick up and send the information.

PHP:

<?php

class publication {

    public $msgStatus; //Array de status da class
    //private var
    private $file; //Arquivo upado
    private $flNm; //Novo nome do arquivo
    private $post; //Conteudo da postagem
    private $tpEx; //Extensões válidas para o arquivo
    private $title; //Titulo da postagem
    private $type; //Tipo de postagem
    private $content; //Conteudo da postagem
    private $tags; //Tags para a postagem
    private $cover; //
    private $db; //Variável de conecxão com o banco de dados
    private $datetime; //Hora
    private $filePath;

    function __construct() {
        $this->tpEx = ['.jpg', '.png', '.gif'];
        $this->msgStatus = ['status' => 'ok', 'msg' => 'Notice: Inicializado mas não executado!'];
        include_once $_SERVER['DOCUMENT_ROOT'] . '/sys/db/base0.php';
        $this->db = connectdb();
        $this->datetime = date("Y-m-d H:i:s");
    }

    private function callBackFail($type, $msg) {
        //header('Content-Type: application/json');
        $this->msgStatus['status'] = $type;
        $this->msgStatus['msg'] = $msg;
        echo json_encode($this->msgStatus);
        die(404);
    }

    private function upStatus($msg) {
        $this->msgStatus['msg'] = $msg;
    }

    private function validEx() {
        if (isset($this->file)) {
            $exVal = count($this->tpEx);
            $foundEx = false;
            for ($i = 0; $i < $exVal; $i++) {
                if (strpos(strtolower($this->file['img-post']['name']), $this->tpEx[$i]) !== false) {
                    $foundEx = true;
                }
            }
            if ($foundEx) {
                $ex = strtolower(substr($this->file['img-post']['name'], -4));
                $newName = hash('md5', time() . $ex) . $ex;
                $this->flNm = $newName;
                $this->upStatus('Arquivo de imagem validado com sucesso!');
                return true;
            } else {
                $this->callBackFail('falha', 'Imagem com extensão desconhecida! A imagem deve ser do tipo (' . inplode(', ', $this->tpEx) . ')');
            }
        } else {
            $this->callBackFail('falha', 'Imagem da capa não encontrado.');
        }
    }

    private function configVars() {
        $vars = $this->post;
        (isset($vars['tl'])) ? $this->title = htmlentities(trim($vars['tl'])) : $this->callBackFail('falha', 'Titulo da postagem não encontrado.');
        (isset($vars['tp'])) ? $this->type = htmlentities(trim($vars['tp'])) : $this->callBackFail('falha', 'É necessário o tipo de postagem.');
        (isset($vars['ctt-post'])) ? $this->content = $vars['ctt-post'] : $this->callBackFail('falha', 'É necessãeio tem um conteudo para esse titulo.');
        (isset($vars['tg'])) ? $this->tags = htmlentities(trim($vars['tg'])) : $this->callBackFail('falha', 'Adicione tags para ajudar na busca por esse conteudo!');
        $this->upStatus('As variáveis foram configuradas com sucesso!');
    }

    private function uploadFile() {
        try {
            $path = $_SERVER['DOCUMENT_ROOT'] . '/upload/publi-cover/';
            move_uploaded_file($this->file['img-post']['tmp_name'], $path . $this->flNm);
            $this->filePath = '/images/upload/publi-cover/' . $this->flNm;
            return true;
        } catch (Exception $ex) {
            $msg = $ex->getMessage();
            $code = $ex->getCode();
            $this->callBackFaill('error', 'Msg: ' . $msg . ' Code: ' . $code);
        }
    }

    public function setAtributes($post, $file) {
        $this->file = $file;
        $this->post = $post;
        $this->configVars();
        $this->upStatus('As variáveis foram aplicadas!');
    }

    public function insert() {
        if ($this->uploadFile()) {
            $db = $this->db;
            $insert = $db->prepare("INSERT INTO `posts`(`type`, `title`, `post`, `date`, `views`, `coverofpost`, `tags`) VALUES ( :tp , :tl , :pt , :dt , :vw , :cop , :tg )");
            $insert->bindValue(":tp", $this->type, PDO::PARAM_STR);
            $insert->bindValue(":tl", $this->title, PDO::PARAM_STR);
            $insert->bindValue(":pt", $this->content, PDO::PARAM_STR);
            $insert->bindValue(":dt", $this->datetime, PDO::PARAM_STR);
            $insert->bindValue(":vw", 0, PDO::PARAM_int);
            $insert->bindValue(":cop", $this->filePath, PDO::PARAM_STR);
            $insert->bindValue(":tg", $this->tags, PDO::PARAM_STR);
            if ($insert->lastInsertId()) {
                $this->msgStatus['status'] = ok;
                $this->msgStatus['msg'] = 'Postagem realizada com susesso!';
            }
        } else {
            $this->callBackFail('falha', 'Não foi possível salvar a capa da publicação!');
        }
    }

    public function update($param) {

    }

}

$post = new publication();
$post->setAtributes($_POST, $_FILES);
var_dump($_FILES);
$status = $post->insert();

Jquery/Ajax:

$("#form-add-post").submit(function (event) {
    event.preventDefault();
    $('#editor').html(CKEDITOR.instances.editor.getData());
    var data = $("#form-add-post").serialize(); //Cria uma array com nome e valor

$.ajax({
    type: "POST", // Método de envio
    url: "/sys/cp/app/add-post.php", // Aqui você trata os dados enviados e da um callback com Json
    data: data, // Variavel acima
    success: function (asr) {
        alert(asr);
    }
});

});

HTML form:

<div class="content-add-post">
                            <form id="form-add-post" method="POST" enctype="multipart/form-data">
                                <div class="header-form-add">
                                    <div class="cont-head-right">
                                        <label for="tl-post">Titulo:</label><br/>
                                        <input id="tl-post" name="tl" onblur="$(this) != ''? $(this).css(''):null;" class="input-adm" type="text" placeholder="Como instalar alguma coisa."/>
                                    </div>
                                    <div class="cont-head-left">
                                        <label for="tp-post">Tipo de postagem:</label><br/>
                                        <input id="tp-post" name="tp" onblur="$(this) != ''? $(this).css(''):null;" class="input-adm" type="text" placeholder="Notícia"/>
                                    </div>
                                </div>
                                <br/>
                                <br/>
                                <textarea id="editor" name="ctt-post"></textarea>
                                <script src="/scripts/addons/ckeditor/ckeditor.js" type="text/javascript"></script>
                                <script type="text/javascript">CKEDITOR.replace('editor');</script>
                                <br/>

                                <label for="tags-post">Tags:</label><br/>
                                <input id="tags-post" name="tg" onblur="$(this) != ''? $(this).css(''):null;" type="text" class="input-adm"  placeholder="Ajax,JSON,JavaScript,PHP,html,JQuery"/>
                                <br/>
                                <labe for="img-post">Capa da postagem</labe><br/>
                                <input id="img-post" type="file" required="" name="img-post"  accept="image/*"/>
                                <div class="limt-img">
                                    <img id="load-Imgpost" name="file" src="" alt="Load img"/>
                                    <script type="text/javascript">
                                        function readURL(input) {
                                            if (input.files && input.files[0]) {
                                                var reader = new FileReader();
                                                reader.onload = function (e) {
                                                    $('#load-Imgpost').attr('src', e.target.result);
                                                }
                                                reader.readAsDataURL(input.files[0]);
                                            }
                                        }
                                        $("#img-post").change(function () {
                                            readURL(this);
                                        });
                                    </script>
                                </div>
                                <button id="btnsalvepost" type="submit">Salvar</button>
                            </form>
                        </div>

1 answer

1


The method serialize() does not work for the functionality you want.

According to the documentation:

The . serialize() method creates a text string in standard URL-encoded Notation. It can Act on a jQuery Object that has Selected individual form Controls, such as , , and : $( "input, textarea, select" ).serialize();

In other words, the return of this method is a string encoded as a URL with parameters. So it only works with things that can be sent by a string, such as a contact form, numbers and simple form texts.

(You may think that a photo may perhaps be sent via base64 string, but I don’t believe the method serialize() do this)

To send an image, you can use the Formdata.

It would look something like this:

var img;
$("#img").change(function(e){
    img = $(this)[0].files[0]; //pega imagem
});

var fd = new FormData();
fd.append("img-post", img);

$.ajax({
    url: "ahuahuahuaua/upload",
    data: fd,
    method: "POST"
});

Another solution would be to use Base64 that you are already recovering from the image to display a preview (I believe), and put in the value() of a input hidden. Dai yes giving the serialize() should work.

  • 1

    Before answering I recommend to search if there is a question with answers that fit here http://answall.com/questions/9704/fazer-upload-de-arquivo-com-ajax, the best in these cases is to mark as duplicate ;D

Browser other questions tagged

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