Jquery Ajax Synchronous Example - Jquery

How to set ajax synchronous request in jquery?

Snippet Code

Rate this page :
  [ 0 votes]

This simple jquery code allows to get synchronous data by specifying the async option to be false. Then, the ajax callback can set some data before your parent function proceeds. The jquery ajax synchronous code is given below.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $('#btn').click(function(e){ var name = $('#name').val(); var messages = getajaxname(name); for( var i=0; i<messages.length; ++i){ $('.container').append(messages[i] + " "); } }); }); function getajaxname(name){ var messages = []; messages.push("Hello " + name); $.ajax({ url: 'ajax-demo.php', type: 'post', data: {name:'hscripts'}, async: false, success: function(data){ messages.push(data); } }); return messages; } </script> <input type="text" id="name" name="name"/> <input type='button' value='Synchronous Demo' id='btn'> <div class="container"></div> ajax-demo.php: <?php $username = $_POST["name"]; if(isset($username)) { echo $username; } ?>


Ask Questions

Ask Question