Search code examples
javascriptc#asp.netwebmethodpagemethods

Calling C# Code Behind from Javascript using PageMethods doesn't work


I'm trying to call my C# Web method from my javascript on 'Enter key press' using PageMethods.

ASP:

<input id="new-chat-text-input" type="text" placeholder="Your Message Here..." onkeydown="chatreply(event)">

Javascript:

function chatreply() {
  var inputtext = document.getElementById("new-chat-text-input");
  var x = event.keyCode;
  if (x == 13) {
      alert("The process came here"); //Gets triggered successfully
      var chatresult= PageMethods.SendChat(inputtext)
      alert(chatresult);
  }
}

Code behind:

[WebMethod]
public string SendChat(string input)
{
      return "Hey there";
}

Basically trying to get the input text from a textbox, send it to a method in the code behind and alert the response. I basically get an empty alert. What am I doing wrong?


Solution

  • I'm not too familiar with PageMethods, but from what I can see on a quick read, it returns immediately while performing an asynchronous AJAX call in the background. You must provide a callback for success and error. The success handler should display the result.

    function aichatreply() {
        var inputtext = document.getElementById("new-chat-text-input");
        var x = event.keyCode;
        if (x == 13) {
            alert("The process came here"); //Gets triggered successfully
            PageMethods.SendChat(inputtext, onSuccess, onFailure);
            //This line will execute immediately, not waiting for SendChat to finish
        }
    }
    
    function onSuccess(result) {
        alert(result);
    }
    
    function onFailure(result) {
        alert("Failed!");
    }