Pass to dwr function string stored in html input - javascript

I'm trying to pass to my dwr function the content of an html input of my page. The content of this input is changed programmatically by the user.
If i pass to my DWR method an hard coded string, the method succedes. The problem is when i give the method the content of the input. DWR just retrieves error.
The DWR function is:
function myDWRFunction(str) {
readyProxyJS.javaImplementatedFunction(str, function (data) {
$('#profileImage').attr('src', 'data:image/jpg;base64,'.concat(data));
});}
And this is the content of my jsp page (in other words, from where i'm calling the dwr method):
<input type="text" name="dynamicContent"/>
<input id="bula" type="button" value="READY" onclick="myDWRFunction(document.getElementsByName('dynamicContent'[0].value;)"/>
i'm not going to post the rest of the DWR implementation since, as i've written before, if i pass an hard-coded string to the method (example: onclick="myDWRFunction('thisIsMyHardCodedString')) , all works fine.
Can anyone help?

Related

get value from textarea using JS and pass it without page reload to server (jsp)

I am using this piece of code to display a TextArea to my JSP page with a button calling two functions after onclick event.
<textarea id="textarea"></textarea>
<button style="float: right;" onclick="jQuery('#reDiv').load(' #reDiv'); doSth();">Get Text</button>
function 1:
<div id="reDiv"><%=new java.util.Date().toString()%></div>
function 2:
<script>
function doSth() {
var text = $("#textarea").val(); //value of textarea
<%=text%> //error
}
</script>
Function 1 works fine.
In function 2 I am trying to pass the value, which I just got from the TextArea, to my Server without reloading the page. My aim later is to call a method and display the data without refreshing the page.
I know the error is that JS is Client-Side and JSP is server side.
But how can I solve this?
It's really bad practice to use scriptlets in your jsp (these things <% %>). It was replaced by EL and JSTL.
But yeah the server runs the java in your jsp page before it gets sent to the client. And the javascript runs on the client side after the java has already been executed. On top of that, you cannot directly access javascript variables with scriptlets. You can however do it the other way round but it won't be useful for you in this case.
You mentioned you want to pass the value from your textarea to the your server without your page reloading. This is what AJAX is for.
<script>
function doSth() {
var text = $("#textarea").val(); //value of textarea
//<%=text%> //error
sendToServer(text);
}
function sendToServer(text){
var params = {
textarea: text
};
$.post("YourServletUrl", $.param(params), function(response) {
// ... handle response here if you have any..
});
}
</script>
Then in the doPost method of your servlet which has a url mapping of YourServletUrl you just do this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
String textarea= request.getParameter("textarea");
System.out.println(textarea);
}

JavaScript to PHP form, based on user input

I have a simple form on my homepage (index.php), that takes one user input.
<form action="/run.php" method="POST" target="_blank"
<input type="text" name="userinput">
<button type="submit">Run!</button>
</form>
That input is then passed to run.php where the content is displayed and inserted into a MySQL database.
However, I need to run JavaScript functions on that user input, and then input the results (from the JavaScript function) into the database (so passing the value from JavaScript to PHP).
I originally had the JavaScript in the run.php, which worked for calculating and displaying the value, but I was unable to pass the value to PHP to insert into the database.
From what I've read, you can't pass JavaScript values to PHP on the same page, as it requires some sort of POST or GET, so I'm attempting to run the JavaScript functions on the homepage index.php and then use a hidden input field to POST the value to the run.php file.
<input id='hidden_input' type='hidden' name='final-calc' value='random(userinput)' />
Where the function is a JavaScript Promise:
function random(userinput) {
....
.then(function(userinput) { // Function needs to use the userinput from the form
// calculations
return X //(X being any random value)
}
}
The two problems I'm running into is that:
I can only get the userinput value after the user enters a value and submits the form, so I don't believe I can pass that userinput value into the JavaScript function and still POST the returned value?
The JavaScript function is an asynchronous Promise, but apparently, this might not have an effect - so it may not be a problem.
The key here is AJAX. You have to retrieve the userinput using plain JS, make any calculations needed and then send the results to your PHP script. I left a fiddle: https://jsfiddle.net/k5xd54eu/1/
<input type="text" id="userinput" name="userinput"/>
<button onclick="inputhandler();">TEST</button>
<script>
function inputhandler() {
var text = document.getElementById('userinput').value;
alert(text);
/*DRAGONS BE HERE*/
/*THEN*/
/*USE AJAX HERE TO PASS THE RESULTS TO PHP SCRIPT*/
}
</script>
I'm not explaining how to implement the AJAX call to send the results, mainly because it's a matter of taste too. For example you can use plain JS or a library such as jQuery (which is my personal preference, since it's very clean and easy). Take a look here:
http://api.jquery.com/jquery.ajax/
and here:
https://www.w3schools.com/jquery/jquery_ajax_intro.asp
for more information.
EDIT: Since I've mentioned AJAX, it would be more correct to include some code. So this is what I generally use for simple POSTs (it's based on the jQuery library so be careful to include it):
var url = 'ajaxhandler.php';
var stuff = '1234abcd';
$.ajax({
type: "POST",
url: url,
data: {stuff: stuff},
success: function (data) {
/*Do things on successful POST*/
}
});

Different JSON pages

i have 2 web pages containing same JSON string. one work fine with java-script function.but other one is completely not working.the only different between these two is url.
here is the page that is working fine with the js function.
(http://jsfiddle.net/echo/jsonp/?test=some+html+content&callback=?)
here is the one that is not working with the js function.
(http://sanjeewa88.byethost31.com/EMPStore/test_json.html)
here is my java-script function
function doJSON() {
$.getJSON('http://jsfiddle.net/echo/jsonp/?test=some+html+content&callback=?', function (data) {
$('#allemployees').append("<li>" + data.test+ "</li>");
});
}
what's wrong with second page and how i fix it to access that page through js function.
PS-
i want to display these data in a listview. first one is displaying that remote data on the listview.but second one which having same json string is not displaying anything.
On the page you provide the json you have to accept a para callback and use this parameter to generate the function name.
look what's happen when you call jsfiddle callback with an other name:
http://jsfiddle.net/echo/jsonp/?test=some+html+content&callback=poney
give:
poney({"test": "some html content"});
You have more information here: jQueryDoc
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

passing dynamic parameters in script.aculo.us

I want to pass dynamic values inside parameters of script.aculo.us for auto suggestion in my jsp page
Below is my code where i want to get the value of checkbox and pass it to server. But in server side jsp its printing as it is ( i.e instead pf checkbox value its printing document.getElementById("mgmtsystem").checked )
<div class="auto_complete" id="object_name_auto_complete"></div>
<script type="text/javascript">
new Ajax.Autocompleter('<%=name%>', 'object_name_auto_complete', '<%=request.getContextPath()%>/component/ajax_introdata', { parameters: 'suggEnable= document.getElementById("mgmtsystem").checked' })
</script>
In above code i'm trying to send the value of document.getElementById("mgmtsystem").checked but its just passing it as same instead its value
If you copied your javascript into the question as it is on your code - this is why
This code does not let document.getElementById(....) get evaluated and treats it as a string
{ parameters: 'suggEnable= document.getElementById("mgmtsystem").checked' }
Try this
{ parameters: 'suggEnable='+document.getElementById("mgmtsystem").checked }
Or better yet use the utility methods built in to PrototypeJS
{ parameters: 'suggEnable='+$("mgmtsystem").checked }

ASP.Net MVC Upload file using jquery-form plugin and returning a Json result

I'm trying to use the JQuery Form plugin (http://jquery.malsup.com/form/) to upload a file and a couple extra fields from my view, and I want the action method to return a Json result to the javascript callback.
Currently, the ActionMethod is called correctly (I can process the files and fields from the form) but when I return the Json result the browser tries to download it as a file (If I download the file and see its contents, it's the JSON content that I am returning.).
This is my form:
<form id="FormNewFile" action="#Url.Content("~/Home/AddFile")" method="post" enctype="multipart/form-data">
<input type="hidden" name="eventId" value="25" />
<input type="text" name="description" />
<input type="file" name="fileName" />
<input type="submit" value="Send!" />
</form>
This is my javascript:
<script type="text/javascript">
$(function () {
$("#FormNewFile").ajaxForm({
dataType:'json',
success:processJson
});
});
function processJson(a,b) {
alert('success');
}
</script>
And this is my ActionMethod:
[HttpPost]
public ActionResult AddFile(long? eventId, string description)
{
int id = 5;
return Json(new {id});
}
The name of the file the browser tries to download is something like AddFilee87ce48e, with the last 8 characters being random hexadecimal characters.
And finally, the content of the file downloaded is:
{"id":5}
And the processJson function in javascript never gets called.
I googled a lot and the only thing that seems to work is returning the JSON result as a "Content" result from the action method, I think that's the approach I'm gonna take, but I still want to know why this isn't working?
Any ideas?
What I ended up doing was manually serializing the object I wanted to return as JSON, if I do this then the response won't have a header, therefore it will be handled by javascript instead of the browser. I used this helper method:
public static ActionResult JsonPlain(object x)
{
var result = new ContentResult();
result.Content = new JavaScriptSerializer().Serialize(x);
return result;
}
Hope this helps someone else
That's normal behavior. Excerpt from the documentation:
Since it is not possible to upload
files using the browser's
XMLHttpRequest object, the Form Plugin
uses a hidden iframe element to help
with the task. This is a common
technique, but it has inherent
limitations. The iframe element is
used as the target of the form's
submit operation which means that the
server response is written to the
iframe. This is fine if the response
type is HTML or XML, but doesn't work
as well if the response type is script
or JSON, both of which often contain
characters that need to be repesented
using entity references when found in
HTML markup.
To account for the challenges of
script and JSON responses, the Form
Plugin allows these responses to be
embedded in a textarea element and it
is recommended that you do so for
these response types when used in
conjuction with file uploads. Please
note, however, that if there is no
file input in the form then the
request uses normal XHR to submit the
form (not an iframe). This puts the
burden on your server code to know
when to use a textarea and when not
to. If you like, you can use the
iframe option of the plugin to force
it to always use an iframe mode and
then your server can always embed the
response in a textarea. The following
response shows how a script should be
returned from the server:
This means that if you want to return JSON you need to wrap it in a <textarea> tags on your server. To achieve this you could write a custom action result deriving from JsonResult and wrapping the generated JSON inside those tags.
The following blog post, jQuery File Upload in ASP.NET MVC without using Flash, addresses the issue of wrapping the response in a textarea as described by Darin Dimitrov's answer.
Have a look at the action on your form tag:
action="#Url.Content("~/Home/AddFile")"
The only usage I've seen of this is in script tags such as :
<script language="javascript" src="<%=Url.Content("~/Scripts/jquery-1.3.2.js")%>
The correct reference for the action would be:
action="/Home/Addfile"
While I am not too sure about the explanation as to why but the UrlHelper:
Url.Content("~/somepath")
converts a virtual path to a absolute path and expects a physical file such as a javascript.
The json result might be being returned as a file download because the mvc framework is expecting a file download of some description. Just as:
<a href="<%= Url.Content("~/_docs/folder/folder/document.pdf") %>">
document.pdf</a>
would download or display a physical pdf file.
My solution using json and no specific javascript:
/// <summary>
/// A result to use in combination with jquery.ajax.form when we want to upload a file using ajax
/// </summary>
public class FileJsonResult : JsonResult
{
public JsonResult Result { get; set; }
public FileJsonResult(JsonResult result):base()
{
this.Result = result;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write("<textarea>");
this.Result.ExecuteResult(context);
context.HttpContext.Response.Write("</textarea>");
context.HttpContext.Response.ContentType = "text/html";
}
}

Categories

Resources