Home > OS >  How do I fix undefined error in Ajax code
How do I fix undefined error in Ajax code

Time:09-10

I'm new to Ajax. This code works but when it does it gives a undefined error notification. How can I fix and give the user "The book's added to your favs!" notification?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
  function AddtoFavourite() {
    $.ajax({
      type: "POST",
      url: "/Books/AddtoFavourite",
      success: OnSuccess,
      error: function(result) {
        /* alert(result);*/
        console.log("test");
      }
    });
  }

  function OnSuccess(response) {
    /*alert(response.d);*/
  }
  
  AddtoFavourite();
</script>

CodePudding user response:

Open Developer toolbar (F12), then uncomment and set breakpoint in this line:

alert(response.d);

Place mouse over "response" and check the format the data is coming back in and the name of the property (such as .d). Data is coming back probably in a different format than what you are expecting.

CodePudding user response:

Please also post your C# code.

I suspect that you are not returning a correct json data.

Your C# controller code should return a JsonResult that contains an object so that the Javascript can parsed it properly.

It should return something like this (note that this is done with dotnet core 6 so you should adapt it to your version)

public JsonResult OnPostAddtoFavourite() {
    return new JsonResult(new { 
        d = "The book's added to your favs!"
    });
}

Javascript code

function OnSuccess(response) {
    console.log(response.d);
}
  • Related