Post data in Ajax call arrays converted to strings? - javascript

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!

Related

Why AJAX success prefers empty spaces in result?

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.

How to send Form Data and other Data using AJAX

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,

Transmitting Form Data via Json

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

Jquery ajax FormData() posting incorrect key names

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.

How to use $.ajax() for input field text AND FILE upload? [duplicate]

This question already has answers here:
jQuery AJAX file upload PHP
(5 answers)
Closed 8 years ago.
This is my code
$.ajax({
type: 'post',
url: '../lib/upload.php',
data: new FormData( $("#niceidentifier") ),
processData: false,
contentType: false,
success: function (response) {
if(response == 'success') {
return true;
}
else {
alert(response);
console.log(response);
}
}
});
The HTML form is just basic HTML (enctype included and method post) but unfortunately NO data is passed. How can I upload a file AND pass the input data once?
It's not as simple to pass files and other data, such as text, together in the same POST request. The only way to achieve that is making multipart/form-data request.
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
I use ajaxForm to upload files asynchronously via ajax, it is much easier than trying to implement your own.
http://malsup.com/jquery/form/
For a cross browser solution I think it is better to use
$("#form_id").ajaxSubmit();
You can use FormData to pass the File. and processData,contentType set to false compulsory. because you are not going to process file in client side.
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append('myFile', value); //No I18N
});
$.ajax({
url: '/your-url',
type: 'POST',
data: data,
cache: false,
dataType: 'json', //No I18N
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
// do something
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
}
});
OR you can send file with data as following:
$( '#formId' )
.submit( function( e ) {
e.preventDefault();
$.ajax({
url: '/your-url',
type: 'POST',
data: new FormData( this ),
cache: false,
dataType: 'json', //No I18N
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
// do something
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
}
});
});

Categories

Resources