I tried to do this for working with a part of values from a html-form.
var formData = new FormData();
formData.append('file', $('#FORM_ADD_LANG_FILE')[0].files[0]);
formData.append('add_lang_code', $('#FORM_ADD_LANG_CODE').val());
formData.append('job', jobid);
var post_setting = new Array(false,false);
But in my console it is showing the following error and I don't know why it is
"TypeError: 'append' called on an object that does not implement interface FormData."
I generate the ajax-call by this function
function getAJAXcall(processData, contentType, formData, callback) {
var returnValue = {
url: '".$global['serverurl']."module/".$m['ID']."/code/cms_data.php',
type: 'POST',
data: formData,
success: callback
};
if (processData === **false**) returnValue.processData = processData;
if (contentType === **false**) returnValue.contentType = contentType;
}
And call them up in this way
$.ajax(getAJAXcall(post_setting[0], post_setting[1], formData, function(result)
{ ...my callback functions... }
Also i try to change the post_setting = new Array(false,false); to true, true but the result was the same
You use the right method call for this, so presumably there's something else wrong.
Could FormData be overwritten by some other library (perhaps a polyfill), that knows nothing of .append()? Check the console of your browser for FormData and see, if you can spot anything fishy there.
You use the result in a jQuery AJAX call, true? Then this answer applies to you. In a nutshell, add
processData: false,
to your AJAX parameters.
Related
I have created a common Javascript file for all my ajax calls. I am trying to use this as a common way to keep track of all ajax calls. Below is the code for the same.
function doAjax(doAjax_params) {
var url = doAjax_params['url'];
var requestType = doAjax_params['requestType'];
var contentType = doAjax_params['contentType'];
var dataType = doAjax_params['dataType'];
var data = doAjax_params['data'];
var beforeSendCallbackFunction = doAjax_params['beforeSendCallbackFunction'];
var successCallbackFunction = doAjax_params['successCallbackFunction'];
var completeCallbackFunction = doAjax_params['completeCallbackFunction'];
var errorCallBackFunction = doAjax_params['errorCallBackFunction'];
//Make the ajax call
$.ajax({
url: getBaseURL() + url,
crossDomain: true,
type: requestType,
contentType: contentType,
dataType: dataType,
data: data,
success: function (data, textStatus, jqXHR) {
console.log(typeof successCallbackFunction);
debugger
//if (typeof successCallbackFunction === "function") {
successCallbackFunction(data);
//}
},
error: function (jqXHR, textStatus, errorThrown) {
if (typeof errorCallBackFunction === "function") {
errorCallBackFunction(errorThrown);
}
}
});
}
This code takes a list of parameters and creates an ajax request based on the parameteres. This code is saved in a file APIHandler.js.
I am trying to call this function from multiple files. An example call is below.
function RedirectToDashboard() {
var params = $.extend({}, doAjax_params_default);
params['url'] = `profile/5`;
params['successCallbackFunction'] = `testsuccess`
doAjax(params);
}
function testsuccess() {
alert("success");
}
When I run this function, I am able to make the call successfully. The only issue comes with the reference to callback function. console.log(typeof successCallbackFunction); returns string instead of function.
I thought maybe order of JS made a difference. I am loading APIHandler.js and then the page specific js. And this ajax call happens at button click, so both JS files are loaded before the ajax call is made.
Other than that, I think maybe I am sending the parameters wrong. That might be causing JS to consider function name as string. But I checked most of the google suggestions on how to pass function, and it seems it needs just the name.
Is there anything else that I might be missing here?
Damn it. I just figured out why it was causing the error. I used quotes when assigning the callback function. Right after posting the question, I realised what was wrong.
params['successCallbackFunction'] = 'testsuccess'
is supposed to be changed to
params['successCallbackFunction'] = testsuccess
My goal is to pass a file to my backend which runs on laravel. The file is drag and dropped on the web page and not my input file. I went through the previous issues on stack overflow and fixed my code accordingly but still the issue exists.
Here is my javascript code that uses ajax to pass the file
$("html").on("drop", function (e) {
e.preventDefault();
e.stopPropagation();
var dt = e.dataTransfer || (e.originalEvent && e.originalEvent.dataTransfer);
var files = e.target.files || (dt && dt.files);
if (files) {
for (var i = 0; i < e.originalEvent.dataTransfer.files.length; i++) {
var file_ext = e.originalEvent.dataTransfer.files[i].name.split('.').pop();
console.log(file_ext);
if ((file_ext == 'pdf') || (file_ext == 'docx') || (file_ext == 'txt')) {
console.log('right file');
var resume = e.originalEvent.dataTransfer.files[i].value;
var form_data = new FormData();
form_data.append("resume", resume);
var resume_val = e.originalEvent.dataTransfer.files[i].name;
console.log(form_data);
var token = $('#token').val()
var hello = "hello";
$.ajax({
url: '/resume_upload',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: ({
resume: form_data,
wish: "Naveen its working"
}),
success: function (data) {
console.log(data.msg);
alert(data.msg);
},
error: function (xhr, status, error) {
console.log(error);
alert(error)
}
});
} else {
console.log('wrong file');
}
}
} else {
console.log('file not recieved');
}
});
Here is where i get the file
var resume = e.originalEvent.dataTransfer.files[i].value;
var form_data = new FormData();
form_data.append("resume",resume);
But when i console.log(form_data) it logged FormData{} just empty form data. So obviously i pass nothing with my ajax function. Am i doing anything wrong in getting the file ? I don't have an idea how to go about this.
Maybe I misunderstood what do you want but I think you should do stg like this:
var form_data = new FormData();
form_data.append('resume_file_name', e.originalEvent.dataTransfer.files[i].value);
form_data.append('resume_file', e.originalEvent.dataTransfer.files[i]);
form_data.append('wish', "Naveen its working");
if u want to upload the file, not just some file info
and with FormData, you can pass all the data you want, so just pass this to $.ajax data parameter:
data: form_data,
and there is something else, may this was the original problem:
when jQuery handles the parameters it also tries to convert it, but this causes problems, when pass a FormData type to data attribute, so you should also add these parameters to the $.ajax input object:
processData: false,
contentType: false
parameters.
Sorry for my bad english!
I have a function:
reportAdminActions.reportMemberList(project, function(data) {
console.log(data);
});
This function is called by another ajax operation like these:
reportMemberList: function(projectId, callback) {
var projectDetail = new Object();
projectDetail.projectId = projectId;
var pluginArrayProject = new Array();
pluginArrayProject.push(projectDetail);
$.ajax({
url : ConfigCom.serverUrl + 'projectreportonmember',
dataType: "jsonp",
type: "POST",
data: JSON.stringify(pluginArrayProject)
}).always(function(data) {
callback(data.responseText);
});
}
I need return value to function defined area after ajax operation. But here I got a error
Uncaught TypeError: callback is not a function
Check the rest of your code for calls to reportMemberList and make sure you always call it with the callback as a parameter. If you omit the callback parameter anywhere (e.g. call reportMemberList with just the projectId parameter), the code above would parse correctly the other calls to the function with the callback would produce the error. (This was the solution for me.)
guessing, but try to change your "jsonp" to "json". If you don't make cross-origin requests there, it should work
reportMemberList: function(projectId, callback) {
var projectDetail = new Object();
projectDetail.projectId = projectId;
var pluginArrayProject = new Array();
pluginArrayProject.push(projectDetail);
$.ajax({
url : ConfigCom.serverUrl + 'projectreportonmember',
dataType: "json",
type: "POST",
data: JSON.stringify(pluginArrayProject)
}).always(function(data) {
callback(data.responseText);
});
}
var values = $('#form_field').serialize();
dataS = "val="+values;
$.ajax({
type: "POST",
url: URL,
data: dataS,
cache: false,
dataType: 'json',
success: function(response)
{ },
});
But the form has an (<input type="file"> field) how do I pass the file into the form using this ajax serialization method. When I print $_FILES doesn't getting any output.
You can't past the $_FILES variable when using ajax. I can assure you that. Thanks.
Ajax does not support file uploads, you should use iframe instead.
you can check further detail here
Posting via Ajax file upload isn't straight forward. First, it isn't directly doable using XHR1.
There are two main ways to do the uploads, using a frame and using the XHR2 spec and the FormData object. This is the method I would recommend.
The easiest way to do this is then to perform two uploads. I'm going to borrow some code here, from GitHub user optikalefx to show you how to do it using jQuery:
// Ajax File upload with jQuery and XHR2
// Sean Clark http://square-bracket.com
// xhr2 file upload
// data is optional
$.fn.upload = function(remote,data,successFn,progressFn) {
// if we dont have post data, move it along
if(typeof data != "object") {
progressFn = successFn;
successFn = data;
}
return this.each(function() {
if($(this)[0].files[0]) {
var formData = new FormData();
formData.append($(this).attr("name"), $(this)[0].files[0]);
// if we have post data too
if(typeof data == "object") {
for(var i in data) {
formData.append(i,data[i]);
}
}
// do the ajax request
$.ajax({
url: remote,
type: 'POST',
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload && progressFn){
myXhr.upload.addEventListener('progress',function(prog) {
var value = ~~((prog.loaded / prog.total) * 100);
// if we passed a progress function
if(progressFn && typeof progressFn == "function") {
progressFn(prog,value);
// if we passed a progress element
} else if (progressFn) {
$(progressFn).val(value);
}
}, false);
}
return myXhr;
},
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false,
complete : function(res) {
var json;
try {
json = JSON.parse(res.responseText);
} catch(e) {
json = res.responseText;
}
if(successFn) successFn(json);
}
});
}
});
};
I should also note that browser support for this is a little more limited, despite XHR2 being around for 2 years now: https://developer.mozilla.org/en-US/docs/Web/API/FormData contains more information as well as a Browser compatibility chart.
As IE does not support cross domain issues, we have to use get or post method by using xdr, my problem is, I don't know how to pass data while using get method with xdr.
Code snippet for get method using jquery ajax is like -
$.ajax({
type: 'GET',
cache: false,
url: site_url,
data: params,
success: onsuccess,
error:onError
});
but suppose if I write this code for xdr it will be like -
var xdr = new XDomainRequest();
xdr.CacheControl = "no-cache";
xdr.open("get", site_url);
xdr.onload = function () {
var data = $.parseJSON(xdr.responseText);
onsuccess(data);
}
xdr.onerror = function() {alert('err');};
xdr.send();
Now in this, I do not know where to pass data!!!
Please help me out to solve this problem.
It all happens in the ".open" method.
Lets say you want to pass some JSON or an object to the request.
Do it like so...
var my_request_data = {
"whatever" : "whatever",
"again" : "whatever again",
"you get" : "the point..."
};
my_request_data = $.param(my_request_data);
xdr.open("get", "http://url.com/to/get/or/post/too/" + my_request_data);
jQuery turns the JSON object into URL friendly params and then it is sent to the server.
That is how you pass data!