Ajax Upload Image

Ajax Upload image

first in your ajax call include success & error function and then check if it gives you error or what?

your code should be like this

$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);

$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));

$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});

Upload image to folder using ajax/jquery

Here is you solution

HTML

<form id="registerForm" method="post" enctype="multipart/form-data">
<input name="archivo" id="archivo" style="width: 70%;" class="btn btn-block" type="file" onchange="PreviewImage(this)" />
<img id="uploadPreview" />
<button type="submit">Submit</button>

Java Script

function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("image").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
};

//ajax

$("#registerForm").submit(function(event) {
var formData = new FormData($(this)[0]);
if ($(this).valid()) {
$.ajax({
url : '../../class/upload.php',
type : 'POST',
data : formData,
contentType : false,
cache : false,
processData : false,
success: function(e) {alert(e) },
error : function(x, t, m) {},
});
}
});

PHP

<?php
echo "<pre>"; print_r($_FILES);echo "</pre>"; die; //this will show you the file transfered by form.
$categoria = $_POST['categoria'];
$nombre = $_POST['nombre'];
$descripcion = $_POST['descripcion'];
$img = $_POST['archivo'];
$activo = $_FILES['activo'];
$disponible = $_POST['disponible'];
$precio = $_POST['precio'];
$IdCategoria = 0;
$filepath = "";

//Imagen

if($categoria=="Piano") {
$IdCategoria = 1;
$filepath = "../Files/Productos/Piano/".$img;
}

$filetmp = $_FILES['archivo']['tmp_name'];
move_uploaded_file($filetmp, $filepath);

echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;


?>

How can I upload image using AJAX in rails5.1.6

//f.file_field in html.erb will be compiled to <input type='file'>//you can construct FormData manually, param by param:var fileInput = document.querySelector('form input[type=file]');var attachment = fileInput.files[0];var formData = new FormData(); formData.append('email', 'Your Email');formData.append('attachment', attachment, 'filename.jpg');
//In jQuery you would send it like this:
$.ajax({ url: "/profile/upload_image", type: "POST", beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, data: "data=" + formData, success: function(data) { ... } });

Upload image using ajax mysql php

Try this:

Jquery:

$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData(); // Create a FormData object
form_data.append('file', file_data); // Append all element in FormData object

$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the input type file */
});

Php:

<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}

?>

Can you upload images using Ajax?

I have figured it out, here is it:

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$('#image_form').submit(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData:false,
success: function(status) {
$('#result').append(status);
}
});
});
});
</script>

//upload.php

<?php

include 'connect.php';

if(is_array($_FILES))
{
foreach ($_FILES['files']['name'] as $name => $value)
{
$file_name = explode(".", $_FILES['files']['name'][$name]);
$allowed_ext = array("jpg", "jpeg", "png", "gif");
if(in_array($file_name[1], $allowed_ext))
{
$new_name = substr(sha1(mt_rand()),0,50) . '.' . $file_name[1];
$sourcePath = $_FILES['files']['tmp_name'][$name];
$target = "photos/".$new_name;
if(move_uploaded_file($sourcePath, $target))
{
mysqli_query($con, "INSERT INTO images VALUES('".$target."')");
echo "<img src='$target' />";
}
}
}
}

?>

ASP NET upload image with jQuery and AJAX

You can manually set the FormData keys and values yourself.

<input type="file" name="imguploader" id="imguploader" />
<button id="btnUpload">Upload</button>

Create FormData and set a new key/value

$("#btnUpload").on("click", function(e) {
e.preventDefault();

var file = $("#imguploader").get(0).files[0];
var formData = new FormData();
formData.set("file", file, file.name);

$.ajax({
url: '@Url.Action("InsertImage", "Product")',
method: "post",
data: formData,
cache: false,
contentType: false,
processData: false
})
.then(function(result) {

});
});

The controller

[HttpPost]
public ActionResult InsertImage(HttpPostedFileBase file)
{

}

upload image file through ajax and php

ok I solved my issue/error about my own question. I understood a lot actually about how openCart upload images, how ajax and xhr works and so on. Anyway, the code I have used is this:

Inside file profile.tpl:

$('#upload-image').on('click',function(e){
var formData = new FormData($('#submitProfile')[0]);
formData.append('route','account/profile');
$.ajax({
url: 'index.php?route=tool/upload/logo',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
$("#containerAlertMessages").html("<div class='alert alert-info'><strong>Sending...</strong></div>");
$("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
},
complete: function() {
$("#containerAlertMessages").html("<div id='alertMessages' class='alert alert-success'><strong>Success!</strong> Your logo has been uploaded successfully! Do not forget to save the abovr information by clicking the Save button at the bottom right corner!</div>");
$("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
},
success: function() {
//nothing yet
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});

Inside file upload.php:

public function logo() {
$this->load->language('tool/upload');

if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
$filename = html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8');


$route = $this->request->post['route'];
if($route == "account/profile") {
$file = "image/" . $filename;
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_LOGOS . $file);
}
}
}
  • DIR_LOGOS has been defined inside config.php file, so I could reffer to this variable again in another file if I want it to.
  • Furthermore, I am sending the route variable, in order to know from where the image upload is coming.
    So, if the uploading is coming from 'account/profile' I am saving the image to '/image' folder
    if its coming from 'accoun/register' I am saving to '/image/register' or whatever folder I want to (existing one or not), and so on

I hope that helps someone, with same issues!

How To Upload Image with AJAX

jQuery's ajax function can send files too, but you must send a FormData:

$("#form").submit(function(e) {

e.preventDefault();

//This line replaces the jQuery's serialize function:
var formData = new FormData($("#form").get(0));
//And then, you can add extra field/values like this, if you need to:
formData.append("dato", "valor");

$.ajax({
url: 'config.php',
type: 'POST',
data: formData ,
contentType: false,
processData: false,
success: function () {
$(".upClass").html("Updated");
}
})
})

The contentType: false and processData: false ensure that the data is send as 'application/x-www-form-urlencoded', the same way as if it where a normal form submit.



Related Topics



Leave a reply



Submit