JQuery, Ajax and PHP : Sending FormData AND String values - javascript

I'd like to send to a PHP page a FormData value and some String values.
Here's my code on the JS side:
$.ajax({
url: 'upload-pic.php',
type: 'post',
data: {
type : type,
id : id,
formData : formData
},
processData:false,
success: function(data, status) {
//stuff i'm doing with the data
}
});
And on the PHP side :
if(isset($_POST['type']) && isset($_POST['id'])){
//stuff i'm doing
}
Then, I get an error saying that type and id are not set. I'm guessing that this comes from the processData: false from my ajax call.
But without this, I get the inevitable Illegal Invocation, coming from trying to send the FormData.
Is there any way to send the FormData AND my String values on the same call ?
Thanks!

I assume you are using the FormData object, in that case you need to append the string values to the FormData object, and pass the object in as the data parameter in jQuery's $.ajax.
You can append data to the FormData object, with the method append.
This should work:
formData.append('type', type);
fromData.append('id', id);
$.ajax({
url: 'upload-pic.php',
type: 'post',
data: formData,
processData:false,
contentType: false,
success: function(data, status) {
//stuff i'm doing with the data
}
});

Related

Jquery ajax call wrong payload

I have some troubles whit jquery ajax call, infact I tried to perform a post call passing like data a string variable:
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: myVar,
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
If I inspect the http call I can see that the payload is:
'Hello': ""
I don't know how it is possible and how fix the problem.
jQuery, by default, will put a Content-Type: application/x-www-form-urlencoded header on data it sends via Ajax.
You, however, are passing a plain text string.
You need to either change the Content-Type to match the data you are sending or the data you are sending to match the Content-Type. (Or you could change both).
The important things are:
The data and content-type need to match
The server needs to be able to handle data in the format you are sending
So you might:
$.ajax({
type: 'POST',
url : 'https://...',
data: myVar,
contentType: 'text/plain'
// ...
})
or, since jQuery will encode objects as URL encoded data:
$.ajax({
type: 'POST',
url : 'https://...',
data: { myVar },
// ...
})
or, if you want multipart data:
const data = new FormData();
data.append('myVar', myVar);
$.ajax({
type: 'POST',
url : 'https://...',
data,
contentType: false // XHR will read the content-type from the FormData object (which it needs to do in order to determine the boundary paramater), putting 'false' here stops jQuery overriding it
// ...
})
or, for JSON
$.ajax({
type: 'POST',
url : 'https://...',
data: JSON.stringify(myVar), // This will be a JSON text representing a string
contentType: 'application/json'
// ...
})
i think you are passing payload in the wrong formate.
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: {
'name':myVar
},
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
On the server side you will get the value in the key 'name' you can fetch the value using 'name' key.

Posting data with jQuery in Wordpress succeeds, but fails with FormData

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

Ajax send array and Image in same request

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

Trouble Accessing Ajax POST variable on Codeigniter end

I'm using jquery to make ajax calls. Basically I don't know how to access the data I'm sending to the server with a post request. I don't know what the variable is called or... something. I don't know!
Ajax functions:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = JSON.stringify({
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
});
return ajax_client(base_url+'ajax_port/gather_records', json);
}
Codeigniter Function:
public function gather_records()
{
$data = json_decode($this->input->post('ids'));
log_message('debug', $data);//null
return json_encode($data);//null :(
}
I'm having no trouble receiving data back from the server here (and accessing with jQuery), my problem is that I can't get the data I'm sending to codeigniter. I'm developing on MAMP if that makes any difference.
I've tried other variable names like,
$this->input->post('data');
$this->input->post('json');
None seem to work.
Thanks very much for any help I can get!
You don't need to do JSON.stringify({..
just pass an object, and everything will be fine. I mean:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = {
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
};
return ajax_client(base_url+'ajax_port/gather_records', json);
}
One more thing. You don't need to json_decode it in your PHP side. Because default contentType in jQuery is 'application/x-www-form-urlencoded; charset=UTF-8'
Change line
$data = json_decode($this->input->post('ids'));
to
$data = $this->input->post('ids');
But if you really want to send JSON, you can add contentType
return $.ajax({
url: url,
type: 'POST',
data: json,
contentType: 'application/json',
dataType: 'json'
});
dataType you have set is "The type of data that you're expecting back from the server." (http://api.jquery.com/jquery.ajax/)

Send file by Ajax and FormData fail

I'm trying to send a file using Ajax in Jquery creating a FormData previously. This is my code:
var inputFileImage = document.getElementById('uploadImage');
var file = inputFileImage.files[0];
var data = new FormData();
data.append('archivo',file);
jQuery.ajax({
url: '/services/rpc.php',
type: 'post',
data: {functionName: 'saveProfileImage', data : data},
contentType:false,
processData:false,
})
.done(function(response) {
alert(response);
}.bind(this))
.fail(function(response) {
alert('Sorry, there was an unexpected error, please try again later.\n\nInformation about the error:\n'+response);
});
This ajax always goes to the fail function, and if I change the processData to true returns my another error saying Error: TypeError: 'append' called on an object that does not implement interface FormData.
Thanks for your help!
processData has to be off to send binary data. The FormData element is completely used as binary data, while data:{} needs to be processed. Additional parameters have to be appended to the formData in this case!
var data = new FormData();
data.append('archivo',file);
data.append('functionName','saveProfileImage');
jQuery.ajax({
url: '/services/rpc.php',
type: 'post',
data: data,
contentType:false,
processData:false,
});

Categories

Resources