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');
}
});
Related
So I have a form and I'm submitting the form through ajax using jquery serialization function
serialized = $(Forms).serialize();
$.ajax({
type : "POST",
cache : false,
url : "blah",
data : serialized,
success: function(data) {
}
but then what if the form has an <input type="file"> field....how do I pass the file into the form using this ajax serialization method...printing $_FILES doesn't output anything
Use FormData object.It works for any type of form
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:
$(function() {
$('#ifoftheform').ajaxForm(function(result) {
alert('the form was successfully processed');
});
});
The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...
var form = $('#job-request-form')[0];
var formData = new FormData(form);
event.preventDefault();
$.ajax({
url: "/send_resume/", // the endpoint
type: "POST", // http method
processData: false,
contentType: false,
data: formData,
It worked for me! just set processData and contentType False.
HTML
<form name="my_form" id="my_form" accept-charset="multipart/form-data" onsubmit="return false">
<input id="name" name="name" placeholder="Enter Name" type="text" value="">
<textarea id="detail" name="detail" placeholder="Enter Detail"></textarea>
<select name="gender" id="gender">
<option value="male" selected="selected">Male</option>
<option value="female">Female</option>
</select>
<input type="file" id="my_images" name="my_images" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
</form>
JavaScript
var data = new FormData();
//Form data
var form_data = $('#my_form').serializeArray();
$.each(form_data, function (key, input) {
data.append(input.name, input.value);
});
//File data
var file_data = $('input[name="my_images"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
data.append("my_images[]", file_data[i]);
}
//Custom data
data.append('key', 'value');
$.ajax({
url: "URL",
method: "post",
processData: false,
contentType: false,
data: data,
success: function (data) {
//success
},
error: function (e) {
//error
}
});
PHP
<?php
echo '<pre>';
print_r($_POST);
print_r($_FILES);
echo '</pre>';
die();
?>
You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.
$.ajax({
url: "ajax.php",
type: "POST",
data: new FormData('form'),
contentType: false,
cache: false,
processData:false,
success: function(data) {
$("#response").html(data);
}
});
$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
data: formData,
dataType: "json",
url: form.attr('action'),
processData: false,
contentType: false,
success: function(data) {
alert('Sucess! Form data posted with file type of input also!');
}
)};});
By making use of new FormData() and setting processData: false, contentType:false in ajax call submission of form with file input worked for me
Using above code I am able to submit form data with file field also through Ajax
HTML5 introduces FormData class that can be used to file upload with ajax.
FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
FormData - Mozilla.org
Hi i have problem with ajax and formData
var formData = new FormData($('form')[0]);
formData.append('image', $('inputFile')[0].files[0]);
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
});
in PHP i just print_r $_POST and $_FILES and it's empty.
HTML
<form onsubmit="return false;" enctype="multipart/data-form" method="POST">
<input type="file" id="inputFile" />
</form>
UPDATE
Headers are sent, request payload has the content but still $_POST or $_FILES are emptry.
var file_data = $("#inputFile").prop("files")[0];
var formData = new FormData();
formData.append("image", file_data);
$.ajax({
type: 'post',
cache: false,
processData: false,
url: url,
data: ajaxData,
error: function (result) {},
success: function (result) {}
});
You can get this as $_FILES['image'] in php code
No matter what I do I can't seem to get a file to upload via AJAX to CodeIgniter method. It always throws and never sees an uploaded file.
HTML
<div>
<h1>Upload Your Translation</h1>
</div>
<form method="POST" class="myForm" enctype="multipart/form-data">
<!-- add your span and pther stuff here-->
<input type="file" id="foto1" name="userfile" />
<input type="button" value="submit" onclick="submitFile();" />
</form>
<script>
function submitFile(){
var formUrl = "/system_administration/AJAX_upload_translation";
var formData = new FormData($('.myForm')[0]);
$.ajax({
url: formUrl,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data, textSatus, jqXHR){
//now get here response returned by PHP in JSON fomat you can parse it using JSON.parse(data)
},
error: function(jqXHR, textStatus, errorThrown){
//handle here error returned
}
});
}
</script>
PAYLOAD
Request Method:POST
Status Code:200 OK
------WebKitFormBoundaryvkN2BT8ZDxXmKj7Y
Content-Disposition: form-data; name="userfile"; filename="clippy-windows-8-10.jpg"
Content-Type: image/jpeg
function AJAX_upload_translation()
{
if (!isset($_FILES['userfile']['error']) || is_array($_FILES['userfile']['error']))
{
throw new RuntimeException('Invalid parameters.');
}
}
Try this code..
$('#upload').on('click', function() {
var file_data = $('#foto1').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'your_upload_php_file', // 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(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
Set form action path and use this for ajax(better not to use onclick function)
$(document).on("submit", ".myForm", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//set form action url at your form
type: $(this).attr("method"),//set form method at your form
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
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
So I have a form and I'm submitting the form through ajax using jquery serialization function
serialized = $(Forms).serialize();
$.ajax({
type : "POST",
cache : false,
url : "blah",
data : serialized,
success: function(data) {
}
but then what if the form has an <input type="file"> field....how do I pass the file into the form using this ajax serialization method...printing $_FILES doesn't output anything
Use FormData object.It works for any type of form
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:
$(function() {
$('#ifoftheform').ajaxForm(function(result) {
alert('the form was successfully processed');
});
});
The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...
var form = $('#job-request-form')[0];
var formData = new FormData(form);
event.preventDefault();
$.ajax({
url: "/send_resume/", // the endpoint
type: "POST", // http method
processData: false,
contentType: false,
data: formData,
It worked for me! just set processData and contentType False.
HTML
<form name="my_form" id="my_form" accept-charset="multipart/form-data" onsubmit="return false">
<input id="name" name="name" placeholder="Enter Name" type="text" value="">
<textarea id="detail" name="detail" placeholder="Enter Detail"></textarea>
<select name="gender" id="gender">
<option value="male" selected="selected">Male</option>
<option value="female">Female</option>
</select>
<input type="file" id="my_images" name="my_images" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
</form>
JavaScript
var data = new FormData();
//Form data
var form_data = $('#my_form').serializeArray();
$.each(form_data, function (key, input) {
data.append(input.name, input.value);
});
//File data
var file_data = $('input[name="my_images"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
data.append("my_images[]", file_data[i]);
}
//Custom data
data.append('key', 'value');
$.ajax({
url: "URL",
method: "post",
processData: false,
contentType: false,
data: data,
success: function (data) {
//success
},
error: function (e) {
//error
}
});
PHP
<?php
echo '<pre>';
print_r($_POST);
print_r($_FILES);
echo '</pre>';
die();
?>
You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.
$.ajax({
url: "ajax.php",
type: "POST",
data: new FormData('form'),
contentType: false,
cache: false,
processData:false,
success: function(data) {
$("#response").html(data);
}
});
$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
data: formData,
dataType: "json",
url: form.attr('action'),
processData: false,
contentType: false,
success: function(data) {
alert('Sucess! Form data posted with file type of input also!');
}
)};});
By making use of new FormData() and setting processData: false, contentType:false in ajax call submission of form with file input worked for me
Using above code I am able to submit form data with file field also through Ajax
HTML5 introduces FormData class that can be used to file upload with ajax.
FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
FormData - Mozilla.org