I need to do some event bindings here and there to the same function. I'll try to simplify my code as much as possible.
This is my event binding:
$(".preset").on("submit",$.proxy(submit_preset,this,"create"));
This is the function which works if I do it as annonymous $(".preset").on("submit",function(){ etc }); :
function submit_preset(e, url){
e.preventDefault();
var _formdata=new FormData(($(e)[0].target)); //don't mind this weird $(e)[0].target
$.ajax({
url:url,
data:_formdata,
type:'post',
success:function(datapass){
console.log(datapass);
}
});
}
What am I doing wrong? The function parameters or the proxy parameters? or something else?
Post-answer: the function content may have missed something, but the problem was, which I find counter-intuitive, I had to swap the parameters. Check the jsfiddle of the answer and the comments too. :)
1 Answer 1
You're setting the scope of the submit_preset() function to the form by using $.proxy therefore you need to use this to reference that form element, not e, as that refers to the event that was raised.
To fix your code you need to provide this to the FormData() constructor, set contentType and processData to false as you're sending binary data and swap the order of the parameters - the data you append to the event comes first. Try this:
function submit_preset(url, e) {
e.preventDefault();
$.ajax({
url: url,
type: 'post',
data: new FormData(this),
contentType: false,
processData: false,
success: function(datapass) {
console.log(datapass);
}
});
}
4 Comments
"create" the url you're trying to call?$.proxy(submit_preset,this,url,method) I need to invert them in my function like: submit_preset(url, method, e) ?
submit_presetwith that event binding($.proxy)?