1

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?

mason
  • 31,774
  • 10
  • 77
  • 121
Jay
  • 4,873
  • 7
  • 72
  • 137
  • Related: http://stackoverflow.com/questions/18441194/how-to-call-a-c-sharp-function-from-javascript http://www.codeproject.com/Questions/631342/Calling-csharp-function-in-javascript – jkd May 28 '15 at 14:37
  • @mason This question demonstrates what this site has become. Everyone is quick to downvote what they don't understand. – Eterm May 28 '15 at 14:37
  • @Eterm sigh, they don't even attempt to clarify a question anymore.. – Jay May 28 '15 at 14:38
  • @Eterm What are you talking about? That has nothing to do with the question, and a single downvote on a question doesn't really mean a whole lot. And lastly, why are you directing your comment at me? – mason May 28 '15 at 14:39
  • http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.2 – artm May 28 '15 at 14:39
  • I suggest you edit your title, post, and tags to indicate that this question is specifically about PageMethods. – John Wu May 28 '15 at 14:49

1 Answers1

2

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!");
}
John Wu
  • 50,556
  • 8
  • 44
  • 80