I declared a function in a inline script at the beginning of my body tags. Then in an external script. On a form submit. it trigger an anonymous function that handle data from the form and submit a $.ajax method. The external script is called at the end of the file
The problem is that I assigned a function name in my form tag as a 'data-success="functionName"'. It does trigger the function in the external script. But the external scripts doesnt recognize the inline function called in the html file.
Here an exemple. https://jsfiddle.net/vsbmn8w1/?utm_source=website&utm_medium=embed&utm_campaign=vsbmn8w1
HTML
<script>
$(document).ready(function() {
// The Inline function that dont get called externally
function searchResult(data) {
alert()
}
});
</script>
<!-- Trigger On Submit -->
<form method="post" class="async-form" data-success="searchResult">
<button type="submit">submit</button>
</form>
EXTERNAL SCRIPT
$(document).ready(function() {
$(document).on("submit", "form.async-form", function(event) {
// Declare form in a variable
var $this = $(this);
// Prevent Page reloading
event.preventDefault();
// Collect Form parameters
var action = $this.prop('action');
var method = $this.prop('method');
var form = $this.serialize();
// Default request object
var request = {
url: action,
type: method,
data: form
};
// Adding parameter to the object if data exist
if (typeof $this.data('success') != 'undefined') {
request['success'] = $this.data('success');
}
if (typeof $this.data('error') != 'undefined') {
request['error'] = $this.data('error');
}
if (typeof $this.data('beforeSend') != 'undefined') {
request['beforeSend'] = $this.data('beforeSend');
}
if (typeof $this.data('complete') != 'undefined') {
request['complete'] = $this.data('complete');
}
// Finally make the ajax request
$.ajax(request);
})
});