Pass Go function to html/js button "onclick" response - javascript

I am using Go's "net/http" package to pass data between the html and the backend in Go. For example, we can used the location of an image like this:
<img src={{.MyPicture}} width=200 height=auto/>
We can do the same thing to pass in functions to the html and call them:
{{if .MyBool}}
{{.MyFunction}}
{{end}}
Now my question is: how do I set the response of a button to call my function? I would expect this to work, but it doesn't:
<button onclick={{.ShowMoreLinks}}>Show more!</button>
I get "[js] Declaration or statement expected." I've tried wrapping it in a script (both inline and in the header), but neither of these seem to work. JS can't handle the passed in variable.

Actually, you're using Go's template mechanism to prepare the HTML that you send to the browser. This only fills in placeholders and ultimately only produces a string (in this case HTML) that will be sent over the network to the browser for interpretation. It's the browser that can only handle interactivity with the user via events such as "onclick". Furthermore, these events have to be Javascript code, like a JS expression or a function call:
onclick="jsFunction()"
You could make your Go template provide the function to be called in the placeholder:
onclick="{{.JSFuncCall}}"
Here ".JSFuncCall" would have to evaluate to some JS function name (and the parentheses to make the call) that you must have defined in your JS client-side code. That Javascript function could then make an XHR call to the server at some specific URL that triggers a Go handler, runs the Go code you want to run, and then returns a response that you can then handle back in the JS function.

Related

I cannot do anything from the AWS.Request.send() callback

I'm using the AWS S3 Javascript SDK and i am trying to do some operations as using external functions or append some HTML code in a HTML div etc. all these things from my callback send() but nothing happens i get errors whereas i don't have any problem when i'm making these stuffs outside that send().
I have absolutely to write some specific code involving external functions inside this send() that just can't be made outside . How to resolve this issue ?
You can have a glance on the AWS.request.send() here

calling PhP function in JavaScript returns white screen

Before anyone complains: i know that javascript is clientside and php is serverside.
I need to call a php-function within my javascript (both in the same file). i used
document.write("<?php add(); ?>");
which calls the function from php like it should. the main problem is that the page turns white (like when i call echo "";), which should not happen. i tested with an completly empty test();, ending up in the same problem.
to answer the question why i want to call the function: i need to update a sql table on pressing a key. as far as i know its impossible to make a keylistener in php and too unsafe to use sql in javascript.
greetings and thx for help
When you use document.write at any other moment than during page load, it will wipe out your document and replace it with whatever you pass as argument. From your question it seems you run this code in an event handler, like for the keypressed event. In this case, it is expected behaviour of document.write that your page turns white. Don't use it there.
What you need to do is identify where in your document you want to insert content, more precisely, at which element, and provide content to it. You can use several methods for this, like .innerHTML, but not document.write.
Secondly, you should understand that when you pass an argument that has php generated values in it, that these arguments are calculated at the moment php generates the page, and not when the corresponding javascript executes. At that latter moment no call to php takes place, as php already did it's job during the generation of the page.
If you want to execute a php function at the moment of an event in the browser, you should issue an http request to the server. This can be done by submitting a form, by navigating to a different url, or by issuing an ajax call. In these cases the server receives a request, and php can be executed, which will again generated content and send it back to the browser.
You can find example ajax code on the internet, for example here.

Get return value from JS code to C#

I want to get the answer of a window.prompt() alert box through the C# Code Behind file. It's just a one-liner of JavaScript code, so I thought I could even execute it from the Code Behind file. It doesn't really matter to me whether it's a <script> tag in the .aspx file or executed through the .aspx.cs file.
I thought of having the script executed (called from the C# part) and then having the return value assigned to a certain not visible field, but is there any better way to do it?
The obvious way would probably go something like this:
.aspx file:
<script>
function foo() {
document.getElementById('MyFieldID').value = window.prompt('Answer this question:', '');
}
</script>
.aspx.cs file:
////////////////////////////////////////////////
//MyFieldID.Text now contains whatever I want//
//////////////////////////////////////////////
What do you say? Is there any better way?
Better way is always opinion based. What I'd say is you have a few options, all depend on what you're doing. HTTP and ASP.NET provide us a few means of sending data to the server, there are 3 main ones before HTML5:
Query string
Form values
AJAX calls
If you're redirecting the user to a new page after they answer the prompt, you can just send them to yournewurl.aspx?promptAnswer=*whatever*
If you're doing a postback, then you can use a form value (this looks like what you're doing in your example). You can put an <asp:HiddenField> on the page and populate it from JavaScript before submitting the form.
If you need just the prompt response, but are not attempting to reload the page, you can make an AJAX call that sends the variable to the server (this still uses #1 or #2 to send the data, it just does it without reloading the page).
Which of those three options works best depends on your implementation. However, your solution should work just fine. However, since the control you'd likely be using to stuff the value into is a HiddenField it would be in MyFieldID.Value not MyFieldID.Text. The only other thing you have to deal with is if your MyFieldID is nested in some other controls (like a ContentPlaceHolder) such that the ClientID has naming containers pretended to it so it's really something like ContentPlanceHolder1_MyFieldID when accessed from JavaScript.

Listen to Response on HTML Form embedded in GWT View?

I have a HTML like the following:
<div>
<form>
<input type="text" />
<button class="sendForm" value="Send form" />
</form>
</div>
<script>
// post the form with Jquery post
// register a callback that handles the response
</script>
I use this type of form a lot with a JavaScript/JQuery overlay that displays the form. That could be handled for example with plugins like FancyBox. I use Fancybox for Ajax content.
I also want to use this form embedded into a GWT view. Lets assume that the for cannot be created on client side because it has some server based markup language inside to set up some model data.
If I want to use this form in GWT I have to do the following. Tell GWT the form request url and use a RequestBuilder to query the html content of this form. Then I can insert it into a div generated by GWT. So far so good.
Problem:
When the user hits the send button the response is handled my the JQuery callback that is inside the script under the form.
Is there a way to access this callback from within GWT?
Is there a way to overwrite the JQuery send action? Since, the code is HTML and comes from the server I cannot place ui-binder UiFields inside to get access to these DOM elements.
I need to get the response if the submitted form accessible to GWT.
Is there a way how I can achieve this with JSNI?
Answers to each question:
1 Is there a way to access this callback from within GWT? actually you cannot modify the callback itself, what you can do from GWT is to call any jquery method, thus you can unbind any previous added handler, and set yours.
//NOTE: not wrapping code in $entry() to make a clearer code.
private static native unbindForm() /*-{
// remove all jQuery handlers added previously to my form
$wnd.$("my_form_selector").off();
// add a new handler for the submit event
$wnd.$("my_form_selector").on("submit", function(event) {
event.preventDefault();
$wnd.$(this).post(url, ...).done(function(data) {
// Use JSNI to call a GWT method
#.com.example.MyClass.handleFormResponse(*)(data);
// NOTE: that you can use a star instead of having to write parameter
// types, when you only have one method signature in your class.
});
}
}-*/
// handle the form response in GWT
public static void handleFormResponse(String data) {
// handle form response in GWT
}
Another thing you can do with GWT, is to wrap your form in a FormPanel and use specific widget methods to set a handler and read the response. But I think this is not what you are asking for.
2 Is there a way to overwrite the JQuery send action Yes, using JSNI to ask jQuery to unbind previously set events. See code in #1.
3 I need to get the response if the submitted form accessible to GWT. You have to include in the jquery.post callback some code to call GWT static methods (you can use-non static as well but this way is easier) this is also JSNI. See code in #1.
4 Is there a way how I can achieve this with JSNI? Of course, JSNI is the way to interact with handwritten javascript from GWT.
Aditional Notes:
GWT is designed to build RIA apps with very optimized js code. I know each one has their reasons for using external libraries, but adding 3party javascript to your app is against the main goals of gwt compiler remove death code and optimize output. If you like jquery like syntax and features for GWT I recomend to use gwtquery, which has been fully written in gwt, hence the compiler will include just the code you use.
Writing JSNI is a source of mistakes difficult to handle in the debugger. So I recommend to use gwt-exporter to populate java methods/classes or gwtquery to call external javascript. See these post I wrote some time ago: Pass value from GWT to Javascript via JSNI and Calling GWT Java function from JavaScript
Javascript => GWT and GWT => javascript values passing both can be done using JSNI . Please have a look here for more information about JSNI

AJAX + dynamically adding java script function to the page

I am loading a portion of page using AJAX calls, which may contain script functions defined in them . Which are attached with the controls being loaded with different events. Now the problem is that when those events triggered i got the error "object not found" which indicate the function is not found/defined. While using Firebug i can see that the function is defined and available. So how can i make sure that browser can find the respective function.
I tried but either i am missing some thing or either its not working, Here is what i am doing
Page
--->Partial View A
----->Partial View B
Now Page Loads Partial A with Ajax Calls which further loads Partial B with Ajax Calls.Both Partial A & B contains few java script function that logically only associated with them not with master page.
The pages loads fine except the functions could not execute as "Object Not Found" comes in.
You should define functions using this syntax:
myFunction = function(foo) {}
not this syntax
function myFunction(foo) {}
The second form won't work when eval()'d (which is probably what's happening)
If you are using a framework or library you have to set a parameter in order to evaluate the script present in the response of the ajax request. It's usualy called evalScripts
evalScripts:true
You can also use the callbacks (success/error) of the request to trigger the events, so that it's easier to keep the code in one place and to avoid situations like this.
If you are using plain javasciprt and the XmlHttpObject, then you have to manually find all the script tags in your response and then eval() them.

Categories