jquery - Javascript sorting out nested functions -
so have script bingo game. i'm having problem running 1 of functions inside function. idea have checkbingo() function defined outside of .click() function. there's ajax @ work, i'm not sure if that's coming play here too. looks like:
$(document).ready(function(){ function checkbingo() { $.ajax({ url: '/check-bingo', type: 'get', success: function(data){ return data; } }): } $('#div').click(function() { // stuff gets done here $.ajax({ url: '/tile', type: 'get', success: function(data){ // stuff data, needs check if there's bingo. var isbingo = checkbingo(); if (isbingo == 'something') { // displays specific on page. } else { // displays other things on page. } } }): }); where i'm getting hung up, isbingo never getting assigned returned info. thought might have been because query wasn't running fast enough, i've tried sticking variable in loop until got assigned , console told me checkbingo() inside .click function wasn't defined. i'm not sure if it's stupid syntax error on part or if i'm doing isn't possible.
can verify indeed possible , i've got scour syntax error?
because line:
var isbingo = checkbingo(); ...is calling function (checkbingo) makes asynchronous call , not return anything, isbingo undefined.
one way approach pass callback function checkbingo since javascript allows functions passed around data, , function called jquery when data obtained server:
function checkbingo(callback) { $.ajax({ url: '/check-bingo', type: 'get', success: function(data){ callback(data); } // or do: // success: callback, }); } // .... success: function(data){ checkbingo(function (isbingo) { if (isbingo == 'something') { // displays specific on page. } else { // displays other things on page. } }); another approach, would allow continue using synchronous style (i.e., checkbingo return , use it) though code not executed synchronously taking advantage of fact later versions of jquery's ajax api return promise object allows style of coding:
$(document).ready(function(){ function checkbingo() { return $.ajax({ url: '/check-bingo.txt', type: 'get' }); } $('#div').click(function() { // stuff gets done here $.ajax({ url: '/tile.txt', type: 'get', success: function(data){ var checkingbingo = checkbingo(); checkingbingo.done(function (isbingo) { if (isbingo == 'something') { alert('a'); // displays specific on page. } else { alert('b'); // displays other things on page. } }); } }); }); }); besides need convert couple of colons semi-colons, , add jquery $ in front of "#div" code, 2 other aspects note:
- i added ".txt" extension ajax calls in case extension merely hidden on system.
- the code
$('#div')presumes there element on page id set "div". if wantdivelements clickable, need$('div').
Comments
Post a Comment