Tina
Tina

Reputation: 89

Call another script's function on Ajax.success

I have a View in which I'm having a script tag and I want to use the function present in another JS file. If I add the AddScrollBar() in the same script file it works , but I want to use in multiple places. So I have it in site.js. When The page gets loaded I can see the script tag of site.js getting loaded.

View with script

<script type="text/javascript"> 
function LoadXyz() {
        $.ajax({
            url: '/ABC/Xyz/' + @Model.Number,
            success: function (data) {
                LoadContainerData(data);
                AddScrollBar();
            }
        });
        $("#navMenu > li").removeClass("active");
        $("#Xyz").addClass("active");
    }

Any ideas on how can I use AddScrollBar() present in site.js

Upvotes: 0

Views: 1541

Answers (2)

Emeeus
Emeeus

Reputation: 5250

You could call functions of other file (site.js in this case) if you insert the file in this way:

    <script src="path/to/site.js"></script>
    <script>
    AddScrollBar();
    </script>

you will be able to call functions and vars within site.js, but keep in mind that functions within site.js are not hoisted (As DonCarlos said in comments) so this doesn't going to work

    <script>
    AddScrollBar();//undefined
    </script>
    <script src="path/to/site.js"></script>
  • site.js must be placed inside the document root, where browser can access it. So if we have a folder structure where the document root is /var/www/ , browser will not be able to access to files in /var.
  • If the file is placed in /var/www/site.js and the file who is calling site.js is placed in the same folder we could call site.js with just src="site.js" (relative path) or src="http://example.com/site.js" (absolute path)
  • If the file is placed in /var/www/scripts/site.js and the script who is calling site.js is placed in /var/www/ we could call site.js with src="/scripts/site.js" (relative path) or src="http://example.com/scripts/site.js" (absolute path)
  • If the file is placed in /var/www/site.js and the script who is calling site.js is placed in /var/www/script/ we could call site.js with src="../site.js" (relative path) or src="http://example.com/site.js" (absolute path)

Upvotes: 1

you can create file script.js, copy code pastes below, run try it

//create file script.js

var loadA = function(){
		console.log("loadA");
}

var loadB =  function(){
		console.log("loadB");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="script.js"></script>
	<script>
		$(document).ready(function(){
			loadA();
            loadB();
		});

	</script>

Upvotes: 0

Related Questions