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?

6
  • Related: stackoverflow.com/questions/18441194/… codeproject.com/Questions/631342/… Commented May 28, 2015 at 14:37
  • @mason This question demonstrates what this site has become. Everyone is quick to downvote what they don't understand. Commented May 28, 2015 at 14:37
  • @Eterm sigh, they don't even attempt to clarify a question anymore.. Commented May 28, 2015 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? Commented May 28, 2015 at 14:39
  • aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.2 Commented May 28, 2015 at 14:39

1 Answer 1

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!");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Cool, too bad this question was closed! I don't think anybody really read it very carefully.
Indeed! People are too quick to move on haha. Thanks man!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.