I have multiple forms generated dynamically.
I need to build the formData for multiple files as well as a couple of extra hidden inputs.
This is what I have tried so far:
$(document).on('click', '.upload-btn', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
method: "POST",
url: "upload.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
...
},
success: function(){
...
}
});
});
Oddly enough, this works somehow, and the files do get uploaded to the server, I can perform all sorts of operations on the temp files but...
the files are never a part of the $_POST array if I var_dump $_POST the files are not in there.
Is there a better way to build the formData? am I missing something on the php side when I'm testing for isset($_POST['file[]'])
Any help is greatly appreciated.
Use php's files array. print_r($_FILES);
Doing the above print, you'll be able to access every file sent from your form. This includes keys, tmp_name etc
Related
I'm having a problem trying to implement an AJAX request into a pre-existing website that I didn't create.
I have no problems sending the data to PHP as a GET request, however POST requests and trying to access $_FILES is returning null.
Here is the AJAX:
var someData = 'test';
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
data: ({someData}),
success: function(data) {
console.log(data);
}
});
PHP:
<?php echo json_encode($_POST['someData']); ?>
I believe the cause of the issue might lie within the htaccess file or be related to some other redirect that is in place on the site. This website was built by a past staff member at the company, and I've had this same problem using AJAX POST with several other sites built by them.
As changing from POST to GET works fine I don't think there is any problem with my very simple code.
Is there some way I can test if the data is going missing due to a redirect, or could there be some other cause?
First check the browser dev tools ctr+shift+J and see if there is a redirect. If not then
You need to set your datatype to json and depending on what version of JQUERY you are using you might have to use "type" instead of "method" if your JQUERY version < 1.9.0
var someData = 'test';
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "json",
data: ({someData}),
success: function(data) {
console.log(data);
}
});
PHP code:
header("Content-Type: application/json", true);
If that doesnt work then make sure your URL is absolutely correct. No extra slashes or spaces.
I have managed to figure this out, there is a 302 redirect in place for all .php extetensions to a url without the extension. There was also an error in my code.
Changing the URL in the AJAX to "post-data" without the .php extension allows me to see $_POST in PHP.
My other problem with not being able to access files came down to the way I was trying to send FormData with AJAX.
My original code to do this was:
var someData = 'test';
var fData = new FormData();
fData.append("images", $("input[name='fileUpload']").prop("files")[0]);
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
contentType: false,
processData: false,
data: ({someData, fData}),
success: function(data) {
console.log(data);
}
});
The problem being that you can't send FormData and other variables at the same time. Instead I have to append my other data to the FormData:
var someData = 'test';
var fData = new FormData();
fData.append("images", $("input[name='fileUpload']").prop("files")[0]);
fData.append("someData", someData);
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
contentType: false,
processData: false,
data: fData,
success: function(data) {
console.log(data);
}
});
I have an ajax call, to upload multiple images from javascript. The code works well when I have a few images but as soon as I increase the files uploaded at the same time (ex: 530 files), the php does not receive anything. Any help to solve this issue please?
$("form").on("submit", function(e) {
e.preventDefault();
var formdata = new FormData(this);
formdata.append('regId', document.getElementById('register_id').value);
$.ajax({
url: 'uploadImages.php',
type: 'post',
data: formdata,
contentType: false,
processData: false,
success: function(response) {
document.getElementById("body").innerHTML = "<p>"+response+"</p>";
},
});
});
I tried to increase the max_upload_size and max_file_uploads from apache2 as this example:
https://connectwww.com/how-to-change-php-file-upload-size-limit-in-ubuntu/5087/
But still it does not work.
I'm trying to upload a file via Ajax.
var fd = new FormData();
fd.append('file', file);
var xhr = $.ajax({
url: 'https://www.mywebsite.com/it/file/upload/',
type: 'POST',
dataType: 'json',
data: fd,
cache: false,
contentType: "application/json; charset=utf-8"
processData: false,
success: function(result, message, xhr)
{
console.log(result);
}
});
For the moment, the upload PHP script simply displays file data
header('Content-Type: application/json');
echo json_encode($_FILES['file']);
die();
As stated here, I am forced to use contentType:"application/json; charset=utf-8" because contentType:false causes a 404 (Not Found) error.
Unfortunately, this solution avoids the 404 error, but the displayed file data is null.
You should use this. It is working for me.
$.ajax({
type: 'POST',
url: $(this).attr('action'), //url_to_php_script
data: new FormData(this),
contentType: false,
processData: false,
success: function (data) {
//do necessary cleanups on success
},
error: function (e) {
//do necessary cleanups on failue
}
});
You will be able to get uploaded image in PHP using $_FILES
It should be ok the way you're doing it, however...
If you set contentType to false, than you will force jquery not to set the content type for you. If it is not set, it will default to `application/x-www-form-urlencoded; charset=UTF-8'.
That means you are sending your data using an url encoded string.
You can't easily send a file in an url encoded string.
Most likely the method on the server side is set up to read the form parameters from the url. Therefor if you set `contentType' to false, the server won't recognise the url, resulting in a 404.
Try setting up the server method to accept post data, remove the url parameters and read the posted form from the $_POST and $_FILES variables.
If you can't figure it out, update the question with the servers' method so we can see how the method is set up.
Well the thing is there is already a edited form with a lot of fields but all the save and validate goes trough ajax.
They asked me now to put a file upload , i tough that just will be set a input and get it on back , but since all goes trough ajax i cant.
I don't want to change all the function and go trough a submit if it's not necessary.
I looked for some uploaders of file trough ajax but all of them are type drag and drop and i don't like them because y only need a simple file.
And the ones that i found that looked simple where in flash...
Is there any simple script that allows me to upload a simple file trough ajax without need of change the type of submitting the fields.
Thank's in advance mates ;)
//the js that saves all the inputs
function _edit_campaign(){
var data = formvalues_inspinia("body");
data.action=_action;
data.status=$("#smf_ior_status").val();
$.ajax({
url: "/save_changes",
dataType: "json",
data: data,
method:"POST",
success: function (response) {
if(!response.status){
toastr_error(response.desc);
$( "#submit_confirm" ).prop( "disabled", false );
$("#"+response.camp).focus();
}else{
toastr_success(response.desc);
}
}
});
}
client side
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
});
server side
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
You can achieve this in simpler way using "ajaxSubmit".
Include jquery.form.js on your page and submit your form.
$(form).ajaxSubmit({
url: url,
type: "POST",
success: function (response) {
// do what you need with response
});
It sends all form data including file on server then you can handle these data in regular manner.
I got the error:
request failed: URI too long (longer than 8190)
I've seen other posts on StackOverflow for this one. Those posts recommend:
Not changing Apache settings (agree)
Using post, not get
Not using jsonp with post
I'm using jQuery's AJAX to POST:
$.ajax({
url: "test.php",
dataType: "json",
data: paras,
type: "POST",
success: function(ret){callback(ret);}
});
It's my impression you can use json just not jsonp. Correct? If so, why might I still be getting the error?
You should try setting proccessData to false.
From the docs:
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
so to prevent the data being added to the url:
$.ajax({
url: "test.php",
dataType: "application/json",
data: paras,
type: "POST",
proccessData: false, // this is true by default
success: function(ret){callback(ret);}
});
Honestly, I thought this was automatic, but since your url is too long it's worth a shot.
I ran into this issue when using jQuery to submit large forms, and was able to solve it by adding this plugin.
For example, using the following code to submit the form after adding the plugin resolved the issue for me:
$(formSelectorHere).ajaxSubmit({
url: myURL,
type: 'post',
contentType: "multipart/form-data",
data: $(this).serialize(),
success: function(data) {
function(data) {
//success code here//
}
});
If you're not using this to submit a form, this may not be relevant to you and won't solve your problem, but that's the most common situation where this issue appears, so I figured it was worth mentioning. (The plugin should also be able to submit a form using JSON, but haven't personally tested it).