The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Jquery json using the module pattern?

  • This topic is empty.
Viewing 14 posts - 1 through 14 (of 14 total)
  • Author
  • #177522

    Hi Folks,

    Is there a way I can write this script using the module pattern as a learning process?

    if(enteredId !== ”){
    $.getJSON(‘xxxx?callback=?’,{ Id: enteredId}, function(json) {
    if (json.usernameLogin) {
    // alert(“usernameLogin”);
    // continueField.fadeIn(“slow”);
    alert(“Please enter only numbers for your login id”);


    It would probably be a better learning experience if you used a script that worked to start with. There seem to be a lot of variables/ declarations/ logic that you “left out” of your snippet. I have a general idea of what you’re doing, but not the context of how you’re doing it.

    In order to make something into a module, it must be basically self-contained. For example:

    /* "paint it black" module */
    (function( $, $el ){
        $el.each( function(){ 
            $(this).css( 'background-color','#000' ); 
        } );
    })( $, $('.elements-to-paint-black') );

    Note this module needs two things from “the outside” (the outer (presumably global) scope): jQuery and a jQuery collection of DOM elements. Instead of assuming these are available in the global scope, on the last line we inject them into the module intentionally.

    Also, please make sure to use code blocks to format the code you post here on the forums. If you need to share larger amounts of code, it would be a good idea to use a service like codepen.


    Thanks very much for the reply.

    I’ve added a working codepen:

    How would i use the module pattern above using the jquery document ready in my example? and would I need to pass all my vars into the module too?

    Many thanks


    Just glancing, you’d need to pass jQuery in. It looks like everything else you’d need are the ids of the form elements you’re using —if so, it would probably be easiest to pass them in a single options object (it would be easy to provide defaults this way, too).

    I might suggest using classnames instead of ids, but that’s up to you. It would make it more modular/resilient. But it won’t really affect how we code it, so no big deal.

    Looks like we’ll need to specify the URL for the ajax call, too.


    I would highly recommend getting rid of this:

        $("form").bind("keypress", function(e) {
            if (e.keyCode == 13) {
                return false;

    Hitting [Enter] is supposed to cause a form to submit. It’s not a bug, it’s a well-established UX feature. Unless you have a really good reason*, you should not break the user’s experience by trying to control how their browser works.

    * and I’ve never heard a “really good reason”


    What is the var productId for? I don’t see any way it could be something other than 0 (i.e., it will never be 8 or 9, so that check looks to be a non-op), and you don’t seem to use it for any other purpose…?


    When I try your pen demo, does not return a valid JSON response. With your callback parameter in place I get ?(), without it, nothing. Because of this, when jQuery executes your success handler, json is not defined and your code throws a typeError.

    What format does the API expect? what does it return on success?


    Thanks very much for your reply.

    Would the options object to get the values look something like this:

    var Options = {
    defaultUsername : 'admin',
    idField : '', 
    usernameField : '',
    usernameText : '',
    passwordField : '',
    submitField : ''

    How would I populate the properties with the form values?

    Would this be the way to go about it for example?

    var Options = {
    usernameField = $("#usernameField");

    PS I’ve read lots of tutorials on this but I really need to do some code for myself to get an idea of what’s going on.

    Thanks again


    Would the options object to get the values look something like this


    How would I populate the properties with the form values?
    Would this be the way to go about it for example?

    probably not. I would pass in the desired selectors in options, and then jQuery-ify them at runtime.

    I’ve read lots of tutorials on this but I really need to do some code for myself to get an idea of what’s going on… New pen here

    To clarify, what I meant was that I’d like to see a working version of the script (not a start at rewriting it), so I can understand what it is supposed to do. If I don’t know what it needs to do, how could I give you an example of how to change it?

    If you don’t have a working example, then I’d need to know how the API works (what URLs to use, what parameters to pass, what their responses should be) and a basic description of how you want the user experience to go.


    Thanks again for the reply.

    Depending upon what organisationid is entered, either a username/ password or just password is displayed. Its a login form for various products, some have usernames and some don’t.

    An id if 4055 would get {“continueLogin”:true,”usernameLogin”:true}) and display both username and password fields.

    An id of 44 would get {“continueLogin”:true,”usernameLogin”:false}) and just display the password field.

    My jquery just gets plonked on the page to get a job done. I would really like to start using structure with my JS. If you could just point me some similar examples I’m sure I could come up with something to post up another codepen.

    Thanks again for your help


    Alright. To start, I’d build out an object with default options, then extend it with (any) runtime options. I’d only have CSS selectors in the options: turn them into jQuery objects after.

    From there, you can —more-or-less— code normally:

    (function( $,userOpts ){
        var defaultOpts = {
            username: 'admin',
            selectors: {
                idInput: '#id',
                usernameInput: '#scemail',
                usernameFieldset: '#usernameField',
                passwordFieldset: '#passwordField',
                submitFieldset: '#submitField'
            ajaxURL: ''
        var _options = $.extend( true,{},defaultOpts,userOpts );
        var $idInput          = $(idInput),
            $usernameInput    = $(usernameInput),
            $usernameFieldset = $(usernameFieldset),
            $passwordFieldset = $(passwordFieldset),
            $submitFieldset   = $(submitFieldset);
        /*  rest of your code goes here  */
    })( $,{} );

    Note I’m passing in $ as $. Doing so might seem redundant, but it accomplishes two things:

    • We put $ into the module scope intentionally, rather than assuming it’s already loaded on the page. If you use something like requirejs, you can specify jQuery as a dependency so it’s loaded automatically if needed.
    • We can use noConflict if needed (i.e., pass jQuery instead of $), and still use $ inside the module.

    I’m passing in an empty object ({}), so this will end up using all the default options. This allows you to override individual (any|all) options as desired, just by specifying them here.


    Thats great, thanks very much.

    I’ve added an output div under the form, and passed a few pieces of text into the exposed object. Can you please demonstrate how I can make one private and one public? By displaying one in the output div and one as undefined or null in developer tools? Just for my understanding?

    Many thanks again

    I’ve updated my pen:


    Anything you define in the function expression using var will be private. To make a public property, assign it to this instead.

    var modularObject = (function(){
        var _private = 'This is a private variable';
        this.public = 'This is a public variable';
        return this;


    After looking at your pen, I am less sure about your question. privateOutput and publicOutput are both private to the module scope (because they are arguments). Further, you’re not assigning properties to the showit object, you’re assigning a value to its innerHTML property.

    In general, the distinction between “private” and “public” variables isn’t really important in our case, since there is no global reference to the module object (and, therefore, even “public” properties would be unreadable). Perhaps you could explain in more detail what it is you want to accomplish?

Viewing 14 posts - 1 through 14 (of 14 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.