Erro - php, javascript - upload foto ajax sem jquery
/////////////////////////////////////////////////////////////////////// index.php //////////////////////////////////////////////////////////////////////////////////////////
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload</title>
<style>
input[type=file]{
float:left;
}
</style>
</head>
<body>
<div class="container">
<h1>Uploader</h1>
<form id="file-form" action="" method="POST">
<input type="file" id="file"/>
<button class="btn btn-sm btn-primary upload-all" onclick="envia();">Upload All</button>
</form>
</div><!-- end .container -->
<script src="ajax.js" type="text/javascript"></script>
<script>
// envia um formulário via ajx
function envia() {
var img = document.getElementById('file').file[0];
var dados = 'file_img=' + img;
// função ajax
funcition_universal(dados, 'server.php', myfuntion);
}
// retorno da função alerta a mensagem de retorno
function myfuntion(arr) {
var a = JSON.parse(arr);
alert(a);
}
</script>
</body>
</html>
////////////////////////////////////////////////////////////////////////// server.php ///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
$tmp_file = $_FILES['file_img']['tmp_name'];
$filename = $_FILES['file_img']['name'];
move_uploaded_file($tmp_file, 'upload_folder/' . $filename);
print json_encode('Uploada realizado com sucesso');
//////////////////////////////////////////////////////////////////////// ajax.js ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
*
* @param {type} dados - os dados que serão enviados ao servidos
* @param {type} url - o caminho que ele deverá precorrer
* @param {type} myFunctions - a função que receberá o retorno do servidos
* @returns {undefined}
*/
function funcition_universal(dados, url, myFunctions) {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
/* verifica se ouve resposta do servidor
* 0 - não iniciada
* 1 - iniciando conexão
* 2 - conexão estabelecida
* 3 - conexão em atividade (algum dado foi recebido)
* 4 - completa
*/
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
switch (xmlhttp.responseText) {
default :
myFunctions(xmlhttp.responseText);
break;
}
}
};
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-type", data.type);
// xmlhttp.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xmlhttp.send(dados);
}Discussão (0)
Carregando comentários...