Im using Jquery Post in my code,
and Im wonder how can I call back from the server, to my HTML page..
this is my Jquery code :
function InsertMemo() {
$('#buttonComplain').bind('click', function () {
var noteMemo = $('#noteId').val();
var url = "Handlers/Handler.aspx";
$.post(url,
{ noteMemo: noteMemo },
function () {
hideMemoShowCons();
}
);
});
}
I want in the function, to call back from my code in C# :
protected void Page_Load(object sender, EventArgs e)
{
rndSntnc = RandomSentnce();
}
and then to pase it to my HTML :
<div class="cons">
<%=thecodeExample %>
</div>
how do I do that ?
You wouldn’t necessarily want to run
Page_Loadagain. 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 makeRandomSentncea staticWebMethodAnd do something like
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:
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 yoursuccessfunction), and to get to your method’s result, you just grab thedproperty of the aforementioned object.