Ir ao conteúdo
  • Cadastre-se

Javascript Pagina recarregando sozinha com Ajax


Posts recomendados

 

 

Copiei da internet um sistema para subir a foto para o servidor e depois pegar a mesma foto e recortar ela onde o usuario quiser, mas depois de enviar a foto para o servidor a pagina recarrega. fiz algumas mudanças porque estou mexendo com mvc seguem o codigo: 


            <label for="arquivo" style="cursor: pointer;">
                <img id="cropbox" src="<?php echo VENDOR_PATH . $_SESSION['nm_caminho_foto']; ?>" class="figure-img img-fluid rounded">
            </label>
            <input class="d-none" type="file" accept=".png,.jpeg" id="arquivo">
            <input type="hidden" id="x" name="x" />
            <input type="hidden" id="y" name="y" />
            <input type="hidden" id="w" name="w" />
            <input type="hidden" id="h" name="h" />
        </figure>
        <input type="submit" onclick="submitForm();" id="sendButton" value="Enviar">


function getCoords() {
    var api;
    $('#toCrop').Jcrop({
        minSize: [160, 160],
        aspectRatio: 1,
        bgOpacity: 0.4,
        addClass: 'jcrop-light',
        onSelect: updateCoords,
        onChange: updateCoords,
        setSelect: [0, 0, 160, 160]
    });
}

function updateCoords(c) {
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);
};

function _(element) {
    if (document.getElementById(element))
        return document.getElementById(element);
    else
        return false;
}

function submitForm() {

    if (_('arquivo').files[0]) { //Se houver um arquivo, faremos alguns testes no mesmo
        var arquivo = _('arquivo').files[0];
        if (arquivo.type != 'image/png' && arquivo.type != 'image/jpeg')
            _('result').innerHTML = 'Por favor, selecione uma imagem do tipo JPEG ou PNG';
        else if (arquivo.size > 1024 * 2048) //2MB
            _('result').innerHTML = 'Por favor selecione uma image mo máximo 2MB de tamanho.';
        else {
            var x = _('x').value;
            var y = _('y').value;
            var w = _('w').value;
            var h = _('h').value;
            var formData = new FormData();
            formData.append('arquivo', arquivo);
            formData.append('x', x);
            formData.append('y', y);
            formData.append('w', w);
            formData.append('h', h);
            if (_('imgType')) {
                var imgType = _('imgType').value;
                formData.append('imgType', imgType);
            }
            if (_('imgName')) {
                var imgName = _('imgName').value;
                formData.append('imgName', imgName);
            }


            var request = new XMLHttpRequest();
            if (_('toCrop'))
                var includeFile = 'painel/crop';
            else {
                var includeFile = 'painel/recebe';
            }
            request.open('post', includeFile, true);

            request.onreadystatechange = function() {
                if (request.status == 200) {
                    _('result').innerHTML = request.responseText;
                    $('.modal').modal('show');
                }
                if (_('toCrop')) {
                    _('sendButton').value = 'Recortar';

                }
            }
            $('.modal').modal('show');
            request.send(formData);
            _('result').innerHTML = '<img src="./recursos/gif/loading.gif" />';
        }
    } else
        _('result').innerHTML = 'Por favor, selecione uma imagem para ser enviada!';
}
\Router::rota("painel/crop", function () {
            if (!empty($_POST) && $_SESSION['isLogado']) {
                $fileType = $_POST['imgType'];
                $imgName  = $_POST['imgName'];
                define('OUTPUT', 'recursos/img/fotos_usuarios/' . $imgName);
                if ($fileType == 'image/png') {
                    $img = imagecreatefrompng('recursos/img/fotos_usuarios/tmp/' . $imgName);
                } else {
                    $img = imagecreatefromjpeg('recursos/img/fotos_usuarios/tmp/' . $imgName);
                }

                $imgWidth  = imagesx($img);
                $imgHeight = imagesy($img);

                $newImage = imagecreatetruecolor(160, 160);
                imagecopyresampled($newImage, $img, 0, 0, $_POST['x'], $_POST['y'], 160, 160, $_POST['w'], $_POST['h']);
                if ($fileType == 'image/png')
                    $finalImage = imagepng($newImage, OUTPUT);
                else
                    $finalImage = imagejpeg($newImage, OUTPUT);
                if ($finalImage)
                    echo 'Foto atualizada com sucesso<img id="thumbnail" src="' . OUTPUT . '" />';
                else
                    echo 'Ocorreu um erro ao tentar criar a nova imagem';
            }
        });
        \Router::rota("painel/recebe", function () {

            if (!empty($_POST) && $_SESSION['isLogado']) {
                $fileName  = $_FILES['arquivo']['name'];
                $fileTMP   = $_FILES['arquivo']['tmp_name'];
                $fileType  = $_FILES['arquivo']['type'];
                $fileError = $_FILES['arquivo']['error'];
                $fileEXT   = explode('.', $fileName);
                $newName   = $_SESSION['id_usuario'] . '.' . end($fileEXT);
                $permitido = array('image/png', 'image/jpeg');

                define('OUTPUT', 'recursos/img/fotos_usuarios/tmp/' . $newName);
                if (in_array($fileType, $permitido) == false)
                    echo 'Por favor selecione um arquivo do tipo JPEG ou PNG.';
                elseif ($fileError == 4)
                    echo 'Desculpe, mas o arquivo não foi enviado, por favor, tente novamente,';
                elseif ($fileError == 3)
                    echo 'Desculpe, o envio do arquivo não foi completado com sucesso, por favor, tente novamente.';
                elseif ($fileError == 2)
                    echo 'Esta imagem é muito grande, por favor, selecione uma imagem de até 2MB de tamanho!';
                elseif ($fileError == 1)
                    echo 'Esta imagem é muito grande, por favor, selecione uma imagem de até 2MB de tamanho!';
                else {

                    if ($fileType == 'image/png')
                        $img = imagecreatefrompng($fileTMP);

                    else

                        $img = imagecreatefromjpeg($fileTMP);
                    $imgWidth  = imagesx($img);
                    $imgHeight = imagesy($img);
                    if ($imgWidth > 500) {
                        $x = 500;
                        $y = ceil(($imgHeight / $imgWidth) * $x);
                    } else {
                        $x = $imgWidth;
                        $y = $imgHeight;
                    }
                    if ($y > 500) {
                        $y2 = 500;
                        $x  = ceil(($x / $y) * $y2);
                        $y  = $y2;
                    }

                    $newImage = imagecreatetruecolor($x, $y);
                    imagecopyresampled($newImage, $img, 0, 0, 0, 0, $x, $y, $imgWidth, $imgHeight);


                    if ($fileType == 'image/png') {
                        header('Content-Type: image/png');
                        $finalImage = imagepng($newImage, OUTPUT);
                    } else {
                        $finalImage = imagejpeg($newImage, OUTPUT);
                    }

                    if ($finalImage)
                        echo '<img onload="getCoords();" id="toCrop" src="' . OUTPUT . '" /><input type="hidden" id="imgType" value="' . $fileType . '"/><input type="hidden" id="imgName" value="' . $newName . '"/>';
                    else
                        echo 'Ocorreu um erro ao tentar criar a nova imagem';
                }
            }
        });

Muito provavelmente o problema é so na função submitForm();

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...