jQuery + php file upload. Pass multiple parameters - php

How to pass extra variables through $.ajax to post.php?
My first variable is
var form_data = new FormData($(this)[0])
I can pass it alone, but if I want to add another variable and make an array
data {
"form_data": form_data,
"name": "hello"
}
it does't work.
My current code:
$(document).ready(function() {
$("form#data").submit(function(){
var form_data = new FormData($(this)[0]);
$.ajax({
url: 'post.php',
type: 'POST',
data: form_data,
success: function (data) {
$('#result').html(data);
},
contentType: false,
processData: false
});
return false;
});
});
<div id="result"></div>
<form id="data" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<button>Submit</button>
</form>

Try this. The formData object has a method append. We're going to use that instead. We're going to append the file under the name file. In PHP access it with $_FILES['file']. Now for the array or object that you want to add to it. Use JSON.stringify on it to turn it into a string. We append the JSON string and add it to the name 'object'. To access the JSON in PHP json_decode($_POST['object']) will turn it into an object.
Fiddle
$(function(){
$("form#data").submit(function (e) {
e.preventDefault();
var form_data = new FormData(),
o = {};
o.name = 'Adam';
o.arr = ['test', 213];
form_data.append('file', $('input[name="file"]', this)[0].files[0]);
form_data.append('object', JSON.stringify(o));
$.ajax({
url: '/info/',
type: 'POST',
data: form_data,
success: function (data) {
$('#result').html(data);
},
contentType: false,
processData: false
});
return false;
});
});

I would JSON.stringify it then json_decode when you get it back in PHP
var data = JSON.stringify({ /* object */ });
Then in your php
$data = json_decode(....);

Try to define a new bariable
var name = "hello";
and then insert it into $.ajax data
$.ajax({
url: 'post.php',
type: 'POST',
data: "form_data="+form_data+"&name="+name,
success: function (data) {
$('#result').html(data);
},
contentType: false,
processData: false
});
I never test this script, but there's no matter to check it out :D

Related

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

JQuery fomdata sending empty data to php file?

I am trying to upload file through jquery formdata without any form. My problem is that it is not sending any data to php file.
Here is my jquery code
jQuery(document).ready(function() {
jQuery('#e_picture').change(function() {
var file_data = jQuery('#e_picture').prop('files')[0];
var form_data = new FormData();
form_data.append('e_picture', file_data);
form_data.append('e_uid', '3585');
//});
// data: {e_uid: e_uid, e_picture:'23'},
jQuery.ajax({
url: "index.php?option=com_objectified&task=course_reg.addPicture",
type: 'POST',
data: {
form_data
},
processData: false,
contentType: false,
success: function(result) {
alert('This is ' + result); // Here I show onlu e_uid but it alerts blank result
}
});
});
});
Html
<input type="file" class="form-control" name='e_picture' id='e_picture'>
You are sending the form_data in wrong way
instead of
data: {
form_data
},
just send it like
data: form_data,
jQuery(document).ready(function() {
jQuery('#e_picture').change(function() {
var file_data = jQuery('#e_picture')[0].files;
var form_data = new FormData();
form_data.append("e_picture[]", file_data[0]);
form_data.append('e_uid', '3585');
//});
// data: {e_uid: e_uid, e_picture:'23'},
jQuery.ajax({
url: "index.php?option=com_objectified&task=course_reg.addPicture",
type: 'POST',
data: {
form_data
},
processData: false,
contentType: false,
success: function(result) {
alert('This is ' + result); // Here I show onlu e_uid but it alerts blank result
}
});
});
});
ange content type to :
contentType: 'multipart/form-data',

AJAX send data to PHP file

send $username php with data: new FormData(this), to add.php like data: new FormData(this),$username how can i do it with ajax code
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadFormuserimg").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "add.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#user_img_a").html(data);
},
error: function()
{ alert("error");
}
});
}));
});
</script>
var myData = new FormData(this);
myData.append('username','<?php echo $username; ?>');
and get on "add.php" like this
$username = $_POST['username'];
This worked on my side.
Based on comments to the question, specifically:
I just want to add some data
Are you just asking how to add more fields to the object that was created already in the data value? Something like this:
var myData = new FormData(this);
myData.append("anotherField", "anotherValue");
// etc.
Then just use that variable as your AJAX data:
$.ajax({
url: "add.php",
type: "POST",
data: myData,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#user_img_a").html(data);
},
error: function()
{ alert("error");
}
});
You can store anything you like in a variable and use that variable at a later time. With a FormData object you would generally use .append() to add more key/value pairs to it.

A FormData object is always empty when trying to upload a file using AJAX

When trying to upload an image using AJAX without submitting the form directly and sending a FormData object to server it returns empty $_FILES array. But if I submit the form using <input type="submit"> tag $_FILES array is not empty and recieves the data.
HTML
<form action="core/update.php" method="post" enctype="multipart/form-data" id="profile-photo" name="profile-photo-form">
<input type="file" id="photo-filename" name="avatar" class="edit-show panel photo-upload">
</form>
<button class="save-button" disabled="disabled">Save</button>
JS
$('#profile-photo').on('submit', function(e) {
e.preventDefault();
var form = $('#profile-photo')[0];
var formData = new FormData(form);
formData.append('avatar', $('#photo-filename')[0].files[0]);
$.ajax({
url: "core/update.php",
data: formData,
type: "POST",
contentType: false,
cache: false,
processData: false
});
console.log(formData);
});
$('.save-button').on('click', function() {
if ($('#photo-filename').val != '') {
$('#profile-photo').submit();
};
}
UPD
Also $('#profile-photo').serialize() returns blank string.
UPD 2
Can it conflict with the other AJAX-requests on the page?
Try this:
Because user may upload multiple files
jQuery.each(jQuery('#photo-filename')[0].files, function(i, file) {
data.append('file-'+i, file);
});
Instead of
formData.append('avatar', $('#photo-filename')[0].files[0]);
Complete Solution:
$('#profile-photo').on('submit', function(e) {
e.preventDefault();
var form = $('#profile-photo')[0];
var formData = new FormData(form);
jQuery.each(jQuery('#photo-filename')[0].files, function(i, file) {
formData.append('file-'+i, file);
});
$.ajax({
url: "core/update.php",
data: formData,
type: "POST",
contentType: false,
cache: false,
processData: false
});
console.log(formData);
});
Try the following,
$('#profile-photo').on('submit', function(e) {
e.preventDefault();
var formData = new FormData(this); // here I am editing
formData.append('avatar', $('#photo-filename')[0].files[0]);
$.ajax({
url: "core/update.php",
data: formData,
type: "POST",
contentType: false,
cache: false,
processData: false
});
console.log(formData);
});
If it is only the file you want to send then you can do it as below and no need to attach form here to formdata:
$('#profile-photo').on('submit', function(e) {
e.preventDefault();
var formdata = new FormData();
var fileInput = $('#photo-filename');
//Use Either this
$.each($(fileInput).get(0).files, function (index, value) {
formdata.append('avatar', value);
});
//Or this
$.each($(fileInput).get(0).files, function (index, value) {
formdata.append(value.name, value);
});
//For single file use this
formData.append('avatar', $('#photo-filename')[0].files[0]);
$.ajax({
url: "core/update.php",
data: formData,
type: "POST",
contentType: false,
cache: false,
processData: false
});
console.log(formData);
});

jQuery Ajax posting not working

My jQuery ajax posting is not working. Here is the javascript
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: postData,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
I am saving the data to be posted inside a hidden div like
<div class='WrapperDiv hidden'>{"post_id":392,"url":"http:\/\/www.wordpress-site\/post\/post-title\/","title":"SEO Friendly title"}</div>
All I am getting in return from the post.php page is an empty array. Here is my code for post.php
<?php
if(isset($_POST)){
print_r($_POST);
} else {
echo "0";
}
?>
Any Idea whats wrong?
EDIT : Its working after I removed
contentType: "application/json",
dataType: 'json'
What about something like this:
var postData = "data=" + encodeURCIComponent($buttonWrapper.html());
Than in PHP:
echo $_POST["data"];
Than parse it or something....
Couple of things to try,
Try to pass the data directly in to the data object first. If it
works then you can debug and see why it's not ready your hidden div.
instead of $buttonWrapper.html try $buttonWrapper.text();
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.**text**();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: **{'id':1}**,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Inside your jQuery ajax call, your data is not set to $_POST variable names. Hence why nothing is showing
Try changing your function to this:
function SocialButtons() {
var buttonWrapper = jQuery('.WrapperDiv');
if (buttonWrapper.length){
var postData = buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: {postData: postData},
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Then you should have a $_POST['postData'] variable on your print_r or var_dump of $_POST.
Its working after I removed
contentType: "application/json",
dataType: 'json'

Categories