Call javascript from asp.net mvc - javascript

How can i call a javascript function from a mvc controller similar
to what you would do in webforms with ICallbackHandler?
Is it possible?
Thank you.

Controller actions cannot call javascript functions. They return action results. Javascript code should be contained on the client side. So if you want to call a javascript function that should execute under certain circumstances you could subscribe for the corresponding event and when this event is triggered call the function.
For example if you wanted to call a javascript function when a button is clicked using jQuery you could do the following:
$(function() {
// subscribe for the click event
$('#someId').click(function() {
// the button is clicked => execute some javascript function here
});
});

Related

How to call javascript on button click Odoo

I want to call a javascript on a button click, I tried a lot of examples and it didn't work. The button needs a name and the associated functions run on the server sides, I want the event to run on the client side only.
if you’re using Odoo v8
$(document).on('click', $('button:has(span:contains(Text Inside Button))'), function() {
console.log('call function here');
});

all JQuery functions lost on partial postback

I have an aspx page (the JQuery.js is called in the masterpage for this). Now this is linked to the http://code.jquery.com/jquery.js
In this page I have an updatepanel which is dynamically loading different usercontrols which in turn have their own JS files loads (using scriptmanager). Now on a partial postback I am losing JQuery functions (for instance .val returns undefined).
[code]
function pageLoad(){
//whatever you want to do on partial postback
//alert('partial handler');
$(jutb).watermark('Username or Email address');
$(jptb).watermark('Password');
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
// Called when async postback begins
function InitializeRequest(sender, args) {
// alert("You are in the InitializeRequestHandler function."); // breakpoint here
}
// Called when async postback ends
function EndRequestHandler(sender, args) {
// this function is run after an Ajax partial postback occurs
loadUsername();
loadPassword();
if (args.get_error() != undefined)
alert("There was an error" + args.get_error().message);
return;
}
[/code]
my page load is being called in the partial postback. (i.e. I can alert to it.)
I have a linkbutton which triggers some JS code. after the partial postback if I try it .val returns undefined.
Any ideas why JQuery is being lost?
When you get the response back from the server into your update panel, all event handler bindings you did the first time the page loaded are broken, because those are new elements now, even though they satisfy the same selection criteria.
You can try to re-run your event handler binding - you can create some kind of init JS function that you'd call in your EndRequestHandler.
Other way, and probably better, would be to use jQuery's on to bind your elements to event handlers. Take a look here on how to use it:
https://api.jquery.com/on/

Call JavaScript function when button loaded by ajax is clicked

I have an html form that loads its contents through ajax and includes buttons that, when clicked, should execute a JavaScript function that is defined in the html page's script tag. SO: Button is loaded through ajax (works), but when button is clicked, it doesn't trigger the desired action and doesn't trigger a JavaScript error in Firebug. How does one get the onclick signal of a bunch of buttons loaded through ajax to bind to an already existing JavaScript function?
EDIT: I should have noted also that I am not using JQuery. I am willing to do so if it is the only way, but otherwise, I would prefer to use only native JavaScript.
EDIT2: My problem was a bit more involved, but as was stated in the chosen answer, you should be able to set the onclick event handler in the php script before sending the data through ajax. If you have a data-heavy response and want to reduce bandwidth, you might consider doing everything client-side, but I find it easier in most situations just to set the onclick attribute in the php script.
Your dynamically generated button could have an inline event bound to it. When generating the button, simply make sure it has an onclick="alreadyExistingFunc();" and the page will happily execute it.
Alternatively, when your AJAX data is finished writing itself into the document, find the new button(s) and bind the event to them:
function ajaxSuccess()
{
document.getElementById('newButtonIdHere').onClick = function() {
alreadyExistingFunc();
}
}
That should do the trick. Also note that if you ever "need" a small part of jQuery to do something (like selectors or event handling), you can almost always do it without loading the whole library.
Append/insert the HTML (retrieved AJAX response) to DOM and bind click event to it:
function alreadyExistingFunc() {
alert('button is clicked!');
}
var ajax_data ="<button id='my-button'>My Button</button>";
$('body').append(ajax_data).find('#my-button').on('click', function(e){
alreadyExistingFunc();
// some more code...
});
OR:
$('body').append(ajax_data).find('#my-button').on('click', alreadyExistingFunc);
You could also use a callback:
function getAjaxContent(callback) {
$.ajax({url: "url"}).done(function() {
callback(data);
});
}
getAjaxContent(function (data) {
//ajax content has been loaded, add the click event here
}

jquery button trigger server side onclick event

I am using a jquery dialog, when user click ok, the server side onclick event should be fired, if click cancel, nothing happened.
i have to prevent the click function at the beginning by preventDefault() function.
$(document).ready(function () {
$("#<%=submit.ClientID %>").click(function (event) {
event.preventDefault();
$("#confirm").dialog({
buttons: {
"OK": function () { $(this).dialog("close");
Here should be the code to trigger the server side click event
},
"Cancel": function () { $(this).dialog("close");},
}
});
});
});
I don't know how to trigger a server side onclick event. any ideas? thanks
https://stackoverflow.com/a/10583339/1202242
I used two button, and one is hidden.
It solved my problem perfectly
Put the event.preventDefault() in the cancel part or some kind of condition for it so it isn't running on every click.
i think you are confusing between server and client sides.
if you want to trigger event on the server side you need to notify him (can be done by ajax call). the click event is a client side event that will not do anything on the server side.
try to put some code under the "OK" function to notify the server whatever you want like via ajax call.
anyway you should move the event.preventDefault() call into the "Cancel" function.
edit: another way to approach it is to prevent the submit to happen if you don't want it. at your form tag add onsubmit="foo()"
and define:
function foo(){
//call your dialog and return true to continue the submit and false to cancel.
}
It looks a little bit dependant on implementation details (even if they're so widely used that they won't be changed) but code is this:
__doPostBack('submit','OnClick');
This will execute the OnClick event handler for the control named submit. As reference take a look to this little tutorial about how postbacks works in ASP.NET.

how to trigger updatepanel within a javascript function

i have an updatepanel in my asp.net web page. I want to trigger the updatepanel within a javascript function insead of triggering with a button.
In order to do that, i used __doPostBack('myUpdatePanel', ''); function. But i think it causes the whole page postback. My document.ready function is also executed when i call this function. I may be missing some points.
Is there any other way to trigger updatepanel within a javascript function?
I think if you put a hidden button inside the update panel and you can use the javascript to fire the click of this button, it will do what you want.
<script type="text/javascript">
function Update_UpdatePaanel() {
document.getElementById('<%= YourButton.ClientID %>').click()
}
</script>
The button MUST be inside a hidden div and DON'T set visibile="false" because if you set it to false, the control will not render and the javascript will produce errors.
<div style="display:none">
<asp:Button ID="YourButton" runat="server" />
</div>
Just create a javascript function and execute the generated postback event:
<%=ClientScript.GetPostBackEventReference(myUpdatePanel, "")%>
The above statement is put on your aspx page, and it references the exact same code generated from the server to cause a postback for your panel. You can use it by putting it inside a function on the client side:
function fncUpdatePanel () {
<%=ClientScript.GetPostBackEventReference(myUpdatePanel, "")%>;
}
Then you can attach that function to any event on your page (even a mouseover event). This example uses a server side to attach the event:
myUpdatePanel.attributes('onmouseover', 'fncUpdatePanel()')

Categories

Resources