18

my question is that is it possible to upload an image to a server using ajax(jquery)

below is my ajax script to send text without page reload

$(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(''); } }) }) }) 

is it possible to modify it to send images?

4
  • 1
    try this: data: { poster : poster, great_id : great_id }, Commented Jan 16, 2014 at 14:25
  • Yes, you can. But I would just use a plugin like fine-uploader Commented Jan 16, 2014 at 14:26
  • 2
    Jai is this a modification to send images? Commented Jan 16, 2014 at 14:28
  • Check this article which might be helpful to you. phparticles.com/ajax/… Commented Jul 10, 2020 at 3:30

5 Answers 5

42

Use JavaScript's formData API and set contentType and processData to false

$("form[name='uploader']").on("submit", function(ev) { ev.preventDefault(); // Prevent browser default submit. var formData = new FormData(this); $.ajax({ url: "page.php", type: "POST", data: formData, success: function (msg) { alert(msg) }, cache: false, contentType: false, processData: false }); }); 
Sign up to request clarification or add additional context in comments.

6 Comments

This will send to page.php all your data of the form, even the document you uploaded, but I don't know how to modify it to set extra parameters in formData.
Just make sure the browsers you are supporting have this feature enabled. See developer.mozilla.org/en-US/docs/Web/API/… to be sure.
Does it support multiple image like <input name="x[]" multiple />
And how to handle it in server side?
var formData = new FormData($(this)[0]); is that not var formData = new FormData(this);
|
6

Here is code that will upload multiple images at once, into a specific folder!

The 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> 

The 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>"; 

And finally, the 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); }()); 

Hope this helps

Comments

2

Post both multiple text inputs plus multiple files via Ajax in one Ajax request

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"> 

Jquery Code

$(document).on('click','#btnSendData',function (event) { event.preventDefault(); var form = $('#myform')[0]; var formData = new FormData(form); // Set header if need any otherwise remove setup part $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="token"]').attr('value') } }); $.ajax({ url: "{{route('sendFormWithImage')}}",// your request url data: formData, processData: false, contentType: false, type: 'POST', success: function (data) { console.log(data); }, error: function () { } }); }); 

1 Comment

Thanks buddy your code works! posting both Text and image onto php file.
1

Jquery code which contains simple ajax :

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

Html elements you can use any element:

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

php Code:

 $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>"; 

The easy way

Comments

0
<html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(function () { $('#abc').on('submit', function (e) { e.preventDefault(); $.ajax({ url: 'post.php', method:'POST', data: new FormData(this), contentType: false, cache:false, processData:false, success: function (data) { alert(data); location.reload(); } }); }); }); </script> </head> <body> <form enctype= "multipart/form-data" id="abc"> <input name="fname" ><br> <input name="lname"><br> <input type="file" name="file" required=""><br> <input name="submit" type="submit" value="Submit"> </form> </body> </html> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.