-1

I want to call a C# server method from JavaScript. In JavaScript function alert is coming but not calling the server method.

Here is my code. This is the server side method:

public void ReloadData()
{
     //here is the code
}

Here is the client side function:

function GetData() {
alert("Function called");
PageMethods.ReloadData();
}

Now, here the getdata function is called and alert is also coming but in server side method is not called. [I have seen by doing in debug mode.]

halfer
  • 19,824
  • 17
  • 99
  • 186
s.k.Soni
  • 1,139
  • 1
  • 19
  • 37

1 Answers1

1

I believe you will have to use AJAX for this. Have a look here: https://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

ReloadData will be a webmethod in your code behind and will look something like this:

[System.Web.Services.WebMethod]
public void ReloadData()
{
     //here is the code
}

Then from the client side you will do something like this:

function GetData() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/ReloadData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });

}

CS.aspx is the name of your webpage.

Following on from your comment below; if you did not want to use JQuery then your Javascript code would look something like this:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'CS.aspx/ReloadData');
xhr.onload = function() {
    if (xhr.status === 200) {
        alert('Successful');
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();
w0051977
  • 15,099
  • 32
  • 152
  • 329
  • is there possible to do with javascript? – s.k.Soni Jul 08 '17 at 15:34
  • @s.k.Soni you use JavaScript to make the AJAX call. The JavaScript code runs in the client browser, whle the C# code is on your server. HTTP (AJAX) is how the two environments communicate. – Pointy Jul 08 '17 at 15:36
  • @s.k.Soni, I have updated the code. Are you asking if it is possible to do this without JQuery? – w0051977 Jul 08 '17 at 15:38