I'm working on a project where I'm using a lot of ajax calls to make the the site interaction more elegant. The process I have been using is to have the link to the script that executes the appropriate action stored as the href in a link tag. I then use jquery to target that element and disable the default action and execute the ajax call.
The problem is that on occasion the $(document).ready() function doesn't properly execute or is delayed in executing before a user can click the links. This results in the page being opened via normal browser load.
I have implemented code that detects if the code is being executed via ajax or via the browser so all that happens is that a blank page is loaded. In some cases I can have it detect the execution type and respond differently but in other cases, if it's not executed by ajax then it causes problems.
Is there a way to ensure that the link's default action is disabled at all times regardless of the page's loading progress or is there a better approach than the one I'm taking?
You can run the code in the global scope, just place the JS code block after the DOM elements (links) you are working with. This way you aren't relying on an event handler to fire. Placing the code block just before the closing </body> tag is good place.
<a class="my-links" href="/path/to/server-side.***"></a>
<script>
function myFunc () {
$.ajax({
url : $(this).attr('href'),//use the href attribute for the link clicked as the URL for the AJAX request
type : 'get',
success : function (serverResponse) {
alert('Success');
},
error : function () {
alert('Error');
}
});
//in a jQuery event handler, returning false is the same as calling: event.preventDefault(); event.stopPropagation()
return false;
}
$('.my-links').bind('click', myFunc);
</script>
</body>
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