0

Ajax return true or false from a function javascript

asynchronous javascript and xml

In this tutorial, we will creating a function javascript which contains ajax returning by ‘1’ or ‘0’ (true or false).

Oke, create a file index.php :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script>
function ajaxReturn(){

	formData= new FormData();
	formData.append('value', 'true');

	var jqXHR = $.ajax({
		type: 'POST',
		url: 'request.php',
		data: formData,
		processData: false,
		contentType: false,
		async: false,
	});

	// return 1 or 0
	return jqXHR.responseText;
}

function btn()
{

	if(ajaxReturn() == 1)
	{
		alert('true!');
	}
	else
	{
		alert('false!');
	}

}
</script>

<button onclick="btn()">Get return</button>

When button clicked, will be calling a function btn() and then running function ajaxReturn().
In ajaxReturn() will returning by ‘ jqXHR.responseText‘.

The script above, ajax will sending request to ‘request.php’.
So, we must creating request.php :

if($_POST['value'])
{
	$val = $_POST['value'];

	if($val == 'true')
	{
		echo '1';
	}
	else
	{
		echo '0';
	}
}

You can try demo :

DEMO

[related_post themes="text" id="387"]

Ambar Hasbiyatmoko

Hello, I’m web developer. Passionate about programming, networking and web server. @kaskus  @facebook

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.