Access javascript data from Java (maven application) - javascript

I hope this is the right subforum to post this.
I'm very new to maven, vaadin and java applications in general, so I hoped you could help me with this as I'm not sure what's the best way to go about it.
Basically I have a maven project (java 7) which, using javascript, creates a popup window with a form inside, allows you to upload a file, display its content in a textarea and send it (the content of the file as a string) to the server via an ajax request. That was the easy part.
What I want to do now is to access that data sent through ajax (the string containing the data of the uploaded file) in Java because I need to run it through some validation.
I had a good look around, including the book of vaadin, and the net in general and considering that I have never done this before, it seems that one way could be to have a connector, but it looks a little too complicated and also it appears - from what I understand from the book of vaadin https://vaadin.com/docs/-/part/framework/gwt/gwt-overview.html - that I won't be able to implement that in my project given the structure I have - which is different from what's in there.
So, my question to you guys is, given the project I have (just a normal maven project) what would be the easiest way for me to access this data from Java?
Here is some code from the project, to put things into context:
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.JavaScript;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.client.ui.*;
#Theme("mytheme")
#Widgetset("my.vaadin.apptest.MyAppWidgetset")
#com.vaadin.annotations.JavaScript({"https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"
})
public class MyUI extends UI {
#Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
layout.addStyleName("myLayout");//add class to main div
Label label = new Label("Hello Vaadin user. Use this application to upload files.");
...
//HERE IS THE JAVASCRIPT CREATING AND INSTANTIATING THE POPUP AND THE AJAX CALL
//CREATING POPUP
JavaScript.getCurrent().execute(""
+"var $HTMLpopup = $('<div class=\"popupContainer\">"
+"<span class=\"cancelBtn big\"></span>"
+"<div class=\"wrapper\">"
+"<form action=\"\" id=\"fileForm\">"
+"<div class=\"mask\">"
+"<input type=\"file\" title=\" \"name=\"uploadFile\" class=\"uploadFile\" accept=\".mol,.sdf\">/*filters files to upload*/"
+"<span class=\"pseudoBtn\">Browse</span>"
+"<input type=\"text\" name=\"displayFile\" class=\"displayFile\" placeholder=\"no file loaded\">"
+"<span class=\"cancelBtn small\"></span>"
+"</div>"
+"<textarea class=\"fileResult\"></textarea>"
+"<button type=\"submit\" class=\"submitBtn\">Upload</button>"
+"<div class=\"clear\"></div>"
+"</form>"
+"</div>"
+"</div>');"
//INSTANTIATING THE POPUP
+"$('.popupTriggerBtn').click(function(){"
+"/*console.log('button clicked!');*/"
+"var $body = $('body');"
+"$HTMLpopup.appendTo($body);"
+"});"
//HERE IS THE AJAX BIT
+"var $submitBtn = $HTMLpopup.find('.submitBtn');"
+"$submitBtn.click(function(e){"
+"e.preventDefault();/*prevent submission*/"
+"if(isFileUploadEmpty()){/*IF EMPTY*/"
+"/*alert('submit clicked');*/"
+"removeError();"
+"showError('empty');"
+ "}"
+"else{/*IF NOT EMPTY*/"
+"/*AJAX OPS*/"
+"if (window.XMLHttpRequest){/*XMLHttpRequest SUPPORT?*/"
+"console.log('XMLHttpRequest supported!');"
+"var postData = returnFileAsString();/*returns the file as a string*/;"
+"/*console.log('here is the file as a string ' + postData);*/"
+"$.ajax({"
+"type:'post',"
+"url:'http://localhost:8080/apptest/',"
+"data:postData,"
+"contentType: 'application/x-www-form-urlencoded',"
+"success: function(responseData, textStatus, jqXHR){"
+"/*alert('data saved');*/"
+"console.log('responseData is ' + responseData);"
+"console.log('text status is ' + textStatus);"
+"console.log('the data submitted is ' + postData );"
+"},"
+"error: function(jqXHR, textStatus, errorThrown){"
+"console.log(errorThrown);"
+"alert('an error has occurred!');"
+"}"
+"});"
+"}"
+"}"
+"});"
+"");
//ADDING COMPONENTS
layout.addComponents( label, button );
layout.setMargin(true);
layout.setSpacing(true);
setContent(layout);
}
Link to pastebin here http://pastebin.com/mSEJq0HT
So, postData contains the string that I passed to the server and that I'd like to access in Java.
I came across this earlier on, which may or may not be another way to deal with it vaadin with ajax. What do you guys think?
Any help would be much appreciated, thanks

Well, firstly I need to express my deep concern that you are using wrong tools in a really strange way to achieve your desired effect. I won't go deeply into that topic but lets just indicate the main purpose of Vaadin framework is to allow developer to write components in Java (similarly to Swing components) to avoid JavaScript mess. Yes, you can run JavaScript using Vaadin Framework but you should avoid it as long as possible.
Ok now lets get into hacking. You have two options to catch your file data (which is a String as you said) by your server:
a) Get rid ofconstructing your XMLHttpRequest by hand. Let Vaadin handle it for you. Instead of
+"$.ajax({"
+"type:'post',"
+"url:'http://localhost:8080/apptest/',"
...
just call JavaScript function, lets say
sendFileContentToTheServer(postData)
Now next thing you need to do is to register JavaScript callback on the Server side (read: Vaadin). Somewhere in your code (doesn't really matter where, just make sure the code is called at least once - ideally exactly once) put:
JavaScript.getCurrent().addFunction("sendFileContentToTheServer", new JavaScriptFunction() {
public void call(JSONArray arguments) throws JSONException {
System.out.println(arguments.getString(0));
//do whatever you want with your data - its under arguments.getString(0)
}
});
That's it. Vaadin will manage the RPC call for you. Your page won't be reloaded and you will get your data on the server side.
b) The second approach it's a way more tricky. It is technically possible to construct XMLHttpRequest by hand and receive data on the server using Vaadin. What you need to do is to register JavaServlet (not VaadinServlet). Send the data to the JavaServlet. Then through some proxy or reference call the existed VaadinUI. It's a compilcated way of doing things that you've already made very tricky so I won't go deeper into that.

Related

Can user's custom JavaScript on MediaWiki call a Lua module?

On MediaWiki wikis each user has a user JavaScript page they can put code in, much like GreaseMonkey but without extensions. Such as at User:YourUsername/vector.js
MediaWiki has also had an embedded Lua, called Scribunto, for a little while now.
I know Lua modules can be called from MediaWiki templates, and I suppose that's their main use. But Googling and hunting around the MediWiki docs I can't find whether there's a way to call a Lua module from your user JavaScript.
(I need to map names of languages to language codes in my JS and there's a Lua module to do just that without me duplicating the code (mainly data) in a second language.)
You can't do this directly, because JS runs on the client and Lua on the server. What you can do is to use the MediaWiki API from JS to invoke the module. Specifically using the expandtemplates API module.
For example, if you wanted to call the function h2d from Module:Hex with the parameter FF ({{#invoke:hex|h2d|FF}} in wikitext) and alert the result, then the JS would look like this:
var api = new mw.Api();
api.get( {
action: 'expandtemplates',
text: '{{#invoke:hex|h2d|FF}}'
} ).done ( function ( data ) {
alert(data.expandtemplates['*']);
} );
And for the OP's specific case, running on the English Wiktionary:
var langName = 'Esperanto';
(new mw.Api()).get({
action: 'expandtemplates',
format: 'json',
prop: 'wikitext',
text: '{{#invoke:languages/templates|getByCanonicalName|' + langName + '|getCode}}'
}).done(function(data) {
alert('Language name: ' + langName + '\nLanguage code: ' + data.expandtemplates.wikitext);
});
(prop: 'wikitext' avoids a warning from the API and lets you access the result as data.expandtemplates.wikitext rather than the slightly mystifying data.expandtemplates['*']. Otherwise there's no difference.)

Real time insertion of data in mvc

I have a news project with comment feature. Any one who add a comment can see his comment immediately without reloading the page ( using ajax ). The problem is that when user1 ( for example ) comment on post1 , only user1 can see his comment immediately but all other users need to reload the page to see the comment of user1. How can I solve this problem ?
The code I am using to get the comment :
$(function () {
$("#AddComment").click(function () {
var CommentText = document.getElementById("CommetForm").innerHTML;
var UserName = document.getElementById("UserName").innerHTML;
var PostId = document.getElementById("PostId").innerHTML;
$.ajax({
url: '/PostComment/AddComment',
type: 'POST',
dataType: 'json',
cache: false,
data: { "PostId": PostId, "CommentText": OrignalCommentText },
success: function (data)
{
if (data == "P") // Commet Stored on database successfully
{
document.getElementById("PostComments-" + PostId).innerHTML +=
"<li>" +
"<div class='media'>" +
"<div class='media-body'>" +
"<a href='' class='comment-author'>"+UserName+"</a>" +
"<span class='CommetText' id='CommentText-" + PostId + "'>" + CommentText + "</span>" +
"</div>" +
"</div>" +
"</li>";
}
else // Some Error occur during storing database
{
document.getElementById("CommentError-" + PostId).innerHTML = "\nSomething went wrog, please try agin";
}
}
});
});
});
And This code for storing comment in database :
private SocialMediaDatabaseContext db = new SocialMediaDatabaseContext();
[HttpPost]
public JsonResult AddComment(string PostId, string CommentText)
{
try
{
Users CurrentUser = (Users)Session["CurrentUser"];
PostComment postcomment = new PostComment();
CommentText = System.Uri.UnescapeDataString(CommentText);
postcomment.PostId = int.Parse(PostId);
postcomment.CommentFromId = CurrentUser.UserId;
postcomment.CommentText = CommentText;
postcomment.CommentDate = DateTime.Now;
db.PostComments.Add(postcomment);
db.SaveChanges();
return Json("P");
}
catch
{
return Json("F");
}
}
I suggest you use SignalR for this. http://www.asp.net/signalr/overview/getting-started/introduction-to-signalr
TL;DR Use can use setInterval or Websockets to accomplish this. Below I explain how.
First of all, we need to understand what is behind this Publish/Subscribe pattern. Since you want to build a real-time application, you may create a function that asks to your server if some data was added since last time it was checked.
USING WindowTimers.setInterval()
Here is the simplest way to accomplish this in my point of view, assuming that's your first time and you never worked with websockets before. For instance, in your client-side project you create a function within a setInterval setInterval( checkNewData, time). Your method checkNewData() will make an ajax requisition to your server, asking if some data was added recently:
function checkNewData() {
// ajax call
// On response, if found some new comment, you will inject it in the DOM
}
Then, in your server-side method, get the timestamp of its call and verify in your database if there are some data. Something like this:
// Method written in PHP
public function ajax_checkNewData() {
$time = time();
// Asks to your model controller if has something new for us.
// SELECT comment FROM comments WHERE timestamp > $time
// Then return its response
}
You will use the response that came from your controller method ajax_checkNewData() to write on your comments-container.
USING WEBSOCKETS (beautiful way)
Now, there are another way to do this, using WebSockets. HTML5 WebSocket represents the first major upgrade in the history of web communications. Before WebSocket, all communication between web clients and servers relied only on HTTP. Now, dynamic data can flow freely over WebSocket connections that are persistent (always on), full duplex (simultaneously bi-directional) and blazingly fast. Amongst different libraries and frameworks, you can use socket.io. I believe this will solve your real-time application problem pretty good, but I am not sure how much of your project you will need to change to suit this solution.
Check it out the simple chat tutorial from SocketIo page and see for yourself if it fits to your needs. Its pretty neat and would be a good challenge to implement using it. Since its event-driven, I believe you wont have problems implementing it.
For further information check it out:
REFERENCES
Get Started: Chat application - http://socket.io/get-started/chat/
Websockets - http://en.wikipedia.org/wiki/WebSocket
WebSockets - https://developer.mozilla.org/en/docs/WebSockets
Good luck!
You could write a JavaScript code which makes ajax call to a servlet that checks for updates in the database.
Return a flag to the success function of the ajax call and If the state has changed or any comment added to the database, you can reload the page or refresh the consisting of the comments with the new comments.
It's not posting on other pages, because the user1 page is making an AJAX call, so it loads correctly. However, the other pages don't 'know' they are supposed to reload via AJAX. You need some kind of timed loop running that checks for any changes. Either of the above answers should work for it.
You could use SignalR for this, you can send realtime messages to the server, here is a sample to know how to implement SignalR in ASP.NET MVC
https://github.com/WaleedChayeb/SignalRChatApp

MVC 5 - How to send an Excel file to the client?

I have a Bootstrap application that shows a list of data. I have a button at the bottom of the page that, when clicked, creates an Excel file and sends it back to the client.
The link (button) the user clicks to start the process is as follows:
<li>Export list to Excel</li>
The JavaScript function that gets called looks like this:
function ExportToExcel() {
var Url = "/UserLocation/ExportToExcel";
$.get(Url);
}
I know this probably isn't right, but it does correctly call my C# function that creates the Excel spreadsheet.
My C# function looks like this:
public ActionResult ExportToExcel()
{
var locationList = this.UserLocationData.GetList(this.AccountRowId).AsEnumerable();
ExcelPackage package = Common.Excel.CreateExcelFile(locationList);
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = "ExcelTest.xlsx",
// Always prompt the user for downloading, set to true if you want the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(package.GetAsByteArray(), "application/force-download");
}
At the moment, when the user clicks the button, my C# function is called, but nothing is returned to the client. I suspect my JS function is not correct, but I don't really know what to do to make it correct. I also don't know what MIME type to use in my C# method (the last line in my C# method). Is there a better way to do all this? I am fairly new to JavaScript.
With $.get() you're getting the data through ajax. The browser will get the file content in the ajax response, but there is no way to offer the user to save this data as a file. (Well, technically is possible in most browsers, but not in all of them, although some more are supported with this js. But obviously it's overkill for this case. Thanks to zerkms for his comment).
The solution is much simpler, use the old good window.open(url), so the file is opened in a new browser window, and the user will be invited to open or save it (that depends on the browser configuration).
Or use directly a link like this:
<li><a href ="/UserLocation/ExportToExcel" class="btn btn-info btn-sm">
Export list to Excel</a></li>
(unless your js function does some extra processing).

Python and reading JavaScript variable value

I am very new to Python programming, so please bear with me.
I have an HTML file with several div layers. This file is opened in a webkit.WebView object. Each div layer saves a value in a global variable (JavaScript) when clicked upon.
How can I read the value of that global JavaScript variable from my Python script?
I found some answers but they don't seem to fit my situation (but I can be wrong, of course):
Passing JavaScript variable to Python
Parse JavaScript variable with Python
[EDIT]
I'm using webkit.WebView because I have to show this in an existing glade (libglade) application.
try this out. It uses the addToJavaScriptWindowObject method to add a QObject into the QWebView. This will enable communication between your python script and the HMTL/Javascript in your webview. The example below will let you change the value of the javascript global variable message to whatever value you want through a JavaScript prompt, then whenever you click on the Python Print Message link it will execute your python code that will take the javascript value and just print it to the console.
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
HTML = """
<html><body onload="broker.print_msg(message)">
<script>var message = 'print_msg message'</script>
Change Message<br/>
Python Print Message
</body></html>
"""
class Broker(QtCore.QObject):
#QtCore.pyqtSlot(str)
def print_msg(self, data):
print data
app = QtGui.QApplication(sys.argv)
view = QtWebKit.QWebView()
view.page().mainFrame().addToJavaScriptWindowObject('broker', Broker(view))
view.setHtml(HTML)
window = QtGui.QMainWindow()
window.setCentralWidget(view)
window.show()
sys.exit(app.exec_())
I know this is old question, but still answering it with the hope that it will be useful to someone.
You can use alert handler and read the value in python side. http://webkitgtk.org/reference/webkitgtk/stable/webkitgtk-webkitwebview.html#WebKitWebView-script-alert
Example on button click you can have action that says
alert("Button Clicked");
On python side you will get the alert notification and you can parse the string. If the object is not a simple object, you will have to convert it to string format that can be parsed on python side. I have seen few examples of alert handler. https://github.com/nhrdl/notesMD/blob/master/notesmd.py is one that I wrote and uses alert handlers to pass lot of data between javascript and python

Call ASP.NET function from JavaScript?

I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event.
Is it possible to call a method I created in ASP with JavaScript's click event?
Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):
It is a little tricky though... :)
i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like
public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}
ii. This should add (using Tab-Tab) this function to your code file:
public void RaisePostBackEvent(string eventArgument) { }
iii. In your onclick event in JavaScript, write the following code:
var pageId = '<%= Page.ClientID %>';
__doPostBack(pageId, argumentString);
This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.
P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!
The __doPostBack() method works well.
Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.
<div style="display: none;">
<asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" />
</div>
From your JavaScript, retrieve the reference to the button using its ClientID and then call the .click() method on it.
var button = document.getElementById(/* button client id */);
button.click();
The Microsoft AJAX library will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.
I suggest the Microsoft AJAX library. Once installed and referenced, you just add a line in your page load or init:
Ajax.Utility.RegisterTypeForAjax(GetType(YOURPAGECLASSNAME))
Then you can do things like:
<Ajax.AjaxMethod()> _
Public Function Get5() AS Integer
Return 5
End Function
Then, you can call it on your page as:
PageClassName.Get5(javascriptCallbackFunction);
The last parameter of your function call must be the javascript callback function that will be executed when the AJAX request is returned.
You can do it asynchronously using .NET Ajax PageMethods. See here or here.
I think blog post How to fetch & show SQL Server database data in ASP.NET page using Ajax (jQuery) will help you.
JavaScript Code
<script src="http://code.jquery.com/jquery-3.3.1.js" />
<script language="javascript" type="text/javascript">
function GetCompanies() {
$("#UpdatePanel").html("<div style='text-align:center; background-color:yellow; border:1px solid red; padding:3px; width:200px'>Please Wait...</div>");
$.ajax({
type: "POST",
url: "Default.aspx/GetCompanies",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
function OnSuccess(data) {
var TableContent = "<table border='0'>" +
"<tr>" +
"<td>Rank</td>" +
"<td>Company Name</td>" +
"<td>Revenue</td>" +
"<td>Industry</td>" +
"</tr>";
for (var i = 0; i < data.d.length; i++) {
TableContent += "<tr>" +
"<td>"+ data.d[i].Rank +"</td>" +
"<td>"+data.d[i].CompanyName+"</td>" +
"<td>"+data.d[i].Revenue+"</td>" +
"<td>"+data.d[i].Industry+"</td>" +
"</tr>";
}
TableContent += "</table>";
$("#UpdatePanel").html(TableContent);
}
function OnError(data) {
}
</script>
ASP.NET Server Side Function
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static List<TopCompany> GetCompanies()
{
System.Threading.Thread.Sleep(5000);
List<TopCompany> allCompany = new List<TopCompany>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
allCompany = dc.TopCompanies.ToList();
}
return allCompany;
}
Static, strongly-typed programming has always felt very natural to me, so at first I resisted learning JavaScript (not to mention HTML and CSS) when I had to build web-based front-ends for my applications. I would do anything to work around this like redirecting to a page just to perform and action on the OnLoad event, as long as I could code pure C#.
You will find however that if you are going to be working with websites, you must have an open mind and start thinking more web-oriented (that is, don't try to do client-side things on the server and vice-versa). I love ASP.NET webforms and still use it (as well as MVC), but I will say that by trying to make things simpler and hiding the separation of client and server it can confuse newcomers and actually end up making things more difficult at times.
My advice is to learn some basic JavaScript (how to register events, retrieve DOM objects, manipulate CSS, etc.) and you will find web programming much more enjoyable (not to mention easier). A lot of people mentioned different Ajax libraries, but I didn't see any actual Ajax examples, so here it goes. (If you are not familiar with Ajax, all it is, is making an asynchronous HTTP request to refresh content (or perhaps perform a server-side action in your scenario) without reloading the entire page or doing a full postback.
Client-Side:
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest(); // Create object that will make the request
xmlhttp.open("GET", "http://example.org/api/service", "true"); // configure object (method, URL, async)
xmlhttp.send(); // Send request
xmlhttp.onstatereadychange = function() { // Register a function to run when the state changes, if the request has finished and the stats code is 200 (OK). Write result to <p>
if (xmlhttp.readyState == 4 && xmlhttp.statsCode == 200) {
document.getElementById("resultText").innerHTML = xmlhttp.responseText;
}
};
</script>
That's it. Although the name can be misleading the result can be in plain text or JSON as well, you are not limited to XML. jQuery provides an even simpler interface for making Ajax calls (among simplifying other JavaScript tasks).
The request can be an HTTP-POST or HTTP-GET and does not have to be to a webpage, but you can post to any service that listens for HTTP requests such as a RESTful API. The ASP.NET MVC 4 Web API makes setting up the server-side web service to handle the request a breeze as well. But many people do not know that you can also add API controllers to web forms project and use them to handle Ajax calls like this.
Server-Side:
public class DataController : ApiController
{
public HttpResponseMessage<string[]> Get()
{
HttpResponseMessage<string[]> response = new HttpResponseMessage<string[]>(
Repository.Get(true),
new MediaTypeHeaderValue("application/json")
);
return response;
}
}
Global.asax
Then just register the HTTP route in your Global.asax file, so ASP.NET will know how to direct the request.
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute("Service", "api/{controller}/{id}");
}
With AJAX and Controllers, you can post back to the server at any time asynchronously to perform any server side operation. This one-two punch provides both the flexibility of JavaScript and the power the C# / ASP.NET, giving the people visiting your site a better overall experience. Without sacrificing anything, you get the best of both worlds.
References
Ajax,
jQuery Ajax,
Controller in Webforms
The Microsoft AJAX library will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.
This is the library called AjaxPro which was written an MVP named Michael Schwarz. This was library was not written by Microsoft.
I have used AjaxPro extensively, and it is a very nice library, that I would recommend for simple callbacks to the server. It does function well with the Microsoft version of Ajax with no issues. However, I would note, with how easy Microsoft has made Ajax, I would only use it if really necessary. It takes a lot of JavaScript to do some really complicated functionality that you get from Microsoft by just dropping it into an update panel.
It is so easy for both scenarios (that is, synchronous/asynchronous) if you want to trigger a server-side event handler, for example, Button's click event.
For triggering an event handler of a control:
If you added a ScriptManager on your page already then skip step 1.
Add the following in your page client script section
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
Write you server side event handler for your control
protected void btnSayHello_Click(object sender, EventArgs e)
{
Label1.Text = "Hello World...";
}
Add a client function to call the server side event handler
function SayHello() {
__doPostBack("btnSayHello", "");
}
Replace the "btnSayHello" in code above with your control's client id.
By doing so, if your control is inside an update panel, the page will not refresh. That is so easy.
One other thing to say is that: Be careful with client id, because it depends on you ID-generation policy defined with the ClientIDMode property.
I'm trying to implement this but it's not working right. The page is
posting back, but my code isn't getting executed. When i debug the
page, the RaisePostBackEvent never gets fired. One thing i did
differently is I'm doing this in a user control instead of an aspx
page.
If anyone else is like Merk, and having trouble over coming this, I have a solution:
When you have a user control, it seems you must also create the PostBackEventHandler in the parent page. And then you can invoke the user control's PostBackEventHandler by calling it directly. See below:
public void RaisePostBackEvent(string _arg)
{
UserControlID.RaisePostBackEvent(_arg);
}
Where UserControlID is the ID you gave the user control on the parent page when you nested it in the mark up.
Note: You can also simply just call methods belonging to that user control directly (in which case, you would only need the RaisePostBackEvent handler in the parent page):
public void RaisePostBackEvent(string _arg)
{
UserControlID.method1();
UserControlID.method2();
}
You might want to create a web service for your common methods.
Just add a WebMethodAttribute over the functions you want to call, and that's about it.
Having a web service with all your common stuff also makes the system easier to maintain.
If the __doPostBack function is not generated on the page you need to insert a control to force it like this:
<asp:Button ID="btnJavascript" runat="server" UseSubmitBehavior="false" />
Regarding:
var button = document.getElementById(/* Button client id */);
button.click();
It should be like:
var button = document.getElementById('<%=formID.ClientID%>');
Where formID is the ASP.NET control ID in the .aspx file.
Add this line to page load if you are getting object expected error.
ClientScript.GetPostBackEventReference(this, "");
You can use PageMethods.Your C# method Name in order to access C# methods or VB.NET methods into JavaScript.
Try this:
if(!ClientScript.IsStartupScriptRegistered("window"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "window", "pop();", true);
}
Or this
Response.Write("<script>alert('Hello World');</script>");
Use the OnClientClick property of the button to call JavaScript functions...
You can also get it by just adding this line in your JavaScript code:
document.getElementById('<%=btnName.ClientID%>').click()
I think this one is very much easy!
Please try this:
<%= Page.ClientScript.GetPostBackEventReference(ddlVoucherType, String.Empty) %>;
ddlVoucherType is a control which the selected index change will call... And you can put any function on the selected index change of this control.
The simplest and best way to achieve this is to use the onmouseup() JavaScript event rather than onclick()
That way you will fire JavaScript after you click and it won't interfere with the ASP OnClick() event.
I try this and so I could run an Asp.Net method while using jQuery.
Do a page redirect in your jQuery code
window.location = "Page.aspx?key=1";
Then use a Query String in Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["key"] != null)
{
string key= Request.QueryString["key"];
if (key=="1")
{
// Some code
}
}
}
So no need to run an extra code
This reply works like a breeze for me thanks cross browser:
The __doPostBack() method works well.
Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.
<div style="display: none;">
<asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" />
</div>
From your JavaScript, retrieve the reference to the button using its ClientID and then call the .Click() method on it:
var button = document.getElementByID(/* button client id */);
button.Click();
Blockquote

Categories

Resources