Tag Archive for onClick Event

Variable scope in js and ajax function

Often, when we encounter a situation when the link has to be followed with some condition check in server, we could skip the form and use the simple a tag to navigate the link with javascript/ajax. You could simple use the ajax call to request the server file and then get the response and based on the response you could either follow the link or block it.

But in doing so, you may have to share the variable between javascript function and ajax function. This arises the variable scope issue in javascript. We have to use the scope operator to point the variable properly. In our case, we have defined the scope as var _this = this; . Now we could use this operator to access the js variable inside the ajax function.

The a tag will navigate the link by default so in order to block it we will use the onClick event. This event will fire and the link will be navigated if the response is true and our function returns either true or false based on the server response. And that’s that. Simple huh!! The code should be self explanatory. But just in case you need my help, you know where to find me else please drop a comment 🙂

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function checkA() {
	var _this = this;
	var check;

		type: 'POST',
		url: 'checkhere.php',
		async: false,
		success: function (response) {			
			if(response) {
				_this.check = true;
			}else {
				_this.check = false;
	return _this.check;
<a href="gohere.php" onclick="return checkA();">Follow Link with Check</a>