How to call java script function from ashx handler file - javascript

My function
<script type="text/javascript">
function methodtocall(id) {
// My code
}
</script>
My ashx page
public class sampleClass : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
// here i need to call that method
}
}
yes i referred net.But no solutions for that. mostly they give solution to call from method to ashx or call from ajax.
can anyone direct me with correct thing?

Refer like this,
ClientScript.RegisterStartupScript(this.GetType(), "methodtocall", script, true);
as per code,
public class sampleClass : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
var id = "someid"; //implement the id that you want to pass to the Javascript function
ClientScript.RegisterStartupScript(this.GetType(), "methodtocall", id, true);
}
}
Hope this helps..!
reference Link : Link

you can do like this
context.Response.Write("<script type='text/javascript'>function closeCurrentTab(){var conf=confirm('Are you sure, you want to close this tab?');if(conf==true){close();}}</script>");
context.Response.Write("<script type='text/javascript'>closeCurrentTab();</script>");

Related

Passing value from java to Javascript

I'm making an Android app using webview.
The app can print out receipts. What I want to do is when the printer is not working, alert box shows up to tell the printer isn't working, and return false to the form's onsubmit event to prevent form from being submitted.
Java code:
public class JSKicker {
#JavascriptInterface
public void callPrint(final String argumet) {
Thread thread = new Thread(new Runnable() {
public void run() {
int nRtn;
connectionNum = myPrinter.Connect("000.000.0.000");
if(connectionNum < 0){ //Printer not working
webview.post(new Runnable() {
#Override
public void run() {
String script = "alert('Printer Error'); return printer_connection = false;";
webview.evaluateJavascript(script, new ValueCallback<String>() {
#Override
// I can't figure out what to do here...
});
}
});
}else{ //Printer is working properly
connectionNum = myPrinter.SetLocale(8);
strText = argument;
nRtn = myPrinter.PrintText(strText, "SJIS");
nRtn = myPrinter.PaperFeed(64);
nRtn = myPrinter.CutPaper(1);
myPrinter.Disconnect();
}
}
});
thread.start();
}
JavaScript in header:
<script type="text/javascript">
function gate(){
jQuery.ajax({
url:'/cart_info.php',
type:'GET'
})
.done( (data) => {
window.JSKicker.callPrint(data);
})
if (printer_connection = false) {
return false;
}else{
return true;
}
}
</script>
HTML form tag:
<form method="post" id="order_form" onsubmit="return gate();">
How can I get this work?
Could you do it thru WebView.evaluateJavascript()?
https://developer.android.com/reference/android/webkit/WebView.html#evaluateJavascript(java.lang.String,%20android.webkit.ValueCallback%3Cjava.lang.String%3E)
So with that you could send simple CustomEvent to document in WebView
webView.evaluateJavascript("document.dispatchEvent(new Event('printer_error', { details: "No printer found!" }));");
and in JavaScript you can hook listener for your custom event to react.
document.addEventListener('printer_error', e => alert(e.details));
Didn't test this so might be that at least evaluateJavascript() needs callback function.
WebSocket can solve your problem.
WebSockets provide a persistent connection between a client and server that both parties can use to start sending data at any time. The client establishes a WebSocket connection through a process known as the WebSocket handshake.
Its very straight forward and easy to implement.
You can follow referrer links for more details:-
JAVA WebSocket:- WebSocket using Spring Boot, WebSocket using Simple JEE
Browser WebSocket(JavaScript):- WebSocket API
In Android ,if you want webview pass value to JavaScript.
First,you need to set the webview enable the JavaScript,
private WebView mWebView;
void onCreate(){
mWebView = findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
}
And ,in you want do some thing code
if(connectionNum < 0){ //Printer not working
// I need to do something here to send a message that the printer isn't working to JS.
//In thread can not use mWebView,should send message to MainThread to do
// mWebView.loadUrl("javascript:javaCall()");
Message msg = new Message();
msg.what = 1;
myHandler.sendMessage(msg);
//myHandler can be your MainThread send to here
}
And where the mWebView created in your code, be in main thread ,you can use the
Handler to deal with the message sended to here.
private Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// this 1 is just thread send to here
if (msg.what == 1) {
//and here can do the webview UI method
mWebView.loadUrl("javascript:javaCall()");
}
}
};
the javaCall() is where you JacaScript invoke method,in javaScript you can writre like this:
<script language="javascript">
function javaCall(){
alert("Printer Error");
//other thing you can do
}
</script>
if you have problem ,you can refer to the official document.
public void loadUrl (String url)
Loads the given URL.
Also see compatibility note on evaluateJavascript(String, ValueCallback).
webview use link

How to pass String Argument to javascript function

This is my front-end:
ImageButton Details = (ImageButton)e.Row.FindControl("iBtnDetails");//take lable id
String strApplication1 = Details.CommandArgument.ToString();
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes.Add("onClick", "SelectRow()");
This is my back-end:
<script type="text/javascript">
function SelectRow() {
var strApplication1 = '<%=strApplication1%>'
if (strApplication1 == "IT Application Request")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "IT Account Request")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "Change Control Management")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "Backup & Restore")
{
window.open('http://.aspx', '_blank');
}
}
</script>
I want to pass String Argument to javascript function, but I got error that strApplication1 doesn't exist in the current context.
You need to make strApplication1 a public property on your page class. Currently, it is just an internal variable.
Something like:
public partial class YourPage : System.Web.UI.Page
{
public string strApplication1 {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
//Your page logic
}
//Looks like you set the variable in an onDatabound or similar.
//So use this where you currently set the variable
strApplication1 = Details.CommandArgument.ToString();
}

Failed to call Asp.net method from Javascript

I want to call Asp.Net function from Javascript. I have a sample which is calling Asp.net MVC funciton like that.
#{
var payUrl = "/recordings/recording-123.wav";
<!-- saves the wav file to local folder called recodings using a session value to make unique file names -->
}
function setupRecorder() {
Wami.setup({
id: "wami",
onReady: setupGUI
});
}
function setupGUI() {
var gui = new Wami.GUI({
id: "wami",
recordUrl: "http://localhost:5296/home/Save",
playUrl: "#payUrl"
});
gui.setPlayEnabled(false);
}
Here is the exact calling from the code
recordUrl: "http://localhost:5296/home/Save",
The HomeController has a method Save which is being called here
public ActionResult Save()
{
Request.SaveAs(Server.MapPath("/recordings/recording-123.wav"), false);
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
I want the exact thing in Asp.Net but i am not able to find the solution if anyone out there can help me out i would be thankful to you this is the only part left in my project i simply need to save the audio. I am doing like this
<script>
function setupRecorder() {
Wami.setup({
id: "wami",
onReady: setupGUI
});
}
function setupGUI() {
var gui = new Wami.GUI({
id: "wami",
recordUrl: "Default.aspx/Save",
playUrl: "/recordings/recording-123.wav"
});
gui.setPlayEnabled(false);
}
</script>
I have a webform Default.aspx which has method save
recordUrl: "Default.aspx/Save",
This is the exact default.aspx.cs method. I have tried [HttpGet] and [httpPost] both nothing is working for me .
[HttpGet]
[System.Web.Services.WebMethod]
public void Save()
{
Request.SaveAs(Server.MapPath("/recordings/recording-123.wav"), false);
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
I think your save method needs to be marked as static since its a webmethod. Only then you should to be able to call it from JS
[System.Web.Services.WebMethod]
public static void Save()
{
Request.SaveAs(Server.MapPath("/recordings/recording-123.wav"), false);
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}

android webview javascript not working with loadDataWithBaseUrl

I am trying to load data into android webview using
webview.loadDataWithBaseURL("", htmlcontent, "text/html", null, "");
a method returns htmlContent from a StringBuilder which populates html data.
I have enabled javascript and set webChromeClient as follows
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.addJavascriptInterface(new JSClass(), "Android");
my interface to javascript:
class JSClass {
public void getHTMLContent(String html)
{
Log.i(Global.TAG, "HTMLContentReceived: "+html);
}
}
and my javascript in html page:
<script type="text/javascript">
var ele = document.getElementsByClassName('test');
for(var i=0;i<ele.length;i++){
ele[i].onclick = function(){
window.Android.getHTMLContent(this.innerHTML);
}
}
</script>
but somehow the javascript is not returning any value.
It works fine with loadData(url) where url is a simple webpage in assets folder
Please help
Thanks in advance
You don't have any baseURL to use, since you're loading a dynamical generated HTML.
For this reason webview.loadData(htmlcontent, "text/html", null); should be more than enough.
Javascripts don't throw any exceptions in Java code. Remember that JS is not that type-safe/strict as Java code ... My way of doing is to put logs between sensitive Javascript calls to see if that line passes and to check values. Since you didn't provide the HTML, I would setup the WebChomeClient and override the onConsoleMessage:
webview.setWebChromeClient(new MyChromeClient());
private class MyChromeClient extends WebChromeClient {
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
String message = consoleMessage.message() + " -- line " + consoleMessage.lineNumber();
switch (consoleMessage.messageLevel()) {
case ERROR:
logErrorMessage(message);
break;
default:
logInfoMessage(message);
break;
}
return true;
}
private void logInfoMessage(String message) {
Log.i("JSTag", message);
}
private void logErrorMessage(String message) {
Log.e("JSTag", message);
}
}
From your JavaScript you would then call for example: console.log('check my value:' + (ele != null)). More info on this here.
Looking at your JavaScript code, I can't understand to what points this.innerHTML.

Inject something to ASP MVC Result

In my project I need to add functionality, that show infobox in right top corner of page, when client save something. Everything works fine when save operation do redirect to another page in my solution.
Client run save action:
[SaveAction] //my own action filter to show info box
public ActionResult Details(int id, FormCollection form)
{
var pojazd = PojazdRepo.GetById(id);;
if (UpdateAndSave(pojazd, form))
{
return RedirectToAction("Index");
}
else
{
return View(GetDetailsViewModel(id, true));
}
}
Now my action filter test that ModelState.IsValid is true then add something to TempData:
public class SaveActionAttribute : ActionFilterAttribute
{
private bool test;
private bool isAjax;
public override void OnActionExecuted(ActionExecutedContext ctx)
{
test = ctx.Controller.ViewData.ModelState.IsValid;
isAjax = ctx.HttpContext.Request.IsAjaxRequest();
base.OnActionExecuted(ctx);
}
public override void OnResultExecuting(ResultExecutingContext ctx)
{
if (test)
{
if (isAjax) ctx.Controller.TempData["ActionPopUp"] = "";
else ctx.Controller.TempData["ActionPopUp"] = "save";
}
base.OnResultExecuting(ctx);
}
}
And my Site.Master run script if TempData["ActionPopUp"] = "save":
<script type="text/javascript">
$(document).ready(function () {
var test = '<%: TempData["ActionPopUp"] %>';
if (test != '') SaveSuccessPopUp(test);
});
</script>
As mentioned, this solution works fine, when controller make Redirect and Site.Master is loaded again, my problem is, how to inject SaveSuccessPopUp() function to action result, when Action was called by AJAX and return something, what don't reload page and don't run Site.Master $(document).ready code block.
Nice question.
You need to probably work with partial view here. I mean if your request is an ajax request, append the TempData again and the TempData will be outputted inside the partial view.
How will you send that partial view output as chunk of html?
I have a blog post about how you can send the partial view as string. The topic is different but you will get the idea:
http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views
Here is an example:
[HttpPost]
public ActionResult toogleIsDone(int itemId) {
//Getting the item according to itemId param
var model = _entities.ToDoTBs.FirstOrDefault(x => x.ToDoItemID == itemId);
//toggling the IsDone property
model.IsDone = !model.IsDone;
//Making the change on the db and saving
ObjectStateEntry osmEntry = _entities.ObjectStateManager.GetObjectStateEntry(model);
osmEntry.ChangeState(EntityState.Modified);
_entities.SaveChanges();
var updatedModel = _entities.ToDoTBs;
//returning the new template as json result
return Json(new { data = this.RenderPartialViewToString("_ToDoDBListPartial", updatedModel) });
}
RenderPartialViewToString is a controller extension. you can find the the complete code for that from below link:
https://bitbucket.org/tugberk/tugberkug.mvc/src/6cc3d3d64721/TugberkUg.MVC/Helpers/ControllerExtensions.cs
After you have your html back on the client side code, append it you DOM and work on it. Animate it, show/hide it, do whatever you need with it

Categories