user2232681
user2232681

Reputation: 833

How do I include an Ajax call as an external file?

I have a simple Ajax call which works perfectly when I wrap it in the document ready function in a script before the closing body tag in my HTML file. However, when I try to move the call into an external .js file, excluding script tags and the document ready function, the call does not work. I have tried adding the external file in both the head and body of the HTML file like this without any success:

<script src="includes_js/login3.js" type="text/javascript"></script>

I did not include much code here because I am not sure what might be helpful.

Upvotes: 5

Views: 13006

Answers (2)

Chetan Hirapara
Chetan Hirapara

Reputation: 694

You can call js methods from external files like below way.

 $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: encodeURI("../CtrlName/MethodName"), // adjust your path
        async: true,
        data: JSON.stringify({ "param": _param }),
        dataType: "json",
        success: function (data) {
            console.log(data);
        },
        error: function (data) {
            console.log(data);
        }
    });

Upvotes: 0

Trevor
Trevor

Reputation: 16116

However, when I try to move the call into an external .js file, excluding script tags and the document ready function

Try adding the document ready function to your external java script file.

$(document).ready(function(){
 alert('worked');
 // ajax call here
});

If the alert gets run that means your external java script file is being loaded. Otherwise something may be wrong with the path in your <script> tag.

Upvotes: 2

Related Questions