I'm completely new to ajax. I want to pass my html form value to php and then get the output from that php page back in the html page
Ajax code
$("#submit1").click(function(){
var formData = $("#add-cart-form").serialize();
$.ajax({
type: 'POST',
url: 'test.php',
dataType : 'json',
data: {
'total_load' : $('#total_load').val(),
'hours' : $('#hours').val(),
},
success: function (data) {
alert(data)
},
});
var result = $.parseJSON(output);
alert(result[0]);
});
Relevant php code
$connected_load = $_POST['total_load']; $no_of_hours = $_POST['hours'];
echo json_encode(array(
$connected_load,
$selected_inverter["model"],
$selected_inverter["voltage"],
$selected_inverter["type"],
$no_of_hours,$selected_battery));
IMHO, code has some inaccuracies.
First of all, you're writing:
var formData = $("#add-cart-form").serialize();
...but you're not sending formData via $.ajax. Instead, you're sending other post data, specifically
{ 'total_load' : $('#total_load').val(), 'hours' : $('#hours').val(),}
...and there is an error inside this object, you have a comma just before the closing curly brace.
Anyway, this is the right way to do it (js)
$("#submit1").click(function(event){
// perhaps formData form embrace "total_load" and "hours" ?
var formData = $("#add-cart-form").serialize();
$.ajax({
url: 'test.php',
cache: false, // optional
async: true, // optional, defaults to true. False value will make ajax synchronous, hanging the browser.
data: formData,
type: 'post',
dataType : 'json'
}).done(function(d){ // trying to simplify comprehension of the console.log output, below...
console.log(d.d_connected_load);
console.log(d.d_model);
console.log(d.d_voltage);
console.log(d.d_type);
console.log(d.d_no_of_hours);
console.log(d.d_selected_battery);
}).fail(function(j,s,e){
console.warn(j.responseText);
});
});
and, PHP side:
<?php
$connected_load = $_POST['total_load'];
$no_of_hours = $_POST['hours'];
# stuffs here for sanitizing $_POST and working on $selected_inverter["model"], $selected_inverter["voltage"], $selected_inverter["type"], $selected_battery
echo json_encode(
array(
"d_connected_load" => $connected_load,
"d_model" => $selected_inverter["model"],
"d_voltage" => $selected_inverter["voltage"],
"d_type" => $selected_inverter["type"],
"d_no_of_hours" => $no_of_hours,
"d_selected_battery" => $selected_battery
)
);
You do not need to parse JSON. jQuery will do it for you when you make an ajax call specifying dataType:'json' in the ajaxcall options (and, obviously, the json echoed from php must be well-formed).
Note, in addition, the way the ajax call is written. In latest releases of jQuery the best is to use .done() and .fail() promise methods instead of success and fail. -> http://api.jquery.com/jquery.ajax/
UPDATE: STEP BY STEP EXAMPLE:
I'll try to make it more understandable.
Initial steps:
create a file named form.php;
create a file named ajax_test.php;
create a file named test.js;
...in the same directory.
====== FILE FORM.PHP ======
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<form id="add-cart-form" method="post">
<p>TOTAL LOAD: <input type="text" value="total load" name="total_load" /></p>
<p>TOTAL LOAD: <input type="text" value="hours!" name="hours" /></p>
<hr />
<button type="submit" id="submit1">SUBMIT</button>
</form>
</body>
<script type="text/javascript" src="js/test.js"></script>
</html>
====== FILE AJAX_TEST.PHP ======
<?php
$connected_load = $_POST['total_load'];
$no_of_hours = $_POST['hours'];
# stuffs here for sanitizing $_POST and working on $selected_inverter["model"], $selected_inverter["voltage"], $selected_inverter["type"], $selected_battery
echo json_encode(
array(
"d_connected_load" => $connected_load,
"d_model" => $selected_inverter["model"],
"d_voltage" => $selected_inverter["voltage"],
"d_type" => $selected_inverter["type"],
"d_no_of_hours" => $no_of_hours,
"d_selected_battery" => $selected_battery
)
);
====== FILE TEST.JS ======
$("#submit1").click(function(event){
// perhaps formData form embrace "total_load" and "hours" ?
var formData = $("#add-cart-form").serialize();
$.ajax({
url: 'ajax_test.php',
cache: false, // optional
async: true, // optional, defaults to true. False value will make ajax synchronous, hanging the browser.
data: formData,
type: 'post',
dataType : 'json'
}).done(function(d){ // trying to simplify comprehension of the console.log output, below...
console.log(d.d_connected_load);
console.log(d.d_model);
console.log(d.d_voltage);
console.log(d.d_type);
console.log(d.d_no_of_hours);
console.log(d.d_selected_battery);
}).fail(function(j,s,e){
console.warn(j.responseText);
});
event.preventDefault();
event.stopImmediatePropagation();
return false;
});
Your output variable is not defined at this point. Try to parse response in the callback success function:
success: function (data) {
var result = $.parseJSON(data);
console.log(result[0]);
}
Related
I've got a problem sending a file to a serverside PHP-script using jQuery's ajax-function.
It's possible to get the File-List with $('#fileinput').attr('files') but how is it possible to send this Data to the server? The resulting array ($_POST) on the serverside php-script is 0 (NULL) when using the file-input.
I know it is possible (though I didn't find any jQuery solutions until now, only Prototye code (http://webreflection.blogspot.com/2009/03/safari-4-multiple-upload-with-progress.html)).
This seems to be relatively new, so please do not mention file upload would be impossible via XHR/Ajax, because it's definitely working.
I need the functionality in Safari 5, FF and Chrome would be nice but are not essential.
My code for now is:
$.ajax({
url: 'php/upload.php',
data: $('#file').attr('files'),
cache: false,
contentType: 'multipart/form-data',
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Starting with Safari 5/Firefox 4, it’s easiest to use the FormData class:
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
So now you have a FormData object, ready to be sent along with the XMLHttpRequest.
jQuery.ajax({
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
});
It’s imperative that you set the contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it.
Also, you must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
You may now retrieve the file in PHP using:
$_FILES['file-0']
(There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)
Using the FormData emulation for older browsers
var opts = {
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
};
if(data.fake) {
// Make sure no text encoding stuff is done by xhr
opts.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); xhr.send = xhr.sendAsBinary; return xhr; }
opts.contentType = "multipart/form-data; boundary="+data.boundary;
opts.data = data.toString();
}
jQuery.ajax(opts);
Create FormData from an existing form
Instead of manually iterating the files, the FormData object can also be created with the contents of an existing form object:
var data = new FormData(jQuery('form')[0]);
Use a PHP native array instead of a counter
Just name your file elements the same and end the name in brackets:
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file[]', file);
});
$_FILES['file'] will then be an array containing the file upload fields for every file uploaded. I actually recommend this over my initial solution as it’s simpler to iterate over.
Look at my code, it does the job for me
$( '#formId' )
.submit( function( e ) {
$.ajax( {
url: 'FormSubmitUrl',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
} );
Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES, regardless of whether you use JavaScript to submit.
HTML form:
<form enctype="multipart/form-data" action="/test.php"
method="post" class="putImages">
<input name="media[]" type="file" multiple/>
<input class="button" type="submit" alt="Upload" value="Upload" />
</form>
PHP produces this $_FILES, when submitted without JavaScript:
Array
(
[media] => Array
(
[name] => Array
(
[0] => Galata_Tower.jpg
[1] => 518f.jpg
)
[type] => Array
(
[0] => image/jpeg
[1] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/phpIQaOYo
[1] => /tmp/phpJQaOYo
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 258004
[1] => 127884
)
)
)
If you do progressive enhancement, using Raphael's JS to submit the files...
var data = new FormData($('input[name^="media"]'));
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
data.append(i, file);
});
$.ajax({
type: ppiFormMethod,
data: data,
url: ppiFormActionURL,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
}
});
... this is what PHP's $_FILES array looks like, after using that JavaScript to submit:
Array
(
[0] => Array
(
[name] => Galata_Tower.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpAQaOYo
[error] => 0
[size] => 258004
)
[1] => Array
(
[name] => 518f.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpBQaOYo
[error] => 0
[size] => 127884
)
)
That's a nice array, and actually what some people transform $_FILES into, but I find it's useful to work with the same $_FILES, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:
// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );
// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
data.append(fileInputName+'['+i+']', file);
});
(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)
That code does two things.
Retrieves the input name attribute automatically, making the HTML more maintainable. Now, as long as form has the class putImages, everything else is taken care of automatically. That is, the input need not have any special name.
The array format that normal HTML submits is recreated by the JavaScript in the data.append line. Note the brackets.
With these changes, submitting with JavaScript now produces precisely the same $_FILES array as submitting with simple HTML.
I just built this function based on some info I read.
Use it like using .serialize(), instead just put .serializefiles();.
Working here in my tests.
//USAGE: $("#form").serializefiles();
(function($) {
$.fn.serializefiles = function() {
var obj = $(this);
/* ADD FILE TO PARAM AJAX */
var formData = new FormData();
$.each($(obj).find("input[type='file']"), function(i, tag) {
$.each($(tag)[0].files, function(i, file) {
formData.append(tag.name, file);
});
});
var params = $(obj).serializeArray();
$.each(params, function (i, val) {
formData.append(val.name, val.value);
});
return formData;
};
})(jQuery);
If your form is defined in your HTML, it is easier to pass the form into the constructor than it is to iterate and add images.
$('#my-form').submit( function(e) {
e.preventDefault();
var data = new FormData(this); // <-- 'this' is your form element
$.ajax({
url: '/my_URL/',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
...
Devin Venable's answer was close to what I wanted, but I wanted one that would work on multiple forms, and use the action already specified in the form so that each file would go to the right place.
I also wanted to use jQuery's on() method so I could avoid using .ready().
That got me to this:
(replace formSelector with your jQuery selector)
$(document).on('submit', formSelecter, function( e ) {
e.preventDefault();
$.ajax( {
url: $(this).attr('action'),
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
}).done(function( data ) {
//do stuff with the data you got back.
});
});
If the file input name indicates an array and flags multiple, and you parse the entire form with FormData, it is not necessary to iteratively append() the input files. FormData will automatically handle multiple files.
$('#submit_1').on('click', function() {
let data = new FormData($("#my_form")[0]);
$.ajax({
url: '/path/to/php_file',
type: 'POST',
data: data,
processData: false,
contentType: false,
success: function(r) {
console.log('success', r);
},
error: function(r) {
console.log('error', r);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my_form">
<input type="file" name="multi_img_file[]" id="multi_img_file" accept=".gif,.jpg,.jpeg,.png,.svg" multiple="multiple" />
<button type="button" name="submit_1" id="submit_1">Not type='submit'</button>
</form>
Note that a regular button type="button" is used, not type="submit". This shows there is no dependency on using submit to get this functionality.
The resulting $_FILES entry is like this in Chrome dev tools:
multi_img_file:
error: (2) [0, 0]
name: (2) ["pic1.jpg", "pic2.jpg"]
size: (2) [1978036, 2446180]
tmp_name: (2) ["/tmp/phphnrdPz", "/tmp/phpBrGSZN"]
type: (2) ["image/jpeg", "image/jpeg"]
Note: There are cases where some images will upload just fine when uploaded as a single file, but they will fail when uploaded in a set of multiple files. The symptom is that PHP reports empty $_POST and $_FILES without AJAX throwing any errors. Issue occurs with Chrome 75.0.3770.100 and PHP 7.0. Only seems to happen with 1 out of several dozen images in my test set.
Nowadays you don't even need jQuery:) fetch API support table
let result = fetch('url', {method: 'POST', body: new FormData(document.querySelector("#form"))})
The FormData class does work, however in iOS Safari (on the iPhone at least) I wasn't able to use Raphael Schweikert's solution as is.
Mozilla Dev has a nice page on manipulating FormData objects.
So, add an empty form somewhere in your page, specifying the enctype:
<form enctype="multipart/form-data" method="post" name="fileinfo" id="fileinfo"></form>
Then, create FormData object as:
var data = new FormData($("#fileinfo"));
and proceed as in Raphael's code.
One gotcha I ran into today I think is worth pointing out related to this problem: if the url for the ajax call is redirected then the header for content-type: 'multipart/form-data' can be lost.
For example, I was posting to http://server.com/context?param=x
In the network tab of Chrome I saw the correct multipart header for this request but then a 302 redirect to http://server.com/context/?param=x (note the slash after context)
During the redirect the multipart header was lost. Ensure requests are not being redirected if these solutions are not working for you.
Older versions of IE do not support FormData ( Full browser support list for FormData is here: https://developer.mozilla.org/en-US/docs/Web/API/FormData).
Either you can use a jquery plugin (For ex, http://malsup.com/jquery/form/#code-samples ) or, you can use IFrame based solution to post multipart form data through ajax: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
All the solutions above are looks good and elegant, but the FormData() object does not expect any parameter, but use append() after instantiate it, like what one wrote above:
formData.append(val.name, val.value);
get form object by jquery-> $("#id")[0]
data = new FormData($("#id")[0]);
ok,data is your want
I have a form, inside which I want to have a "virtual form", which handles file attachments. I have a File-input and a button to send the file.
The problem is that my PHP backed gets only POST and that with structure:
"file"; filename="xxx.jpg"
Content-type: image/jpeg
.
.
.
where the dots represent the binary data from the file.
From what I have read it should be $_FILES and $_POST variables but I don't get them.
Here are the relevant codelines in HTML and in Javascript:
<input type="file" id="file-to-append" name="file-attachment">
<input type="button" onClick="append_file()" value="Add file">
function append_file() {
var formData = new FormData();
console.log(jQuery('#file-to-append'));
formData.append('file', jQuery(":file")[0].files[0]);
jQuery.ajax({
url : 'file_upload.php',
type : 'POST',
data : formData,
processData: false,
success : function(data) {
console.log(data);
alert("Added");
}
});
}
Could somebody spot or know where the problem lies?
The data is passing properly so there is no problem with your Ajax call.
You get the file object in PHP using the super global $_FILES.
In your case, you would use it like:
$file = $_FILES['file'];
echo $file['name'];
echo $file['tmp_name'];
.
.
.
To take a look at the $_FILES array you could:
echo "<pre>";
print_r($_FILES);
echo "</pre>";
Things are getting stranger and stranger. I got it working, but only on IE 11 by setting contentType: 'multipart/form-data' With Chrome it doesn't work at all with that setting.
I have tried with contentType: false, but it doesn't work on either platform though it should be the right thing(TM) to do :/.
I have also added enctype-setting in the outer form, but I wonder how it could help, because I am not submitting (whole form) but only adding things "inside" the main form (that I handle myself). Apparently it didn't help either.
This shouldn't be a problem but for some reason I am stuck with this ajax implementation, though I have used file upload since long time ago (two figure number)...
hank
Use right encrypte in your form
<form id="data" enctype="multipart/form-data" method="post" >
<input type="submit" value="Add file">
</form>
use ajax submit
$("form#data").submit(function()
{var formData = new FormData($(this)[0]);
$.ajax({
url: "filename.php",
type: 'POST',
data: formData,
async: false,
success: function (data)
{
var jsonData = $.parseJSON(data);
var errFlag =jsonData.errorFlag;
var errMsg =jsonData.errorMessage;
if(errFlag == 1)
{
//successmessage;
}
else
{
//errormessage;
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
I've got a problem sending a file to a serverside PHP-script using jQuery's ajax-function.
It's possible to get the File-List with $('#fileinput').attr('files') but how is it possible to send this Data to the server? The resulting array ($_POST) on the serverside php-script is 0 (NULL) when using the file-input.
I know it is possible (though I didn't find any jQuery solutions until now, only Prototye code (http://webreflection.blogspot.com/2009/03/safari-4-multiple-upload-with-progress.html)).
This seems to be relatively new, so please do not mention file upload would be impossible via XHR/Ajax, because it's definitely working.
I need the functionality in Safari 5, FF and Chrome would be nice but are not essential.
My code for now is:
$.ajax({
url: 'php/upload.php',
data: $('#file').attr('files'),
cache: false,
contentType: 'multipart/form-data',
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Starting with Safari 5/Firefox 4, it’s easiest to use the FormData class:
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
So now you have a FormData object, ready to be sent along with the XMLHttpRequest.
jQuery.ajax({
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
});
It’s imperative that you set the contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it.
Also, you must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
You may now retrieve the file in PHP using:
$_FILES['file-0']
(There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)
Using the FormData emulation for older browsers
var opts = {
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
};
if(data.fake) {
// Make sure no text encoding stuff is done by xhr
opts.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); xhr.send = xhr.sendAsBinary; return xhr; }
opts.contentType = "multipart/form-data; boundary="+data.boundary;
opts.data = data.toString();
}
jQuery.ajax(opts);
Create FormData from an existing form
Instead of manually iterating the files, the FormData object can also be created with the contents of an existing form object:
var data = new FormData(jQuery('form')[0]);
Use a PHP native array instead of a counter
Just name your file elements the same and end the name in brackets:
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file[]', file);
});
$_FILES['file'] will then be an array containing the file upload fields for every file uploaded. I actually recommend this over my initial solution as it’s simpler to iterate over.
Look at my code, it does the job for me
$( '#formId' )
.submit( function( e ) {
$.ajax( {
url: 'FormSubmitUrl',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
} );
Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES, regardless of whether you use JavaScript to submit.
HTML form:
<form enctype="multipart/form-data" action="/test.php"
method="post" class="putImages">
<input name="media[]" type="file" multiple/>
<input class="button" type="submit" alt="Upload" value="Upload" />
</form>
PHP produces this $_FILES, when submitted without JavaScript:
Array
(
[media] => Array
(
[name] => Array
(
[0] => Galata_Tower.jpg
[1] => 518f.jpg
)
[type] => Array
(
[0] => image/jpeg
[1] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/phpIQaOYo
[1] => /tmp/phpJQaOYo
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 258004
[1] => 127884
)
)
)
If you do progressive enhancement, using Raphael's JS to submit the files...
var data = new FormData($('input[name^="media"]'));
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
data.append(i, file);
});
$.ajax({
type: ppiFormMethod,
data: data,
url: ppiFormActionURL,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
}
});
... this is what PHP's $_FILES array looks like, after using that JavaScript to submit:
Array
(
[0] => Array
(
[name] => Galata_Tower.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpAQaOYo
[error] => 0
[size] => 258004
)
[1] => Array
(
[name] => 518f.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpBQaOYo
[error] => 0
[size] => 127884
)
)
That's a nice array, and actually what some people transform $_FILES into, but I find it's useful to work with the same $_FILES, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:
// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );
// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
data.append(fileInputName+'['+i+']', file);
});
(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)
That code does two things.
Retrieves the input name attribute automatically, making the HTML more maintainable. Now, as long as form has the class putImages, everything else is taken care of automatically. That is, the input need not have any special name.
The array format that normal HTML submits is recreated by the JavaScript in the data.append line. Note the brackets.
With these changes, submitting with JavaScript now produces precisely the same $_FILES array as submitting with simple HTML.
I just built this function based on some info I read.
Use it like using .serialize(), instead just put .serializefiles();.
Working here in my tests.
//USAGE: $("#form").serializefiles();
(function($) {
$.fn.serializefiles = function() {
var obj = $(this);
/* ADD FILE TO PARAM AJAX */
var formData = new FormData();
$.each($(obj).find("input[type='file']"), function(i, tag) {
$.each($(tag)[0].files, function(i, file) {
formData.append(tag.name, file);
});
});
var params = $(obj).serializeArray();
$.each(params, function (i, val) {
formData.append(val.name, val.value);
});
return formData;
};
})(jQuery);
If your form is defined in your HTML, it is easier to pass the form into the constructor than it is to iterate and add images.
$('#my-form').submit( function(e) {
e.preventDefault();
var data = new FormData(this); // <-- 'this' is your form element
$.ajax({
url: '/my_URL/',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
...
Devin Venable's answer was close to what I wanted, but I wanted one that would work on multiple forms, and use the action already specified in the form so that each file would go to the right place.
I also wanted to use jQuery's on() method so I could avoid using .ready().
That got me to this:
(replace formSelector with your jQuery selector)
$(document).on('submit', formSelecter, function( e ) {
e.preventDefault();
$.ajax( {
url: $(this).attr('action'),
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
}).done(function( data ) {
//do stuff with the data you got back.
});
});
If the file input name indicates an array and flags multiple, and you parse the entire form with FormData, it is not necessary to iteratively append() the input files. FormData will automatically handle multiple files.
$('#submit_1').on('click', function() {
let data = new FormData($("#my_form")[0]);
$.ajax({
url: '/path/to/php_file',
type: 'POST',
data: data,
processData: false,
contentType: false,
success: function(r) {
console.log('success', r);
},
error: function(r) {
console.log('error', r);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my_form">
<input type="file" name="multi_img_file[]" id="multi_img_file" accept=".gif,.jpg,.jpeg,.png,.svg" multiple="multiple" />
<button type="button" name="submit_1" id="submit_1">Not type='submit'</button>
</form>
Note that a regular button type="button" is used, not type="submit". This shows there is no dependency on using submit to get this functionality.
The resulting $_FILES entry is like this in Chrome dev tools:
multi_img_file:
error: (2) [0, 0]
name: (2) ["pic1.jpg", "pic2.jpg"]
size: (2) [1978036, 2446180]
tmp_name: (2) ["/tmp/phphnrdPz", "/tmp/phpBrGSZN"]
type: (2) ["image/jpeg", "image/jpeg"]
Note: There are cases where some images will upload just fine when uploaded as a single file, but they will fail when uploaded in a set of multiple files. The symptom is that PHP reports empty $_POST and $_FILES without AJAX throwing any errors. Issue occurs with Chrome 75.0.3770.100 and PHP 7.0. Only seems to happen with 1 out of several dozen images in my test set.
Nowadays you don't even need jQuery:) fetch API support table
let result = fetch('url', {method: 'POST', body: new FormData(document.querySelector("#form"))})
The FormData class does work, however in iOS Safari (on the iPhone at least) I wasn't able to use Raphael Schweikert's solution as is.
Mozilla Dev has a nice page on manipulating FormData objects.
So, add an empty form somewhere in your page, specifying the enctype:
<form enctype="multipart/form-data" method="post" name="fileinfo" id="fileinfo"></form>
Then, create FormData object as:
var data = new FormData($("#fileinfo"));
and proceed as in Raphael's code.
One gotcha I ran into today I think is worth pointing out related to this problem: if the url for the ajax call is redirected then the header for content-type: 'multipart/form-data' can be lost.
For example, I was posting to http://server.com/context?param=x
In the network tab of Chrome I saw the correct multipart header for this request but then a 302 redirect to http://server.com/context/?param=x (note the slash after context)
During the redirect the multipart header was lost. Ensure requests are not being redirected if these solutions are not working for you.
Older versions of IE do not support FormData ( Full browser support list for FormData is here: https://developer.mozilla.org/en-US/docs/Web/API/FormData).
Either you can use a jquery plugin (For ex, http://malsup.com/jquery/form/#code-samples ) or, you can use IFrame based solution to post multipart form data through ajax: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
All the solutions above are looks good and elegant, but the FormData() object does not expect any parameter, but use append() after instantiate it, like what one wrote above:
formData.append(val.name, val.value);
get form object by jquery-> $("#id")[0]
data = new FormData($("#id")[0]);
ok,data is your want
Im trying to pass and return an array to and from a php script, I've tested the json_ecode portion and its working but I can't get the json_decode on the php side.
Javascript
scid_list = [];
$('.filter_on').each(function(){scid_list.push($(this).data("scid"));});
$.ajax({
type: "POST",
dataType: "json",
data: {scid_list:scid_list},
url: "/scripts/products_filter.php",
success: function(data){
alert(data.join('\n'));
}
});
PHP
<?php
$scid_list=(json_decode($_POST['scid_list'], true));
echo json_encode($scid_list);
exit();
?>
Ive also tried leaving out the true on decode
$scid_list=(json_decode($_POST['scid_list']);
and not decoding it at all
$scid_list=$_POST['scid_list'];
I'm not sure what I'm missing. I've tried playing around with serializing the data too but read I didn't have to if you specify the dataType as json, I tried using stripslashes
Any help is appreciated!
Cheers
I think the problem is that the data you're sending isn't json even though you're specifying it on the Ajax call. As it's only a 2-dimensional array you're getting, why don't you just use Array.join in your JS before doing the post:
var scids = scid_list.join(',');
That would turn it in to a comma separated string. e.g.
"id1,id2..."
You can simplify the Ajax call a bit too:
$.post('/scripts/products_filter.php', {scids: scids}, function(data) {
// process data response here
});
Then in your PHP file you can use explode() to turn it back in to an array:
$ids = explode(",",$_POST["scids"]);
foreach ($ids as $id) {
// Do something with the array of ids.
};
Hope that all makes sense.
Your dataType parameter specifies that you expect JSON data in response, but it does not mean you are sending data as JSON. In your case you are sending an array, therefor in PHP instead of:
$scid_list=(json_decode($_POST['scid_list'], true)); /* WRONG */
you should simply use:
$scid_list=$_POST['scid_list'];
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String The type of data that you're expecting back from the
server.
Alltogether, for given HTML:
<form action="work.php" method="post">
<p><input class="filter_on" data-scid="22" type="checkbox" /> Filter 22</p>
<p><input class="filter_on" data-scid="28" type="checkbox" /> Filter 28</p>
<p><input class="filter_on" data-scid="31" type="checkbox" /> Filter 31</p>
<p><input type="submit" value="Send" /></p>
</form>
and SCRIPT:
$(document).on('ready', function() {
$('form').on('submit', function(e) {
e.preventDefault();
scid_list = [];
$('.filter_on:checked').each(function(i){
scid_list.push( $(this).data("scid") );
});
$.ajax({
type: "POST",
dataType: "json",
data: {scid_list:scid_list},
url: "work.php",
success: function(data){
alert(data.join('\n'));
}
});
});
});
PHP part is:
$scid_list=$_POST['scid_list'];
echo json_encode($scid_list);
exit();
So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
$('#results').html(data);
}
});
and it works fine by printing my results.
My php file is echoing data that should be printed in my results div.
Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??
Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.
<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>
And you could use those values accessing PHPVariables.VariableName1 on the javascript.
You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.
the explode function is used like this
explode('§', $somestringofinfoyouwanttoturnintoanarray);
you can then echo the relevent data like so
echo data[0];
which in this case wiill echo the text peiceofdata.
write this type of code in ajax file
var data =array('name'=>'steve', date=>'18-3-2014');
echo jsonencode(data);
//ajax call in this manner
$.ajax({
type: 'POST',
data: pass data array,
url: ajaxfile url,
success: function(data) {
var data = $.parseJSON(data);
$('#name').html(data.name);
$('#date').html(data.date);
}
});
Use json format, and in this json add your data variables :
PHP :
$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);
echo json_encode($arr);
Javascript :
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
data = JSON && JSON.parse(data) || $.parseJSON(data);
$('#results1').html(data.var1);
$('#results2').html(data.var2);
}
});