jQuery file Upload and ajax - javascript

So, I have the following form and js/php:
php
<form enctype="multipart/form-data">
<input id="fileupload" type="file" name="files[]" class="files " onChange="UploadImage" accept='image/*'/>
<input type="button" class="submit_form" value="submit">
</form>
<?php
add_action( 'wp_ajax_UploadImage', 'UploadImage' );
function UploadImage()
{
$upload_dir = wp_upload_dir();
$files = $_FILES['files'];
//Some function
}
?>
JS
function UploadImage(e)
{
jQuery('#fileupload').fileupload({
url: upload_image.ajax_url,
});
if(jQuery('#fileupload')) {
var form = document.forms.namedItem("upload_video");
var formdata = new FormData(form);
formdata.append('action', 'UploadImage');
jQuery.ajax({
success : function(data){
alert('sddsf');
}
})
}
};
As you can see from here, when an image is selected using Blueimp jQuery File upload (which the js is not properly written), I want the image file to be handled by the php function.
In other words, the js is not correctly written and I am not sure how to initiate the plugin then when the image is selected, it is processed by the php function via ajax (meaning, how do I parse the file info to php function via ajax?)

Don't use $.ajax directly. The plugin already does that behind the scenes.
Here's a working example, based on your code, but adapted to run on JSFiddle:
$(document).ready(function(){
var url = '/echo/json/';
var formdata = {json: JSON.stringify({field1: 'value1'})};
jQuery('#fileupload').fileupload({
url: url,
formData : formdata,
dataType: 'json',
type: "POST",
contentType:false,
processData:false,
success : function(data){
alert('success...');
console.dir(data);
}
});
});
Demo: http://jsfiddle.net/pottersky/8usb1sn3/3/

Related

Empty array when dd($request->all()) upload file via ajax laravel

first of all i try to do the file uploading via ajax , when i try dd($request->all())in my controller , it give result empty array
public function uploadFile(Request $request){
dd($request->all());
}
My blade view with ajax
<label for="inputfile">
<a title="Click here to upload record "><i class="fa fa-upload"></i></a>
</label>
<input id="inputfile" name="inputfile" type="file" />
<script>
$('#inputfile').on('change',function(ev){
ev.preventDefault();
var postData=new FormData();
postData.append('file',this.files[0]);
$.ajax({
url:'{{url('reporting/uploadFile')}}',
headers:{'X-CSRF-Token':$('meta[name=csrf_token]').attr('content')},
type:"get",
contentType:false,
data:postData,
processData:false,
dataType:'json',
success: function( data ) {
console.log(data)
},
error: function() {
alert('error');
} }); });
</script>
My laravel version is 5.8 . The flow is when the user upload attachment, it will directly store to file storage without clicking button submit . But when i try to retrieve $request->all() its return empty array which is i can't continue further step. Sorry if my explaination not clear .
Yes ok laravel can be a real pain sometimes especially when it comes to file uploads.
You can try this article for laravel 5.8 give it a try and let me know if it works.
https://www.w3adda.com/blog/laravel-5-8-jquery-ajax-form-submit
I think the main difference with this article is the way it sets the data in the ajax call. However you might need to check the whole article over and compare it to your code.
$.ajax({
url: "{{ url('jquery-ajax-form-submit')}}",
method: 'post',
data: $('#contact_us').serialize(),
Please ensure you are using the form multipart setting correctly.
This is usually the issue in most cases.
<form action="upload.php" method="post" enctype="multipart/form-data">
let files = $('#inputfile');
let image = files[0].files;
let form_data = new FormData();
if (image.length > 0) {
for (let i = 0; i < image.length; i++)
form_data.append('inputfile[]', image[i]);
}
$.ajax({
url:'{{url('reporting/uploadFile')}}',
headers:{'X-CSRF-Token':$('meta[name=csrf_token]').attr('content')},
type:"get",
contentType:false,
data:form_data,
processData:false,
dataType:'json',
success: function( data ) {
console.log(data)
},
error: function() {
alert('error');
}
});
});
try this.
You just need to set "Content-Type" in header.
You also have pass type get, for file upload must require post.
have you console.log(this.files[0]);
<script>
$('#inputfile').on('change',function(ev){
ev.preventDefault();
console.log(this.files[0]);
var postData=new FormData();
postData.append('file',this.files[0]);
$.ajax({
url:'{{url('reporting/uploadFile')}}',
headers:{
'X-CSRF-Token':$('meta[name=csrf_token]').attr('content'),
'Content-Type': undefined
},
type:"POST",
data:postData,
success: function( data ) {
console.log(data)
},
error: function() {
alert('error');
} }); });
</script>

send image url and data through serialization

I am trying to make a form where there will be user data(name,dob etc) and an image. When user submits the form a pdf will be generated with the user given data and the image. I can successfully serialize the data but failed to get image in my pdf. I am using simple ajax post method to post data. Below is my code.
HTML code
<form onsubmit="submitMe(event)" method="POST" id="cform">
<input type="text" name="name" placeholder="Your Name" required>
<input type="file" name="pic" id="pic" accept="image/*" onchange="ValidateInput(this);" required>
<input type="submit" value="Preview"/>
</form>
Jquery code
function submitMe(event) {
event.preventDefault();
jQuery(function($)
{
var query = $('#cform').serialize();
var url = 'ajax_form.php';
$.post(url, query, function () {
$('#ifr').attr('src',"http://docs.google.com/gview?url=http://someurl/temp.pdf&embedded=true");
});
});
}
PHP code
<?php
$name=$_POST['name'];
$image1=$_FILES['pic']['name'];
?>
Here I am not getting image1 value. I want to get the url of the image.
You need FormData to achieve it.
SOURCE
Additionally, you need to change some stuff inside ajax call(explained in link above)
contentType: false
cache: false
processData:false
So the full call would be:
$(document).on('change','.pic-upload',uploadProfilePic);
#.pic-upload is input type=file
function uploadProfilePic(e){
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
$.ajax({
type:"POST",
url:"uploadpic.php",
data: actual,
contentType: false,
cache: false,
processData:false,
dataType:"json",
success: function (response){
#Maybe return link to new image on successful call
}
});
}
Then in PHP you handle it like this:
$_FILES['file']['name']
since you named it 'file' here:
actual.append('file', newpic[0]);

Image upload via ajax POST without using HTML form

I am trying to send some data via POST method to a PHP file without using form in HTML. This is the code I have. Why doesn't it do anything?
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid" id="gid">
<input type="hidden" value="User" name="user" id="user">
<button onclick="myFormData()">Upload Image</button>
<script>
$('#fileToUpload').on('change', function() {
var myFormData = new FormData();
var file = document.getElementById('fileToUpload').value;
var gid = document.getElementById('gid').value;
var user = document.getElementById('user').value;
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
});
$.ajax({
url: 'imgupload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
</script>
On imgupload.php I get the POST data like this
$gid = $_POST['gid'];
$user = $_POST['user'];
It worked when I used the HTML form method. What's wrong here?
FormData.append() takes key-value pairs, so this is wrong:
myFormData.append(file,gid,user);
You need something like:
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
Appart from that you need to put this code inside an event handler so that it triggers when you need it to.
For example:
$('#fileToUpload').on('change', function() {
// your javascript code
});
And you should probably also put it inside a document.ready block.

Isset does not work with ajax call

I am making a simple page where user can upload a image without refreshing the whole page. But if(isset($_post[oneimgtxt])) is not working..
here is my serverSide Code that upload image :
<?php
$maxmum_size = 3145728; //3mb
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["oneimgtxt"])){//<!------------------ this line is not working
if((!empty($_FILES[$_FILES['upimage']['tmp_name']])) && ($_FILES["upimage"]['error'] == 0)){
$file=$_FILES['upimage']['tmp_name'];
$image_count = count($_FILES['upimage']['tmp_name']);
if($image_count == 1){
$image_name = $_FILES["upimage"]["name"];
$image_type = $_FILES["upimage"]["type"];
$image_size = $_FILES["upimage"]["size"];
$image_error = $_FILES["upimage"]["error"];
if(file_exists($file)){//if file is uploaded on server in tmp folder (xampp) depends !!
$filetype =exif_imagetype($file); // 1st method to check if it is image, this read first binary data of image..
if (in_array($filetype, $image_type_allowed)) {
// second method to check valid image
if(verifyImage($filename)){// verifyImage is function created in fucrenzione file.. using getimagesize
if($ImageSizes < $maxmum_size){//3mb
$usr_dir = "folder/". $image_name;
move_uploaded_file($file, $usr_dir);
}else{
$error_container["1006"]=true;
}
}else{
$error_container["1005"]=true;
}
}else{
$error_container["1004"]=true;
}
}else{
$error_container["1003"]=true;
}
}else{
$error_container["1002"]=true;
}
}else{
$error_container["1007"]=true;
}
}else{//this else of image issset isset($_POST["oneimgtxt"])
$error_container["1001"]=true;//"Error during uploading image";
}
echo json_encode($error_container);
}
?>
in chrome inspect element i got this..
image
and this is my js code with ajax...
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: {oneimgtxt : formdata},
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Here is html code:
<form method="post" id="f12le" enctype="multipart/form-data">
<input type="file" name="upimage"/>
<label for="imgr">Choose an Image..</label>
<textarea placeholder="Write something about photo"></textarea>
<input type="button" name="addimagedata" value="Post" class="sndbtn"/>
</form>
Thanks for any help.
You should send your FormData as a whole data object not a part of another data object. So, it should be like this -
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: formdata,
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Now, you should be able to access the form as it is. For example if you have any input with name inputxt inside the form, you should be able to access it with $_POST['inputxt']. And if you have any input type="file" with the name upimage, you need to access through $_FILES['upimage']. So, if you want to do isset() for that. You can do like this :
if(isset($_FILES['upimage'])){
add enctype on form any time using file inputs
<form enctype="multipart/form-data" >
<input type=file />
...
</form>
and make sure it's always a POST request.
Good luck...!
I had headaches for this thing! you should use $_FILES['name_of_dom_element']; in your php code.

Passing image from form to wordpress using ajax without any plugin

I have made a form on my wordpress theme through which i want user to upload image .This is my HTML
<input type="file" id="file" />
<button id="uplod" ">Upload</button>
and below is my js
jQuery("#uplod").click(function()
{
console.log("trying to fetch image");
var selectedFile = jQuery('#file').get(0).files[0];
console.log(selectedFile);
var ajaxdata=
{
action:"reg_upload_img",
img:"selectedFile"
}
jQuery.post(ajaxurl, ajaxdata,function(res)
{
jQuery(".divError").html(res);
});
});
and my function in functions.php file of theme is
function fiu_upload_file(){
$error = '';
var_dump($_FILES);
wp_die();
}
add_action('wp_ajax_reg_upload_img', 'fiu_upload_file');
add_action('wp_ajax_nopriv_reg_upload_img', 'fiu_upload_file');
what should i add in my js code and php code so that image of form can be passed to my wordpress directory so that i can save and handle it in wp database
You can't upload files with jQuery.post(), only XMLHttpRequest can be used with FormDataand jQuery.ajax() can be used which uses XMLHttpRequest internally.
jQuery("#uplod").click(function(e) {
e.preventDefault();
var fd = new FormData($("#file"));
fd.append("action", "reg_upload_img");
fd.append("img","selectedFile");
$.ajax({
url: url,
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
});
and a small typo with your button's attributes, you have an extra ":
<button id="uplod">Upload</button>
//----------------^-----------one extra '"' removed from here.

Categories

Resources