web-dev-qa-db-fra.com

Comment envoyer une image à PHP fichier en utilisant Ajax?

ma question est: est-il possible de télécharger une image sur un serveur en utilisant ajax

ci-dessous est mon script ajax pour envoyer du texte sans rechargement de page

$(function() {
//this submits a form
$('#post_submit').click(function(event) {
event.preventDefault();
var great_id = $("#post_container_supreme:first").attr("class");
var poster = $("#poster").val() ;
    $.ajax({
        type: "POST",
        url: "my php file",
        data: 'poster='+ poster + '&great_id=' + great_id,
        beforeSend: function() {
            $("#loader_ic").show();
            $('#loader_ic').fadeIn(400).html('<img src="data_cardz_loader.gif" />').fadeIn("slow");
        },
        success: function(data) {
            $("#loader_ic").hide();
            $("#new_post").prepend(data);
            $("#poster").val('');
        }

    })
})
})

est-il possible de le modifier pour envoyer des images?

14
Immortal Dude

Cela marche.

$("form[name='uploader']").submit(function(e) {
  var formData = new FormData($(this)[0]);

  $.ajax({
    url: "page.php",
    type: "POST",
    data: formData,
    success: function (msg) {
      alert(msg)
    },
    cache: false,
    contentType: false,
    processData: false
  });

  e.preventDefault();
});

Est-ce ce que vous cherchiez?

31
AleVale94

Voici le code qui téléchargera plusieurs images à la fois, dans un dossier spécifique!

Le HTML:

<form method="post" enctype="multipart/form-data" id="image_upload_form" action="submit_image.php">
<input type="file" name="images" id="images" multiple accept="image/x-png, image/gif, image/jpeg, image/jpg" />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">

</ul>

Le PHP:

<?php
$errors = $_FILES["images"]["error"];
foreach ($errors as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
    $name = $_FILES["images"]["name"][$key];
    //$ext = pathinfo($name, PATHINFO_EXTENSION);
    $name = explode("_", $name);
    $imagename='';
    foreach($name as $letter){
        $imagename .= $letter;
    }

    move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "images/uploads/" .  $imagename);

}
}


echo "<h2>Successfully Uploaded Images</h2>";

Et enfin, le JavaSCript/Ajax:

(function () {
var input = document.getElementById("images"), 
    formdata = false;

function showUploadedItem (source) {
    var list = document.getElementById("image-list"),
        li   = document.createElement("li"),
        img  = document.createElement("img");
    img.src = source;
    li.appendChild(img);
    list.appendChild(li);
}   

if (window.FormData) {
    formdata = new FormData();
    document.getElementById("btn").style.display = "none";
}

input.addEventListener("change", function (evt) {
    document.getElementById("response").innerHTML = "Uploading . . ."
    var i = 0, len = this.files.length, img, reader, file;

    for ( ; i < len; i++ ) {
        file = this.files[i];

        if (!!file.type.match(/image.*/)) {
            if ( window.FileReader ) {
                reader = new FileReader();
                reader.onloadend = function (e) { 
                    showUploadedItem(e.target.result, file.fileName);
                };
                reader.readAsDataURL(file);
            }
            if (formdata) {
                formdata.append("images[]", file);
            }
        }   
    }

    if (formdata) {
        $.ajax({
            url: "submit_image.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (res) {
                document.getElementById("response").innerHTML = res;
            }
        });
    }
}, false);
}());

J'espère que cela t'aides

5
VaMoose

Jquery code qui contient simple ajax: 

   $("#product").on("input", function(event) {
      var data=$("#nameform").serialize();
    $.post("./__partails/search-productbyCat.php",data,function(e){
       $(".result").empty().append(e);

     });


    });

Les éléments HTML, vous pouvez utiliser n'importe quel élément: 

     <form id="nameform">
     <input type="text" name="product" id="product">
     </form>

code php:

  $pdo=new PDO("mysql:Host=localhost;dbname=onlineshooping","root","");
  $Catagoryf=$_POST['product'];

 $pricef=$_POST['price'];
  $colorf=$_POST['color'];

  $stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
  $stmtcat->execute(array($Catagoryf));

  while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
  $iddb=$result['ID'];
     $namedb=$result['Name'];
    $pricedb=$result['Price'];
     $colordb=$result['Color'];

   echo "<tr>";
   echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>'; 
   echo "<td><pre>$pricedb</pre></td>";
   echo "<td><pre>    $colordb</pre>";
   echo "</tr>";

Le moyen facile 

1

HTML

<form class="form-horizontal" id="myform" enctype="multipart/form-data">
<input type="text" name="name" class="form-control">
<input type="text" name="email" class="form-control">
<input type="file" name="image" class="form-control">
<input type="file" name="anotherFile" class="form-control">

Code Jquery

$(document).on('click','#btnSendData',function (event) {
    event.preventDefault();
    var form = $('#myform')[0];
    var formData = new FormData(form);

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
        }
    });
    $.ajax({
        url: "{{route('sendFormWithImage')}}",
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (data) {
            console.log(data);
        },
        error: function () {

        }
    });

});
0
Kabeer Hussain