Trying to get a clear button to work for my simple calculator. It should clear three text boxes: the first number (fn), second number (sn), and the total (tn). I am using a web api for this - everything works except for the clear button. I am uncertain on how to write the Clear function correctly - any guidance would be appreciated. I think I am going in the wrong direction with the controller function. Below I listed my HTML, then my Controller, and then my model for just the clear function.
HTML:
'''
function clr() {
// clear function goes here
$.ajax({
url: "/api/calc/clr/" + fn.value + "/" + sn.value,
cache: false,
success: function (html) {
tn.value = html
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
<input type="reset" value="Clear Results" onclick="clr();" />
Controller code:
[Route("api/calc/clr/{paramOne}/{paramTwo}")]
public IHttpActionResult Delete(float paramOne, float paramTwo)
{
return oCalc.Clr(paramOne, paramTwo);
}
Model Code:
public float Clr (float fn, float sn)
{
return ();
}
'''
You don't need to call API for any of the client side processing. You can clear out the values using following code
<input type="text" id="n1" value="10" />
<input type="text" id="n2" value="20" />
<input type="button" onclick="clr()" />
JavaScript code
<script>
function clr() {
// clear function goes here
$("#n1,#n2").val("");
}
</script>
Related
Hi everyone i'm new to spring MVC so i have little idea about the framework. All I'm trying to do is refresh a div in my view with items filtered by a hibernate query, which prints correctly to standard out.
For some reason I'm not aware of I get a 500; Internal server error when i try a get request via ajax.
I changed the return type in the controller, my original idea was to use the default index controller with an optional parameter.
View:
<div id="itemListContainer">
<c:if test="${!empty items}">
<c:forEach items="${items}" var="item">
<c:url value="/showImage.htm" var="url">
<c:param name="id" value="${item.id}" />
</c:url>
<div id="${item.id}" class="col-lg-2 col-md-3 col-xs-6 thumb">
<img class="img-responsive" src="${url}" alt="${item.name}">
</div>
<input id="name_${item.id}" type="hidden" value="${item.name}">
<input id="name_${item.id}" type="hidden" value="${item.review}">
</c:forEach>
</c:if>
<c:if test="${!empty itemList}">
<h1>Nothing found</h1>
</c:if>
</div>
JS File
function filterItems(value) {
$("#itemListContainer").empty();
$.ajax({
method: "GET",
//dataType: "json",
url: "filterItems.htm",
data: {
type: value
},
success: function (data) {
if (data) {
$("#itemListContainer").html(data);
} else {
console.log(xhr.responseText);
alert("failure");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}
Controller:
#RequestMapping(value = "/filterItems", method = RequestMethod.GET)
public #ResponseBody List<Item> filterItems(#RequestParam(value = "type", required = false) String type) {
List<Item> items = new ArrayList<Item>();
try {
items = itemDao.getItems(type);
} catch (Exception e) {
e.printStackTrace();
}
return items;
}
Any help will be greatly appreciated. Thanks in advance!!
Once again, when it comes my little experience with hibernate, the error has nothing to do with Javascript, controller o DAO but with entity mapping.
My Item entity had an association with a User entity, and had to specify between lazy and eager loading of the association. In my case it was solved by adding lazy="true" to my xml file.
I'm creating a JSP/Servlet web application and I'd like to upload a file to a servlet via Ajax. How would I go about doing this? I'm using jQuery.
I've done so far:
<form class="upload-box">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error" />
<input type="submit" id="upload-button" value="upload" />
</form>
With this jQuery:
$(document).on("#upload-button", "click", function() {
$.ajax({
type: "POST",
url: "/Upload",
async: true,
data: $(".upload-box").serialize(),
contentType: "multipart/form-data",
processData: false,
success: function(msg) {
alert("File has been uploaded successfully");
},
error:function(msg) {
$("#upload-error").html("Couldn't upload file");
}
});
});
However, it doesn't appear to send the file contents.
To the point, as of the current XMLHttpRequest version 1 as used by jQuery, it is not possible to upload files using JavaScript through XMLHttpRequest. The common workaround is to let JavaScript create a hidden <iframe> and submit the form to it instead so that the impression is created that it happens asynchronously. That's also exactly what the majority of the jQuery file upload plugins are doing, such as the jQuery Form plugin (an example).
Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JavaScript disabled (as you have now...), like below:
<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
Then it's, with the help of the jQuery Form plugin, just a matter of
<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
As to the servlet side, no special stuff needs to be done here. Just implement it exactly the same way as you would do when not using Ajax: How can I upload files to a server using JSP/Servlet?
You'll only need an additional check in the servlet if the X-Requested-With header equals XMLHttpRequest or not, so that you know how what kind of response to return for the case that the client has JavaScript disabled (as of now, it is mostly the older mobile browsers which have JavaScript disabled).
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
// Return an Ajax response (e.g. write JSON or XML).
} else {
// Return a regular response (e.g. forward to JSP).
}
Note that the relatively new XMLHttpRequest version 2 is capable of sending a selected file using the new File and FormData APIs. See also HTML5 drag and drop file upload to Java Servlet and Send a file as multipart through XMLHttpRequest.
Monsif's code works well if the form has only file type inputs. If there are some other inputs other than the file type, then they get lost. So, instead of copying each form data and appending them to FormData object, the original form itself can be given to the constructor.
<script type="text/javascript">
var files = null; // when files input changes this will be initialised.
$(function() {
$('#form2Submit').on('submit', uploadFile);
});
function uploadFile(event) {
event.stopPropagation();
event.preventDefault();
//var files = files;
var form = document.getElementById('form2Submit');
var data = new FormData(form);
postFilesData(data);
}
function postFilesData(data) {
$.ajax({
url : 'yourUrl',
type : 'POST',
data : data,
cache : false,
dataType : 'json',
processData : false,
contentType : false,
success : function(data, textStatus, jqXHR) {
alert(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert('ERRORS: ' + textStatus);
}
});
}
</script>
The HTML code can be something like following:
<form id ="form2Submit" action="yourUrl">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br>
<input id="fileSelect" name="fileSelect[]" type="file" multiple accept=".xml,txt">
<br>
<input type="submit" value="Submit">
</form>
$('#fileUploader').on('change', uploadFile);
function uploadFile(event)
{
event.stopPropagation();
event.preventDefault();
var files = event.target.files;
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
postFilesData(data);
}
function postFilesData(data)
{
$.ajax({
url: 'yourUrl',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
//success
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('ERRORS: ' + textStatus);
}
});
}
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileUploader"/>
</form>
This code works for me.
I used Commons IO's io.jar, Commons file upload.jar, and the jQuery form plugin:
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
<form id="upload-form" class="upload-box" action="upload" method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "../../web/Images/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
I've integrated reCAPTCHA and it is working fine, except for when the users are too quick to click the Submit button right after checking the "I'm not a robot" checkbox. It takes quite some time for reCAPTCHA to register the user action via Ajax, and if they click on Submit too quickly, the g-recaptcha-response is missing, and the validation fails.
Hence my question: how to I grey out the Submit button until g-recaptcha-response value is available?
<form id="capform" action="/captchaverify" method="POST">
<div class="g-recaptcha" data-sitekey="..."></div>
<p>
<input id="capsubmit" type="submit" value="Submit">
</form>
I ended up using the data-callback attribute as described in the documentation:
<form action="/captchaverify" method="POST">
<div class="g-recaptcha" data-sitekey="..." data-callback="capenable" data-expired-callback="capdisable"></div>
<p>
<input id="capsubmit" type="submit" value="Submit">
</form>
JavaScript (mootools-based, but the general idea should be clear):
function capenable() {
$('capsubmit').set('disabled', false);
}
function capdisable() {
$('capsubmit').set('disabled', true);
}
window.addEvent('domready', function(){
capdisable();
});
Here's an example that begins with the submit button disabled, and enables it once the callback is received from reCaptcha. It also uses jquery validate to ensure the form is valid before submitting.
var UserSubmitted = {
$form: null,
recaptcha: null,
init: function () {
this.$form = $("#form").submit(this.onSubmit);
},
onSubmit: function (e) {
if ($(this).valid()) {
var response = grecaptcha.getResponse();
if (!response) {
e.preventDefault();
alert("Please verify that you're a human!");
}
}
},
setupRecaptcha: function (key) {
UserSubmitted.recaptcha = grecaptcha.render('recaptcha', {
'sitekey': key,
'callback': UserSubmitted.verifyCallback
//'theme': 'light'//,
//'type': 'image'
});
},
verifyCallback: function (response) {
if (response) {
$(".visible-unverified").addClass("hidden");
$(".hidden-unverified").removeClass("hidden");
}
}
};
I call setupRecaptcha from the page with a named function that's part of the js include.
<script>
var recaptchaLoader = function () {
UserSubmitted.setupRecaptcha("yourkey");
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaLoader&render=explicit" async defer></script>
You could simplify this. I use it in a multi-tenant application with different keys, and UserSubmitted is actually part of a larger library. You can't usenamespaces (UserSubmitted.somefunction) as the onload param either (to my knowledge).
I have a Modal that opens & gives User options to check some checkboxes. When the User checks checkboxes of his choice. I want to send all the values of checkboxes & call AJAX method.
I want to send values of selected checkboxes to the Controller method.
Here is my Code :-
// These are dynamic checkboxes - This is just an e.g
<input type="checkbox" name="name" value="Code">
<input type="checkbox" name="name" value="Code1">
<input type="checkbox" name="name" value="Code2">
<input type="checkbox" name="name" value="Code3">
// onClick event of Button
jq.get('/Controller/getData', function (data) {
jq('#placeHolder').html(data);
});
// Controller
[HttpGet]
public ActionResult getData()
{
return PartialView("_pagepartial");
}
To get the values of the checked checked boxes and add to an array
var array = [];
$('input:checked').each(function() {
array.push($(this).val());
}
And to pass to you controller
$.ajax({
type: "GET",
url: '#Url.Action("getData", "Controller")',
dataType: "html",
traditional: true,
data: { values: array},
success : function (data) {
$('#placeHolder').html(data);
}
});
assuming you controller method is
public ActionResult getData(string[] values)
{
// return some partial view based on values
}
Have a good day.
I am doing a select all checkbox to delete selected posts. I am able to get the result in the jquery but I am not sure how to use that result to process in my Codeigniter Controller. Maybe someone can enlighten me. Thanks!
View File:
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="1" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="2" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="3" />
<button id="delete_selected" name="delete_selected" class="btn btn-danger btn-small" value="" onClick="return confirm('Delete selected posts?')"><i class="icon-trash icon-white"> </i> Delete Selected</button>
JQuery:
//GET SELECTED POSTS/PAGES FOR DELETION
$("#delete_selected").click(function(event) {
/* stop form from submitting normally */
event.preventDefault();
var values = new Array();
$.each($('input[name="delete_selection[]"]:checked'), function() {
var delete_selection = $(this).val()
console.log(delete_selection);
});
});
Controller:
public function post_delete(){
//HOW TO GRAB THE RESULT FROM THE JQUERY?
//I KNOW IT SHOULD BE IN AJAX BUT NOT QUITE SURE HOW TO DO IT.
$id = $this->input->post('delete_selection');
for( $i=0; $i<sizeof($id); $i++) :
$this->posts_model->delete_post_selection($id[$i]);
endfor;
$data['message_success'] = $this->session->set_flashdata('message_success', 'You have successfully deleted your selected posts.');
redirect('admin/posts/posts_list', $data);
}
Model:
//MULTIPLE DELETE
function delete_post_selection($id) {
$this->db->where_in('post_id', $id)->delete('posts');
return true;
}
Your thinking is wrong, the controller isn't gonna 'grab' the values. But javascript is going to post to the controller
Assuming you put your html inside a form you could do something like this:
view:
<form action="/post_delete">
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="1" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="2" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="3" />
<button id="delete_selected" name="delete_selected" class="btn btn-danger btn-small" value=""><i class="icon-trash icon-white"> </i> Delete Selected</button>
</form>
JS:
$('#delete_selection').click(function(e){
if(!confirm('Delete?')) return;//ask user if they're sure
//stop default form submitting from happening because
//we'll use ajax
e.preventDefault();
var form = $(this).closest('form');//get the parent form
$.ajax({
url: form.attr('action'),//get url to send it to
type: "POST",
data: form.serialize(),//get data from the form
success: function(){
//do something with success
}
error: function(){
//do something with error
}
});
And now you can use the data in your controller by accessing $_POST try
var_dump($_POST);
to see what has been posted
I am not sure if this is the correct way as it POST repeatedly but does the work so far.
In my JS:
//GET SELECTED POSTS/PAGES FOR DELETION
$("#delete_selection").click(function(event) {
if(!confirm('Delete selected posts?')) return false;//ask user if they're sure
/* stop form from submitting normally */
event.preventDefault();
$.each($('input[name="delete_selection[]"]:checked'), function() {
$.ajax({
type: "POST",
url: 'post_delete_selection',
data:
{ selected: $(this).val() },
success: function(data){
setTimeout(function () {
window.location.href = window.location.href;
}, 1000);
$('#ajax_message').show().html('Successfully deleted.');
},
});
});
});
My Controller:
public function post_delete_selection(){
$selectedIds = $_POST['selected']; //THIS GRABS THE VALUES FROM THE AJAX
$this->posts_model->delete_post_selection($selectedIds);
}
My Model:
function delete_post_selection($selectedIds) {
$this->db->where_in('post_id', $selectedIds)->delete('posts');
return true;
}