I want to make an ajax call that sends both JSON and file data to my PHP backend. This is my ajax call currently:
$.ajax({
type: 'POST',
dataType: 'json',
data: jsonData,
url: 'xxx.php',
cache: false,
success: function(data) {
//removed for example
}
});
The data(jsonData) is a JSON array that also holds the input from a file select as well(I am assuming this is wrong due to the type mismatch). I tried using contentType: false, and processData: false, but when I try to access $_POST data in PHP there is nothing there. The data I am passing does not come from a form and there is quite a bit of it so I do not want to use FormData and append it to that object. I am hoping i will not have to make two ajax calls to accomplish this.
If you want to send data along with any file than you can use FormData object.
Send your jsonData as like that:
var jsonData = new FormData(document.getElementById("yourFormID"));
Than in PHP, you can check your data and file as:
<?php
print_r($_POST); // will return all data
print_r($_FILES); // will return your file
?>
Try Using formdata instead of normal serialized json
Here's an example:
var formData = new FormData();
formData.append("KEY", "VALUE");
formData.append("file", document.getElementById("fileinputID").files[0]);
then in your ajax
$.ajax({
type: 'POST',
url: "YOUR URL",
data: formData,
contentType: false,
processData: false,
dataType: 'json',
success: function (response) {
CallBack(response, ExtraData);
},
error: function () {
alert("Error Posting Data");
}
});
You can try like this also
You can visit this answer also
https://stackoverflow.com/a/35086265/2798643
HTML
<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />
JS
var fd = new FormData();
var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
fd.append("kay", "value"); //As the same way you can append more fields
for (var i = 0; i < files.length; i++) {
fd.append("UploadedImage" + i, files[i]);
}
$.ajax({
type: "POST",
url: 'Url',
contentType: false,
processData: false,
data: fd,
success: function (e) {
alert("success");
}
})
Related
I want to upload a file using jQuery/Ajax in my Wordpress plugin. The javascript to PHP call works. So the wiring etc. works. But as soon as I post the formData, necessary to post the files, I don't reach the PHP function any more.
The javascript,
var doesntWork = new FormData();
doesntWork.append('file', 'a name');
var withthisItWorks = 'text'
var data = {
'action': 'emfi_file_upload',
'data': doesntWork
}
$.ajax({
type: "POST",
url: ajax_object.ajaxurl,
data: data,
success: function(response) {
jQuery('#emfi-message').html(`<span style="color: green;">Respons: ${response}</span>`);
}
});
The PHP function just returns a string answer:
function emfi_file_upload_callback() {
echo 'Yes, in the callback';
wp_die();
}
When I put the plain text in my data object I get answer from the PHP function. When I put the formData in, there is no answer. I've tried a lot of examples on the internet, but it boils down to this every time. Adding contentType: false and processData: false, as was mentioned somewhere else, didn't help. What's wrong?
All fields that are being sent must be in the formdata object.
Additionally for FormData to work with jQuery.ajax, processData and contentType have to be set to false.
var doesWork = new FormData();
doesWork.append('file', someFile);
doesWork.append('action', 'emfi_file_upload');
$.ajax({
type: "POST",
url: ajax_object.ajaxurl,
data: doesWork,
contentType: false,
processData: false,
success: function(response) {
jQuery('#emfi-message').html(`<span style="color: green;">Respons: ${response}</span>`);
}
});
I'm trying to do a Ajax's loops requests for send files to an API but i don't not what I send at Ajax's data. When I do only file in upload I use the own formdata object and works very well. I tried use loop and each row send an individual file but it's doesn't works too:
Multiple files:
var form_data = new FormData();
for(i=0;i<3;i++){ // 3 length just for tests
form_data.append('file', $('#myfile').prop('files')[i]);
}
for (var value of form_data.values()) {
$.ajax({
url: 'URI',
data: value,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
alert("Success!")
},
error: function(e){
alert("Error")
}
});
}
I'm trying to send HTML form data using AJAX however I'm also trying to send other data along with the same AJAX POST call.
Is this possible?
$('#HTMLConForm').on('submit', function (e)
{
e.preventDefault();
$.ajax({
url: "***NewUserURL.com***",
type: "POST",
data:{
'otherinfo': otherinfo,
'form_data': new FormData(this),
},
processData: false,
contentType: false,
success: function (data)
{
alert('You Have Registered')
/*window.location = "index.html"; */
},
error: function (xhr, desc, err)
{
}
});
});
Any help with be appreciated!
Pass the FormData object itself to data, don't wrap it in a simple object.
Use the FormData object's append method to add additional data.
e.preventDefault();
const formdata = new FormData(this);
formdata.append("otherinfo", otherinfo);
$.ajax({
url: "***NewUserURL.com***",
type: "POST",
data: formdata,
I believe I am making a very basic mistake somewhere.
I have a Form I want to transmit to a PHP page. I also want to send a parameter with that information so I have created a basic 2D array:
$fd['api'] -> contaning the parameter as a string
$fd['body'] -> containing the form data
I am struggling to transmit this array "$fd" as a json string and believe I am using the javascript syntax incorrectly somewhere as I do not often use Javascript.
Any Help would be appreciated.
function admin_statistics_form_send(){
var fd = []
fd['api'] = "refresh_all"
fd['body'] = new FormData(document.getElementById("admin_statistics_form"))
var jsonstring = fd
console.log(jsonstring)
$.ajax({
async: true,
beforeSend: function(){
},
url: "admin_statistics_api.php",
type: "POST",
data: jsonstring,
dataType: "json",
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data)
},
error: function(data) {
console.log(data)
}
})
}
You only want to send the FormData object. To add other key/value pairs you append to that object:
function admin_statistics_form_send(){
var fd = new FormData($("#admin_statistics_form")[0]);
fd.append('api',"refresh_all");
$.ajax({
//async: true, // redundant since it is default and should never use `false`
beforeSend: function(){
},
url: "admin_statistics_api.php",
type: "POST",
data: fd,
dataType: "json",
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data)
},
error: function(data) {
console.log(data)
}
})
}
Say I have an array which contains a few images:
var images = [image1, image2, image3]
How do I send these images to a php file using AJAX in a single request?
The following code did not work:
$.ajax({
url: 'PHP/posts.php',
type: 'post',
data: {data: images},
success: function(data) {
alert(data);
location.reload();
}
});
My HTML:
<div id="newPostFile">
<label for="newPostFiles"><i class="fa fa-file-text-o" id="newPostFileIcon" aria-hidden="true"></i></label>
<input type="file" name="newPostFiles" id="newPostFiles">
</div>
Endgoal:
Whenever a file is selected, the file is added to the array and when the submit button is clicked, all the files are uploaded at once.
You have to send files as formData
var images = [image1, image2, image3]
var data = new FormData();
images.forEach(function(image, i) {
data.append('image_' + i, image);
});
$.ajax({
url: 'PHP/posts.php',
type: 'post',
data: data,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
location.reload();
}
});
But as you're reloading the page anyway, why use ajax at all ?
You can pass a JSON object to PHP, which would be the convenient solution here
var data ={'image1':image1,'image2':image2};
You can pass this object to the php code and then parse it:
Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'PHP/posts.php',
data : {result:JSON.stringify(data)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "image1 : ".$data["image1"];
Another option would be serializing the array before sending, or convert it into a comma separated string using array.join, then parse/split on the posts.php
array.join(",")
you can just use the list symbol after the input name [i]
for example:
let formData = new FormData();
let files = fileInput.prop('files');
for (let i = 0; i < TotalFiles; i++) {
formData.append('file['+i+']', files[i]);
}
Use FormData Object to send files using ajax.new FormData($('#your_form_id')[0]) automatically appends all form input in FormData object which we can be done by manually formData.append('file1',file1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
let formData = new FormData($('#your_form_id')[0]);
$.ajax({
url: 'PHP/posts.php',
type: 'POST',
data: formData,
dataType:'json',
processData: false,
contentType: false,
success: function(response) {
console.log(response);
location.reload();
},
error: function() {
console.log('fail');
}
});
</script>