I am trying to provide a call back function for an ajax call, where the function name is saved under the "data-apply" attribute of a form.
jQuery(function($) {
$('form[data-async]').on('submit', function(event) {
var $form = $(this);
var $target = $($form.attr('data-target'));
var apply = $form.attr('data-apply');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function(data, status) {
var callBackFunc = new Function(apply);
callBackFunc.call();
}
});
event.preventDefault();
});
});
function addBubble(){
alert('a');
}
The form:
<form id="111" class="form-horizontal " data-async data-target="#rating-modal" data-apply="addBubble();" action="/some/action/performed" method="POST">
I want to avoid using eval()
in this case, since eval()
might introduce security and performance issues. Not sure Function()
is a safer method or there is a completely different way to handle this.
So is there anyway to pass in a function callback in order to handle difference situations?
The original code was borrowed from: https://gist.github.com/havvg/3226804
Since the function is globally defined, you can call it through the window
object.
window["functionName"].call();
Remove the parentheses from addBubble
<form id="111" class="form-horizontal " data-async data-target="#rating-modal" data-apply="addBubble" action="/some/action/performed" method="POST">
Javascript
jQuery(function($) {
$('form[data-async]').on('submit', function(event) {
var $form = $(this);
var $target = $($form.attr('data-target'));
var apply = $form.attr('data-apply');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function(data, status) {
if(typeof window[apply] == "function")
window[apply].call(); //window[apply](); or window[apply].apply(); will work too
}
});
event.preventDefault();
});
});
function addBubble(){
alert('a');
}
If the function is defined globally (i.e. on the window
object) you could use window[$form.attr('data-apply')]()
to call the callback. Note that you would have to remove the ()
in data-apply
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With