Загрузить изображение с ajax без jquery (чистый javascript) на php-сервер
я пытаюсь загрузить изображение на свой php-сервер, используя ajax, но с чистым javascript (без Jquery). Я оставляю вам форму, функцию js и файл php.
<form enctype="multipart/form-data">
<div class="form-group">
<label for="titulo">Titulo</label>
<input type="text" class="form-control" id="titulo">
</div>
<div class="form-group">
<label for="articulo">Articulo</label>
<input class="form-control" type="text" name="articulo" id="articulo">
</div>
Subir Imagen
<input class="form-control" type="file" name="fileToUpload" id="fileToUpload">
<button class="btn btn-light my-2" id="insertar">Insertar Datos</button>
</form>
Вот мой JS-файл
document.getElementById("insertar").addEventListener("click", insertarDatos());
function insertarDatos(e) {
var titulo = document.getElementById('titulo').value,
artirulo = document.getElementById('articulo').value,
imagen = document.getElementById('fileToUpload').value,
datos = "ajax=2&titulo=" + titulo +
"&articulo=" + artirulo +
"&imagen=" + imagen;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "index.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhttp.send(datos);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var respuesta = this.response;
console.log(respuesta);
}
};
}
и вот мой php-файл, в котором я просто хочу проверить, что он принимает файл (в данном случае изображение) с var_dump ($_FILES)
elseif ($_POST['ajax'] == 2) {
$titulo = $_POST['titulo'];
$articulo = $_POST['articulo'];
$imagen = $_POST['imagen'];
var_dump($_FILES);}
надеюсь, вы можете мне помочь. Приветствия
1 answers
Есть несколько вариантов, таких как использование fileReader или FormData и, по правде говоря, я предпочитаю второй, потому что это намного проще, чем вы можете себе представить.
Для начала назначьте идентификатор форме, чтобы вы могли взять все поля и добавить их в Объект FormData, затем вы можете добавить другие переменные, в вашем случае только ajax=2
document.getElementById("insertar").addEventListener("click", insertarDatos);
function insertarDatos(e) {
// Evitar que se procese el formulario
e.preventDefault();
// Crear variable de formulario
let formSubir = document.querySelector('#formSubir');
// Poner todos los campos del formulario en FormData
let datos = new FormData(formSubir);
// Agregar ajax=2
datos.append('ajax', 2);
// Si quieres ver los datos:
console.log([...datos]);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "index.php", true);
// Este encabezado es para peticiones por GET, no lo uses
// xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
// Primero se define la función para analizar resultado
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var respuesta = this.response;
console.log(respuesta);
}
};
// Después se envían los datos
xhttp.send(datos);
}
<form enctype="multipart/form-data" id="formSubir">
<div class="form-group">
<label for="titulo">Titulo</label>
<input type="text" class="form-control" id="titulo">
</div>
<div class="form-group">
<label for="articulo">Articulo</label>
<input class="form-control" type="text" name="articulo" id="articulo">
</div>
Subir Imagen
<input class="form-control" type="file" name="fileToUpload" id="fileToUpload">
<button class="btn btn-light my-2" id="insertar">Insertar Datos</button>
</form>
С этим вы получите данные в PHP, как у вас есть сейчас.
Примечание: при добавлении функций в события не используйте круглые скобки, потому что они будут выполняться немедленно:
document.getElementById("insertar").addEventListener("click", insertarDatos());
Вместо этого просто введите имя:
document.getElementById("insertar").addEventListener("click", insertarDatos);