Ajax file upload outside of form without plugins - php

I've been searching for a solution to upload files using Ajax when the input field is not inside a form tag. I have already tried this solution.
This is my HTML
<span id="user-image-up-btn">Last opp bilde</span>
<input id="user_image_upload" type="file" />
This is my code, and I get the return TypeError: undefined is not an object (evaluating '$("#user_image_upload").files') or when I use alternative number 2, I get Object, object.
This is my jQuery
// IMAGE UPLOAD
$("#user_image_upload").change(function() {
var fileform = new FormData();
fileform.append('pictureFile', $("#user_image_upload").files[0]);
$.ajax({
url: '/userimageupload',
type: 'POST',
processData: false,
contentType: false,
dataType : 'json',
data: fileform,
beforeSend: function(){
$("#user-image-up-btn").html('Laster opp...');
console.log(fileform);
},
success: function(data){
$("#user-image-up-btn").html('Last opp bilde');
console.log(fileform);
},
error: function(exception){
alert('error:'+exception);
console.log(fileform);
}
});
});
EDIT:
By using the answer from Adeneo I managed to upload the files. However, I still get error:[object Object], which causes the rest of the form to fail. How come?

A jQuery object has no files property, that would be the underlying DOM node
$("#user_image_upload").on('change', function() {
var fileform = new FormData();
fileform.append('pictureFile', this.files[0]);
$.ajax({
url: '/userimageupload',
type: 'POST',
processData: false,
contentType: false,
dataType : 'json',
data: fileform,
beforeSend: function(){
$("#user-image-up-btn").html('Laster opp...');
},
success: function(data){
$("#user-image-up-btn").html('Last opp bilde');
},
error: function(exception){
alert('error:'+exception);
}
});
});

Related

CSRF token mismatch when setting processData: false, contentType: false,

Hey guys I'm trying to send files to Laravel server using ajax for that i need to create form data and send it with the ajax request and in order to prevent illegal invocation i need to set these
processData: false,
contentType: false,
heres my code->
$("#saveChanges").click(function () {
let formData = new FormData();
formData.append("banner", $("input[name='banner']"));
$.ajax({
url: "/save/website/data",
type: "POST",
data: {
pickUpBtnColor: $("input[name='pickUpBtnColor']").val(),
banner: $("input[name='banner']").val(),
logo: $("input[name='logo']").val(),
_token: $('meta[name="csrf"]').attr("content"),
formData: formData,
},
processData: false,
contentType: false,
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
},
});
});
But when i set these my csrf is also ignored and the server responds with "CSRF token mismatch."
Any one has a solution?
The issue is because you need to place all the form field values within a single FormData object and send that in the request.
$("#saveChanges").click(function() {
let formData = new FormData();
formData.append("banner", $("input[name='banner']"));
formData.append('pickUpBtnColor', $("input[name='pickUpBtnColor']").val());
formData.append('banner', $("input[name='banner']").val());
formData.append('logo', $("input[name='logo']").val());
formData.append('_token', $('meta[name="csrf"]').attr("content");
$.ajax({
url: "/save/website/data",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
},
});
});
Note that you could potentially simplify this if your input elements are contained within a form; hook to the submit event of the form element instead of the click of the button, and then call let formData = new FormData(referenceToYourFormHere);. There is no need for the append() calls when using the constructor in this manner.

Pass form data via Ajax into PhP

I have a form using both text-fields and upload-fields.
<form action="submit" method="post" enctype="multipart/form-data">
<input type="text" name="textfield">
<input type="file" name="file_upload">
<button type="submit">Submit</button>
</form>
How can I pass all the inserted data via ajax and use the data in PhP?
What I currently trying via ajax is:
var fd = new FormData($('form'));
$.ajax({
url: ajaxurl,
type: 'POST',
processData: false,
contentType: false,
data: {
fd: fd,
action: 'devplus_submit_annex' // a php function
},
success: function(response) {
JSON.parse(response);
},
error: function(response) {
console.log('Error');
}
});
The FormData constructor takes an HTMLFormElement as its argument, you passed a jQuery object.
For jQuery.ajax you pass the form data object alone as the data field
If you need to add data outside of the from you can use the append() method.
var fd = new FormData($('form')[0]);
fd.append('action', 'devplus_submit_annex');
$.ajax({
url: ajaxurl,
type: 'POST',
processData: false,
contentType: false,
data: fd,
success: function(response) {
JSON.parse(response);
},
error: function(response) {
console.log('Error');
}
});

PHP get post button through ajax

In product-master.php (view page), I have a few buttons: Add, Edit, Delete.
Each button got unique name: btnAddProduct, btnEditProduct, btnDelProduct
These buttons share the same action page as shown in the ajax code below: action/product-master.php (yes I named it according to the view page, just different folder)
Yes, I'm using ajax method to process form data. How to validate which button was pressed?
I tried using isset($_POST['btnAddProduct']) but it is not working. Below is my button:
btnAddProduct
<input type="submit" class="btn btn-success" id="btnAddProduct" name="btnAddProduct">
product-master.php
$('#btnAddProduct').on('click', function(e) {
var formData = new FormData($('#form-add-modal')[0]);
$.ajax({
url: "action/<?php echo basename(__FILE__); ?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(){
//Display error here
}
});
});
Buttons aren't included when you create a FormData from a form, since the FormData constructor has no way of knowing which button was clicked. You need to add it to the FormData explicitly.
$('#btnAddProduct').on('click', function(e) {
var formData = new FormData($('#form-add-modal')[0]);
formData.set(this.name, "1");
$.ajax({
url: "action/<?php echo basename(__FILE__); ?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(){
//Display error here
}
});
});

PHP Ajax Post File and Text Same Time

I can post only image and get it with $_FILES['foto']['name']. I need post image and text same time.
var fotoFile = new FormData();
$('#foto').on('change', function (evt) {
var files = evt.target.files;
if (files.length > 0) {
fotoFile.append("foto", files[0]);
}
});
It is post code
` $.ajax({
url: 'postpages/personelsave.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: {foto : fotoFile, tc_no : document.getElementById('tcNo').value},
success: function(php_script_response){
alert(php_script_response);
}
});`
and personelsave.php
$_FILES['foto']['type']
$_POST["tc_no"]
Error : undefined index foto.
What is wrong with it?
You can't use multiple dataTypes, if you use JSONP this will return a jsonp block which you could use to call a callback to handle the return data like this:
Basic example of using .ajax() with JSONP?
So through JSONP you can handle multiple dataTypes.
Just use below to submit all types of input data including file
var formData = new FormData($("#formID")[0]);
$.ajax({
type: "POST",
url: 'postpages/personelsave.php',
data: formData,
processData: false,
contentType: false,
});

Upload file using jquery ajax, and get result in $_FILES

How to upload file using, I tried this but it's not working and also not giving me the result in $_POST on result page.
$.ajax({
type:'post',
url:'../investor/archive2.php',
enctype: 'multipart/form-data',
tmp_dir:'tmp',
//dataType: 'json',
processData: false, // Don't process the files
//contentType: false,
cache: false,
data:'action='+action+'&title='+title+'&datetime='+datetime+'&name='+docfile,
success:function(result){
alert(result);
}
});
You must use Form data if you are using AJAX.
var data = new FormData()
data.append( 'photo', $('#photo')[0].files[0] ); //photo is the name and id of the <input type="file">
data.append( 'action', action);
data.append( 'title', title);
.
.
$.ajax({
type: "POST",
url: "../investor/archive2.php",
processData: false,
contentType: false,
cache:false,
data: data,
success: function(data){
alert(data);
}
});
You can use jQuery form plugin to handle file uploads through Ajax, files data will be available at the action under $_FILES if you submit a form using that plugin through Ajax.
Plugin Link: http://malsup.com/jquery/form/
Sample Code:
$('#form_id').ajaxForm(function(data, status, jqXHR) {
console.log(data);
});

Categories