Put your code inside the function. You can call a function when you need it:
var sendData = function() { $.ajax({ url: "script.php", type: "POST", data: data, dataType: "json" }) .done(function( json ) { if (json.result === false) { showModal("login"); return; } else { $('#result').html(json.result); } }); };
When to call sendData() , the second time depends on how your login (showModal) works. Find a way to catch the "successful login" event.
You can pass sendData to the showModal function and call it there. Therefore, showModal does not need to know anything about data :
var sendData = function() { $.ajax({ url: "script.php", type: "POST", data: data, dataType: "json" }) .done(function( json ) { if (json.result === false) {
Then, where showModal is defined:
function showModal(dialog, loginCallback) { $('body').append('<form>...'); // Show Modal with form to login // With submit form, the user will be logged in $('#loginform').on('submit', function(event) { $.ajax({ url: "login.php", type: "POST", data: { 'username': username, 'password': password }, dataType: "json" }) .done(function( json ) { // User is now logged in // Now repeat first request loginCallback(); }); }); }
source share