send an image using ajax

0

function objetoAjax() {
  var xmlhttp = false;

  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
  }

  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    xmlhttp = new XMLHttpRequest();
  }

  return xmlhttp;
}

var xhttp = objetoAjax();

function enviar(form) {
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("respuesta").innerHTML = this.responseText;
        } else {
            document.getElementById("respuesta").innerHTML = "no enviado";
        }
    }

    xhttp.open("POST","subir.php", true);
    xhttp.send(new FormData(form));
}
    
asked by Vanegas9090 25.07.2018 в 00:14
source

2 answers

0

You could summarize your code with jquery, this would send your form by post, to the url indicated

$("#MyForm").submit(function(e) {
    var url = "subir.php";
    $.ajax({
           type: "POST",
           url: url,
           data: $("#MyForm").serialize(),
           success: function(data)
           {
                    document.getElementById("respuesta").innerHTML = data;
           },
           error: function (xhr, ajaxOptions, thrownError) {
                   document.getElementById("respuesta").innerHTML = "no enviado";
           }
         });
    e.preventDefault();
});
    
answered by 25.07.2018 в 00:51
0

This is the HTML code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>index</title>
        <script type="text/javascript" src="ajax.js"></script>
    </head>
    <body>
        <div id="respuesta">
            hola mundo
        </div>

        <form id="form" action="javascript: enviar(this)">
            <input type="file" name="archivo" id="archivo">
            <input type="submit" value="enviar">
        </form>
    </body>
</html>

this is the PHP code

<?php
    $nombre_temporal = $_FILES['archivo']['tmp_name'];
    $nombre = $_FILES['archivo']['name'];

    echo $nombre;
    $destino = "archivos/" . $nombre;
    move_uploaded_file($nombre_temporal, $destino);
?>
    
answered by 25.07.2018 в 06:28