0

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. :)

  • Your complete code can be written like this if you do not need the IIFE: `$(function() { $('#form').on("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... } }); }); });` – mplungjan Dec 03 '18 at 12:58
  • @mplungjan yeah I know about it. I am just using this approach so that I can format my code better. Instead of making a separate `.js` file and a class, I can manage it in one file very easily under different names. `var main = { request1: ()=>{ // some code; }, request2: ()=>{ // some code; } };` – carl johnson Dec 03 '18 at 13:11

1 Answers1

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.

Simeon
  • 51
  • 1
  • 3
  • I know about anonymous functions of javascript. My question is, is it okay to use the ajax submit requests in anonymous functions? It was the title of my question. :) – carl johnson Dec 04 '18 at 09:46