Forum Moderators: open

Message Too Old, No Replies

jQuery .ajax() - adding extra parameters

I'm manually adding values to data, there must be a better way

         

caribguy

9:47 pm on Nov 11, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



My app server's validation routine depends on the name/value pair of the submit button in order to process the request.

Below is what I'm doing now, and I think it's rather ugly. I'm also considering to add it as a hidden field, but can't believe there isn't a cleaner way...


<form id="registration_form" method="post" action="/register">
<input type="text" name="first_name" >
[..]
<input type="submit" name="add_member" value="Register" >
</form>


The jQuery snippet looks like this:


$("#registration_form").submit( function(e) {
e.preventDefault();
var my_context = '#form-content'
var default_data = '&add_member="Register"';
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: "html",
data : $("#registration_form").serialize() + default_data ,
context: $(my_context),
success: function(data) {
$(my_context, data).each( function () {
$(my_context).replaceWith($(this));
});
}
});
});

Fotiman

2:59 pm on Nov 12, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It looks like version 1.4.3 of jQuery added this format:

.submit( [ eventData ], handler(eventObject) )

So you could do something like this to pass along the id of the submit button:


$("#registration_form").submit( {btn: '#add_member'}, function(e) {
e.preventDefault();
alert($(e.data.btn).attr('id'));


So you could use that to get the name/value of the submit button. However, if you have multiple submit buttons, that wouldn't work (you wouldn't know which one was clicked). A possible alternatively might be to also attach a click listener to the submit buttons that simply records which button was clicked, and then access that data in your submit event handler.

caribguy

7:02 pm on Nov 12, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks! Attaching a listener seems like a good option.

If my validation script does not receive the button value, it generates a default form rather than validating the data. Not sure why the people who designed this could not have used post/get to determine which function to execute...