Can I use Ajax submit requests inside a (function($){...}(jQuery));?

时间:2018-12-03 12:53:13

标签: javascript jquery ajax anonymous-function

I'm a PHP developer and know a little bit of javascript. I am using ajax to submit a request to the server. I've read that it's good to put all your code inside the javascript anonymous function like: (function($){ //code here }(jQuery)). So, I've put my ajax code inside the anonymous function as well. It's working absolutely fine, but, I'm curious if it's okay to do so or not?

P.s: By all your code, I mean the whole .js file of the app containing user defined scripts.

Here's an example of my question.

HTML:

<form action="https://www.server-url.com/" method="POST" id="form">
    <input type="text" name="user-name">
    <button type="submit">submit</button>
</form>

JavaScript:

(function($){
    var main = {
        serverRequest: ()=>{
            $('#form').submit((e)=>{
                e.preventDefault();

                var username= $('input[name=user_name]').val();

                $.ajax({
                    url: $('#form').attr('action'),
                    type: 'POST',
                    data: {
                        user_name: username
                    },
                    success: (res)=>{
                        // success code here...
                    },
                    error: (err)=>{
                        // error code here...
                    }
                });
            });
        }
    };

    $(document).ready(()=>{
        main.serverRequest();
    });
}(jQuery));

Any help would be appreciated, thanks in advance. :)

1 个答案:

答案 0 :(得分:0)

This is indeed a good practice, as it prevents your code getting in conflict with other libraries that might use the $-sign in their own context.

if you are interested, you could take a look here, where your question has already been answered.