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.
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!
This is my code , When I click on submit , somehow the data is inserting but that echo data in back php form is not showing in this front ajax js code , please tell me if anything is wrong in my data
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
alert(data);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
ok this is my full js code
$(document).ready(function(){
$('form#off').submit(function(event){
event.preventDefault();
if($('#name').val()==''){
$('#nameid').text('Plase Select Customer Name ');
return false;
}
else{
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
//alert('data has been added');
error: (err)=>{console.warn(err)}
// location.href='gst_chargeoff.php';
alert(data);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
});
The ajax call is working fine. It is also getting response from the url. If there would be any server side error , It can be detected in the error: of the ajax parameter.
In your code it was written incorrectly, the same i have corrected in the below code, you will get the error in console if there will be any server side error. else the response will be returned properly.
Check the below code.
$(document).ready(function(){
$('form#off').submit(function(event){
event.preventDefault();
if($('#name').val()==''){
$('#nameid').text('Plase Select Customer Name ');
return false;
}
else{
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
//alert('data has been added');
// location.href='gst_chargeoff.php';
alert(data);
},
error: function(err){
console.log(err);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
});
You forgot to add the error attribute to your AJAX request. It's most likely throwing an error.
error: (err) => {
console.warn(err)
}
Wrap the entire $.ajax block inside a console.log($.ajax({...}));.
Then look into the console for the response codes for more info
Also you can use this to find more about the case:
error: function(err){
console.log(err);
}
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)
}
})
}
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.
I have the following code:
$.ajax({
type: "Post",
url: 'http://example.com/jambo',
contentType: "application/json",
data: String(' ' + $('InputTextBox').val()),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
The value in InputTextBox has leading 0's but when this is posted to the url the leading 0's are truncated.
When sending json to a server, you should use the built-in JSON.stringify method to create json rather than creating it manually.
$.ajax({
type: "Post",
url: 'http://example.com/jambo',
contentType: "application/json",
data: JSON.stringify($('InputTextBox').val()),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
This will result in sending "0005" instead of 0005, which when parsed, will be converted back into the string rather than a number which will lose the leading zeros.
Testing the code on this page;
$.ajax({
type: "Post",
url: '/test',
contentType: "application/json",
data: String(' 004'),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
obviously alerts the 404 page but in the net tab of Chrome and Firefox shows the data is sent correctly ' 004'.
Please re ask your question with the code on the server, as the issue is not client side.
As Kevin B noted ' 004' is a type numeric according to the JSON specification
so if you want the zeros and want to use a JSON library on the server sent the data as '" 004"' or use JSON.stringify(' 004').
Removing contentType: "application/json", in my ajax call fixed the issue for me
Reason:-
contentType: "application/json", will get the values first converted to numbers as it tries to parse your data to JSON. Removing this line from your ajax call will stop the parsing of data.
Note : The parsing will happen not only in your data you are POSTing, but also it will parse the queryStrings in your URL when you use GET method