1

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. :)

asked Apr 19, 2017 at 9:26
2
  • Are you able to call this function submit_preset with that event binding($.proxy)? Commented Apr 19, 2017 at 9:37
  • yes, I tried to alert("test") in the function, and when I submit the form, the alert pops up Commented Apr 19, 2017 at 9:40

1 Answer 1

2

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

Working example

answered Apr 19, 2017 at 9:31
Sign up to request clarification or add additional context in comments.

4 Comments

hello, thanks for the answer, I did include processData and contentType, I didn't put it here to make it shorter. But the url parameter doesn't work, because I tried to alert it, plus my action goes on the same page as a GET method.
Is "create" the url you're trying to call?
Ah - in that case you need to swap the order of the parameters in the function. See my updated answer
so if I have 3 parameters like: $.proxy(submit_preset,this,url,method) I need to invert them in my function like: submit_preset(url, method, e) ?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.