You wouldn't necessarily want to run Page_Load
again. I mean, you could (and most ajax in web form development does run through the full page life cycle), but if there's no dependencies on any other part of the page, It'd probably just make more sense to make RandomSentnce
a static WebMethod
[WebMethod]
public static string RandomSentnce ()
{
... get your random sentence here ..
}
And do something like
$.ajax({
type: "POST",
url: "PageName.aspx/RandomSentnce",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
WebMethods do not go through the whole asp.net web forms life cycle, so they're generally faster, too.
Do you know which div needs to have its content replaced at the time of the invocation? If so, it would also make sense to give the div an ID so you can find it in your success method above, so you could just do:
...
success: function(msg) {
$("#myDivID").text(msg.d);
}
...
If it's something where you only know by clicking on it, you'd just have to capture a reference to the element when you invoke the ajax call and use that reference in the success method (or, using jQuery promises, you don't strictly have to pass in a success method, but I won't go into that now).
BTW I don't have all this memorized, I used http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/ as a source. If there's anything wrong with what I said, consult that source.
Edit:
You ask: First : on the $.ajax, on the url.. when you typed "PageName.aspx/RandomSentnce", it means that you go directly to the function?! and second : on the success function, what the "d" means in the $("#myDivID").text(msg.d); ?
Answer to #1: Not sure what you mean by "go" here, but that's how the url is structured for web methods on aspx pages, and, from your page, only that function will be invoked.
Answer to #2: by default (as of asp.net 3.5+), WebMethod responses get wrapped in a object "for security concerns" (see What does .d in JSON mean? and http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/). Basically, the body of your response will look like {"d":"..."}
which will get parsed into a javascript object (the first parameter to your success
function), and to get to your method's result, you just grab the d
property of the aforementioned object.