iwato Posted August 1, 2018 Share Posted August 1, 2018 GENERAL QUESTION: Can variables created outside of a function be used within a function without having to read them first as arguments of the function? If so, can a function created within a function use a variable created outside of both functions? CODE var dataString = 'search_input=' + search_letter_input; $.ajax({ type: "POST", url: './...', data: dataString, dataType: 'JSON', statusCode: { 404: function() { alert( "Page not found" ); }}, success: function(jsonData) {...} }); SPECIFIC QUESTION: I would like to use the value of the variable search_letter_input in the success function of the $.ajax( ) method. Is this possible? Roddy Link to comment Share on other sites More sharing options...
Ingolme Posted August 1, 2018 Share Posted August 1, 2018 I can't see where in your code it is declared, so I can't tell you if it is accessible. As long as the variable is declared outside of any other functions, it is accessible anywhere. Have you tried it? 1 Link to comment Share on other sites More sharing options...
iwato Posted August 1, 2018 Author Share Posted August 1, 2018 No, i have not. I thought I would check first, before I start writing. The variable is declared earlier in the routine. I will try it now. Thank you! Roddy Link to comment Share on other sites More sharing options...
JMRKER Posted August 3, 2018 Share Posted August 3, 2018 Regardless of native JS or JQuery, perhaps this would help with your understanding: <script> var globalVar = 'globalVar'; function parentFunc() { // no function parameters var parentVar = 'parentVar'; function childFunc() { // not function parameters var childVar = 'childVar'; alert('childFunc has access to:\n'+childVar+'\n'+parentVar+'\n'+globalVar); } childFunc(); alert('parentFunc has access to:\n'+parentVar+'\n'+globalVar); } alert('body has access to only:\n'+globalVar); parentFunc(); </script> 1 1 Link to comment Share on other sites More sharing options...
iwato Posted August 3, 2018 Author Share Posted August 3, 2018 Thanks, JMRKER! I have copied your script into my Javascript notes. It will make it easy to remember, should I ever forget. :-) Roddy Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now