I want to send data from a form to a Servlet using Ajax, but when I made a check about the data that was being serialized using the jQuery .serialize() function, I noticed that it wasn't taking the value of the file field. In a previous test I got an error with a message like this: the request was rejected because there was no multipart data found
The following is the form HTML code:
<form id="frmCrcnCaso" class="form-horizontal" enctype="multipart/form-data">
<input id="txtNoVlt" name="txtNoVlt" type="text" class="form-control">
<input id="txtNmr" name="txtNmr" type="text" class="form-control">
<input id="txtFchOfc" name="txtFchOfc" type="date" class="form-control">
<input id="flAcvAjt" name="flAcvAjt" type="file" class="form-control"/>
</form>
<button id="btnGuardar" type="button" class="btn btn-lg btn-primary">
Guardar
</button>
And this is the javascript code:
$("#btnGuardar").on("click",function(){
ValidarGuardado();
});
function ValidarGuardado(){
...
// Activar el guardado
Guardar();
}// </editor-fold>
function Guardar(){
$(...).append("...
<button id='btnGdrCaso' type='button' class='btn btn-primary'><i class='fa fa-check'></i> Guardar</button>\n\
...");
$(...).modal();
$("#btnGdrCaso").on("click",function(){
...
var datosCaso = $("#frmCrcnCaso").serialize();
...
$.ajax({
url: "GuardarCaso" // Servlet name,
type: "POST",
contentType : false,
data: datosCaso,
success:function(r){
if(r === "1"){
...
}else if(r === "2"){
...
}else{
...
}
},
error:function(r){
...
}
});
});
}
Related
I am trying to insert a record into MySQL database using HTML form. I am using AJAX to call web services in Java. But it is not working. It gives an alert saying false. When I tried with POSTMAN it works fine. But using AJAX it's not working.
Can anybody help me? Thanks in advance.
Code in Add.jsp
<body>
<form id="submit">
Username:<br>
<input type="text" name="username"><br>
Email:<br>
<input type="email" name="email"><br><br>
Password:<br>
<input type="text" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "http://localhost:8080/WebService/webresources/users/insert",
data: formToJSON(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
alert('Success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Error: ' + textStatus);
}
});
});
});
function formToJSON()
{
return JSON.stringify
({
"username": $('#username').val(),
"email": $('#email').val(),
"password": $('#password').val()
});
};
</script>
Code in Service
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("/insert")
public boolean insertUsers(String content)
{
Gson g = new Gson();
Users u = (Users) g.fromJson(content, Users.class);
UsersDAO dao = new UsersDAO();
return dao.insertUsers(u);
}
You have to add id for all the input fields.
Try this.
<body>
<form id="submit">
Username:<br>
<input type="text" id="username" name="username"><br>
Email:<br>
<input type="email" id="email" name="email"><br><br>
Password:<br>
<input type="text" id="password" name="password"><br><br>
<button id="submit">Save</button>
</form>
</body>
And in this, You have to change this,
$("#submit").submit(function(event)
into this,
$("#submit").click(function(event)
i cant get the value of a freeMarker variable when i put my code in a external javascript file
here is my page when the javascript code inside, this works i can get the value of my freemarker variable in this way:
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign title="value 1">
<#assign subtitle="value 2">
<script>
function doAjaxPost()
{
var name= $('#name').val();
var lastName= $('#lastName').val();
var json = {"name" : name, "lastName" : lastName};
console.log(json);
var variableFreeMarker = "${freeMarkValue}";
console.log('this value is: ' + variableFreeMarker);
$.ajax(
{
type: "POST",
url: "myUrl",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
/* error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}*/
});
}
</script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
<br>
</#layout.masterPageLay>
but if i put my javascript code in a external file in this case myPageScript.js and then call that script in my page i cant get the value of my freeMarker variable this is how i'm calling my script
<script src="../resources/js/scripts/myPageScript.js"></script>
and this is my page that dont work
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign titulo="value 1">
<#assign subtitulo="value 2">
<script src="../resources/js/scripts/myPageScript.js"></script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
<br>
</#layout.masterPageLay>
this output in my chrome console "${freeMarkValue}" instead of the value of the variable
here are my controllers i'm processing the form using jquery ajax
#RequestMapping(value = "myForm", method = RequestMethod.GET)
public String myForm(Model model) {
model.addAttribute("freeMarkValue", "controll");
return "myForm";
}
#RequestMapping(value = "myForm", method = RequestMethod.POST)
public #ResponseBody String getTags(#RequestBody final String json, Model model)
throws IOException
{
ObjectMapper mapper = new ObjectMapper();
User objetmapped = mapper.readValue(json, User .class);
User person = new User iox();
person.setName(objetmapped .getName());
person.setLastName(objetmapped .getLastName());
);
model.addAttribute("freeMarkValue", "second controller value");
return toJson(objetmapped );
}
private String toJson(User person)
{
ObjectMapper mapper = new ObjectMapper();
try
{
String value = mapper.writeValueAsString(person);
// return "["+value+"]";
return value;
}
catch (JsonProcessingException e)
{
e.printStackTrace();
return null;
}
}
You can move your variable into a script block in the html page.
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign titulo="value 1">
<#assign subtitulo="value 2">
<script src="../resources/js/scripts/myPageScript.js"></script>
<script>
// This variable can be accessed from myPageScript.js
var variableFreeMarker = "${freeMarkValue}";
</script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
Or add it as a value of a hidden input etc..
<input type="hidden" id="myVal" value="${freeMarkValue}">
Your JS (in a seperate script) would then need to read the value for example using jQuery.
var aValue = $("#myVal").val();
I use the first method for common stuff such as adding a date format string that is specific to the user on to every page. They will have global scope so be careful with naming.
well i have got this Themeforest Template and played around with it until the website looks in a way how i imagined it. The only Problem i have is that the .js form somehow doesnt work and i dont have any idea. I dont even know where to tell the form to which Adress it should send the text. Maybe you can help me.
The Domain is: entwicklung.thechillingbull.de
This is the HTML:
<div class="container"> </div>
<div class="container"> </div>
<div class="bg-2 section" id="contact">
<div class="inner" data-topspace="50" data-bottomspace="20" data-image="flavours/coffeecream/images/demo-content/background-6.jpg">
<div class="container">
<h3 class="hdr4">Kontakt und Reservierung</h3>
<div class="easyBox full">
<div class="row nomargin">
<div class="col-md-11">
<h4 class="hdr2 special">Wenn du Uns etwas mitteilen oder Reservieren möchtest hast du hier die Chance!</h4>
<form class="simpleForm" action="form/form.php" method="post">
<fieldset>
<div class="form-group">
<label>Dein Name</label>
<input type="text" class="form-control" name="field_[]" placeholder="Schreibe deinen Namen">
</div>
<div class="form-group">
<label>Deine E-Mail-Adresse</label>
<input type="email" required class="form-control" name="email" placeholder="Schreibe deine E-Mail-Adresse">
</div>
<div class="form-group">
<label>Deine Nachricht</label>
<textarea class="form-control" rows="5" name="field_[]" placeholder="Schreibe deine Nachricht"></textarea>
</div>
<input type="hidden" name="msg_subject" value="Contact Form">
<input type="hidden" name="field_[]" value=" ">
<input class="btn btn-default" type="submit" value="Senden">
</fieldset>
</form>
<div class="successMsg" style="display:none;">Nachricht erfolgreich gesendet! </div>
<div class="errorMsg" style="display:none;"> Ups! Es ist ein Fehler unterlaufen, versuche es später erneut. </div>
</div>
<div class="col-md-2"> </div>
</div>
</div>
</div>
</div>
and this is the .js
/**
* Submitting Form
*/
jQuery(document).ready(function ($) {
var debug = false; //show system errors
var sendingMessage = 'Sending...';
$('.simpleForm').submit(function () {
var $f = $(this);
var $submit = $f.find('input[type="submit"]');
//prevent double click
if ($submit.hasClass('disabled')) {
return false;
}
$submit.attr('data-value', $submit.val()).val(sendingMessage).addClass('disabled');
$.ajax({
url: $f.attr('action'),
method: 'post',
data: $f.serialize(),
dataType: 'json',
success: function (data) {
if (data.errors) {
// error
var $errorMsg = jQuery($f).parent().find(".errorMsg");
jQuery($f).fadeOut(300,function(){
$errorMsg.fadeIn();
});
} else {
// success
var $successMsg = jQuery($f).parent().find(".successMsg");
jQuery($f).fadeOut(300,function(){
$successMsg.fadeIn();
});
}
$submit.val($submit.attr('data-value')).removeClass('disabled');
},
error: function (data) {
if (debug) {
alert(data.responseText);
}
$submit.val($submit.attr('data-value')).removeClass('disabled');
}
});
return false;
});
});
hope you can help me get this to work.
Thank you !
Change:
<form class="simpleForm" action="form/form.php" method="post">
To
<form class="simpleForm" action="/your-code-file" method="post">
where your-code-file will be the location of the file which will handle the form values.
I have a button on my JSP form which must send a boolean value to the controller.
<button type="button" class="btn btn-success"><i class="glyphicon glyphicon-ok-circle"></i> Activate</button>
On the form I'm using POJO object which actually have a status (boolean status).
public class User implements Serializable {
private String name;
private boolean status;
// getters and setters omitted
}
I need to add javascript handler to the button to send this status and user id to the controller only with POST method. How can I do it using javascript?
UPD:
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
<td>${user.country}</td>
<td class="col-sm-1 col-md-1">
<a href="/user/${user.id}" style="text-decoration: none">
<button type="button" class="btn btn-primary btn-block"><i
class="glyphicon glyphicon-pencil"></i> Edit
</button>
</a>
</td>
<c:choose>
<c:when test="${user.active == true}">
<td class="col-sm-1 col-md-1">
<button type="button" class="btn btn-danger btn-block"><i
class="glyphicon glyphicon-remove"></i> Suspend
</button>
</td>
</c:when>
<c:otherwise>
<td class="col-sm-1 col-md-1">
<button type="button" class="btn btn-success"><i
class="glyphicon glyphicon-ok-circle"></i> Activate
</button>
</td>
</c:otherwise>
</c:choose>
</tr>
</c:forEach>
you can use as:
function doSend(){
document.forms[0].action = "url?val=true";
document.forms[0].submit();
}
and
<button type="button" onclick="doSend()" and other attrubute>
Specify a method attribute on your form.
<form name="myform" method="POST">
It will cause the form to be submitted as a POST.
Or You can do it using hidden field as:
<html>
<head>
<script type="text/javascript">
function doSend(){
alert("hi");
document.forms[0].setAttribute("method","POST");
document.forms[0].submit();
}
</script>
</head>
<body>
<form action="test2.html" method="GET">
<input type="hidden" name="hiddenField" value="ture1"/>
<input type="button" onclick="doSend()" value="click"/>
</form>
</body>
</html>
Use ajax for it..
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
Following function you have to call on click event.
function callOnClick(usrid)
{
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
//action todo after successful return
}
else{
alert("An error has occured making the request")
}
}
}
var status=encodeURIComponent(document.getElementById("status").value)// make a hidden field and set the status in value attribute
var userid=usrid//set this value as the attribute of javascript function
var parameters="status="+status+"&id="+userid
mypostrequest.open("POST", "name of controller or servlet", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters)
}
I need to save event data to an xml file.I need to do this using a java code.i am using html5.
So from the javascript i need to call this java code and need to save event text,date and other details to an xml file.And whenever the data is needed it should be displayed back in the dhtmlx scheduler.How can i do this?
function init() {
scheduler.config.xml_date="%Y-%m-%d %H:%i";
scheduler.config.prevent_cache = true;
scheduler.init('scheduler_here',new Date(2010,0,20),"month");
scheduler.load("data/data.xml");
}
function show() {
alert(scheduler.toXML());
}
function save() {
var form = document.forms[0];
form.action = "./data/xml_writer.php";
form.elements.data.value = scheduler.toXML();
form.submit();
}
function download() {
var form = document.forms[0];
form.action = "./data/xml_download.php";
form.elements.data.value = scheduler.toXML();
form.submit();
}
xml_writer.php
<?php
file_put_contents("./data.xml",$_POST["data"]);
header("Location:./dummy.html");
?>
<?php
if(empty($_POST['data'])) {
echo "why";
exit;
}
xml_download
$filename = "data.xml";
header("Cache-Control: ");
header("Content-type: text/plain");
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo $_POST['data'];
?>
html code
<form action="./php/xml_writer.php" method="post" target="hidden_frame" accept-charset="utf-8">
<input type="hidden" name="data" value="" id="data">
</form>
<iframe src='about:blank' frameborder="0" style="width:0px; height:0px;" id="hidden_frame" name="hidden_frame"></iframe>
<div id="scheduler_here" class="dhx_cal_container" style='width:100%; height:100%;'>
<div class="dhx_cal_navline">
<div class="dhx_cal_prev_button"> </div>
<div class="dhx_cal_next_button"> </div>
<div class="dhx_cal_today_button"></div>
<div class="dhx_cal_date"></div>
<input type="button" name="download" value="Download" onclick="download()" style="right:500px;" />
<input type="button" name="show" value="Show" onclick="show()" style="right:400px;" />
<input type="button" name="save" value="Save" onclick="save()" style="right:300px;" />
<div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
<div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div>
<div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
</div>
<div class="dhx_cal_header">
</div>
<div class="dhx_cal_data">
</div>
This much code i have.But code for saving to an xml file is in php.I need java code instead of php.