User6667769
User6667769

Reputation: 805

javascript function doesn't responding

Simple thing!!..In asp.net- MVC project. i have a button . and i have a external javascript file mydata.js. in that file contains a function checkJS().

function checkJs()
{
   debugger;
   alert("your output!!!");
}

My code:

<div id="mydivid" style="background-color:lightblue;">
   STAGE
</div>
<input type="button" id="btnid" value="Load Data" /> 

When i click a button , Its just call the jQuery click function

$(document).ready(function () {
   $("#btnid").click(function (event) {
      debugger;
      $.getScript('mydata.js', function() {
         // debugger;
          checkJs();
      });

   });
});

I used initialy 1.12.4.js library file in the head tag
and i added my external js file in head tag.

what is the problem in my code. why the button click did not reached the external method.

Upvotes: 2

Views: 77

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

1.Make sure that jQuery library added before your external java-script file.

When you ensure the first point do like below:-

$(document).ready(function () {
    $("#btnid").click(function (event) {
       checkJs();
    });
});

2.If you want to use $.getScript() then do like below:-

$(document).ready(function () {
    $("#btnid").click(function (event) {
      $.getScript('mydata.js').done(function(data, textStatus) { // check the file path of mydata.js is correct or not?
         checkJs();
      });
    });
});

The above code will work only when you have jQuery library added before this code and you remove the external JavaScript file path from your head.

Note:-

data:- returned data from external script

textStatus:- status of the call to external script (plain-text like "Success")

For more knowledge check this link:- jQuery.getScript()

Upvotes: 2

Prashant Shirke
Prashant Shirke

Reputation: 1423

You can directly call your function without getScript if you have already included the mydata.js in head.

If not, and want to do it with getScript then make sure you are giving correct path, load js in done callback and if still not then check if calls goes to fail callback.

 $(document).ready(function () {
    $("#btnid").click(function (event) {
      debugger;

       $.getScript('mydata.js').done(function(data, textStatus, jqxhr) {
          checkJs();
       }).fail(function(){
           if(arguments[0].readyState==0){
           //script failed to load
           }else{
             //script loaded but failed to parse
             alert(arguments[2].toString());
           }
       })
    });
});

Done callback has 3 parameters with has following values in it.

  1. data: has the returned data(script)
  2. textStatus: it returns the status in plain text, e.g. "Success"
  3. jqxhr : its jqXHR object, which is a superset of the XMLHTTPRequest object and has the "status" property which returns status code.

Upvotes: 2

Related Questions