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);
});
Related
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.
There is a HTML form having input fields Name, Location, Address, Family members(Csv to be uploaded) and a Submit button. But when clicked on submit, Csv file data is not being passed to the php. Below is the code for reference,
var formData = new FormData($('.AdvFrm')[0]);
$.ajax({
type: "POST",
method: "POST",
url: "test.php",
data: formData.serialize(),
cache: false,
contentType: false,
processData: false,
enctype: 'multipart/form-data',
success: function(data) {}
});
I don't know why you put your data in a FormData part then serialize it? It should return error because there is no serialize method of FormData.
I guess that you've just changed it from jQuery serialize object to FormData in the first line.
And in your case, all you need to do is change formData.serialize() to formData
var formData = new FormData($('.AdvFrm')[0]);
$.ajax({
type: "POST",
method: "POST",
url: "test.php",
data: formData,
cache: false,
contentType: false,
processData: false,
enctype: 'multipart/form-data',
success: function(data) {}
});
If you your formData object is not contains the detail you should add it like this:
var formData = new FormData();
var file = $('#file').val(); // Remember to put an id to your file <input type="file" id="file" />
formData.append('file', file);
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,
});
I am trying to upload firstname, lastname, description and image path to MySql database. And move uploaded image to specific folder.
Here is my ajax function
formData = new FormData(addPeopleForm);
var file_data = $('input[type="file"]')[0].file;
formData.append("file", file_data);
$.ajax({
type: "POST",
url: "functions.php",
contentType: false,
cache: false,
processData: false,
data: {
function: "savepeople",
data: formData
}, success: function(data){
console.log(data);
getPeople();
}
});
functions.php
if(isset($_POST['function'])){
$f = $_POST['function'];
if($f == "savepeople"){
require_once("config.php");
echo $_POST['firstname'];
.
.
.
you can not send directly image to php file with ajax call, you have to take form enctype="multipart/form-data" while form defination
and replace this code for file upload while ajax call
for appending file in formdata use below code
formData = new FormData(); //your form name
var file_data = $('input[type="file"]')[0].file;
formData.append("file", file_data);
formData.append("function","savepeople"); // new variable for your php condition
$.ajax({
url: "YOUR_FILE_PATH",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
// success operation here
},
and on php side you have to use $_FILES['YOUR_FILE_NAME'] instead of $_POST['YOUR_FILE_NAME'] for accessing a uploaded file on server.
you can try this code
$.ajax({
type:'POST',
url:'functions.php',
data:new FormData($('#my_form')[0]),
cache: false,
contentType: false,
processData: false,
success:function(msg)
{
console.log(msg);
}
});
return false;
where #my_form is your form id
var formData = new FormData($(this)[0]);
var action = "savepeople";
$.ajax({
url : 'functions.php',
type : 'POST',
data: {action:action,formData:formData},
contentType: false,
cache: false,
processData:false,
async : false,
, success: function(data){
console.log(data);
getPeople();
}
});
functions.php
if(isset($_POST['action']) && $_POST['action'] == "savepeople"){
//TO DO CODE
}
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);
}
});
});