Here's my ajax code which I am using to post form data with FormData object. Here I am trying to post form data with image upload to controller.
var data1= new FormData();
data1.append("doc_photo", $('#file-doc-photo')[0].files[0]);
data1.append("name", $('#txt-doc-name').val());
data1.append("email", $('#txt-doc-emailid').val());
data1.append("phone", $('#txt-doc-phno').val());
data1.append("country ", $('#ddl-doc-country').val());
$.ajax({
type: "POST",
url: baseUrl + "doctor/ctr_doctor/update_doctor",
data: data1,
cache: false,
dataType: "json",
contentType: false,
processData: false,
success: function (res)
{
alert("Hello");
}
});
Console Output:
------WebKitFormBoundaryoLvd2A1IOU3cxAPp
Content-Disposition:_form-data;_name Disallowed Key Characters.
I have modified Codeigniters core Input class to find out the error.
function _clean_input_keys($str)
{
if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
{
//$str will append post var key in error message
exit($str.' Disallowed Key Characters.');
}
// Clean UTF-8 if supported
if (UTF8_ENABLED === TRUE)
{
$str = $this->uni->clean_string($str);
}
return $str;
}
I have enabled XSS filter in config.
I know it's posting form key incorrectly but why that is what I want to know.
Related
I'm trying to send arrays as post variables in an Ajax call using formData. For some reason they are getting converted to strings when I look in the console. I can't update the functions accepting the data to accept strings, they must accept arrays. I was reading about using the serialize function but then I'm also left with strings...so I'm not sure how to do this. Here is the code I have so far:
function submitSearch(method) {
if (method==='ajax_getPrograms') {
fields = ['pkProgramID','fldName','fldOrganization','fldProgramStartDate','fldProgramEndDate'];
}
if (method==='ajax_getPlots') {
fields = ['id','lat','long','plotSampleYear'];
}
if (method==='ajax_getTrees') {
fields = ['id','species','DBH','treeStatus','treeSampleYear'];
}
var posturl = baseURL + "data/"+method;
var formData = new FormData();
formData.append('fields',fields);
$.ajax({
url: posturl,
cache: false,
data: formData,
method: 'POST',
mimeType: "multipart/form-data",
contentType: false,
processData: false,
type: 'POST',
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
},
success: function (data) {
console.log(data);
}
});
}
When I submit that I get an error that my function is receiving a string and not an array, and this is what I see in the network tab of the console:
Any help is appreciated, thank you!
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 have an AJAX request towards PHP, but when debugging the function success is returning empty spaces before the result. I can not identify the inconvenience.
I have already made requests before and I had not had this problem.
$('.eliminarve').click(function() {
var token = $(this).attr('id');
var datos = new FormData();
datos.append('eliminarVEntrevista', true);
datos.append('tokenVE', token);
$.ajax({
url: "../../views/ajax.php",
method: "POST",
data: datos,
processData: false,
contentType: false,
cache: false,
beforeSend: function() {
$("#loading").removeClass('d-none');
},
success: function(result, status, xhr) {
$("#loading").addClass('d-none');
console.log(result);
console.log(status);
console.log(xhr);
//alert(retorno);
}
});
});
PHP:
if (isset($_POST['eliminarVEntrevista']) and isset($_POST['tokenVE'])) {
echo "hello";
}
Answer:
Sounds like the editor you're using is adding /n or another new line hidden character to your output. Open the file in something like Notepad++ to check if there are any hidden (or special) characters in the file.
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)
}
})
}
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");
}
})