I can't send json object to Java server using ajax. Browser console throws error:
GET http: // localhost: 8080 / MySpring / change? {% 22name% 22:% 22d% 22} 400 (Bad Request).
I use SpringMVC
HTML file
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page session="false"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#load").bind("click", function() {
var inputText = $("#mytext").val();
var task = {name : inputText};
$.ajax({
url : "change",
crossDomain: true,
type: 'GET',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
data: JSON.stringify(task),
success: function (response) {
var result = response.name;
$("#result_text").text(result);
}
});
});
});
</script>
</head>
<body>
<input type="text" name="mytext" id="mytext">
</br>
<input type="button" name="load" id="load" value="Load">
</br>
<p id="result_text"></p>
</body>
</html>
#Controller
public class MailController {
#RequestMapping(value = "/change", method = RequestMethod.GET)
public #ResponseBody
Task change(#RequestParam String name) {
Task result = new Task();
result.setName(name);
return result;
}
}
Try this. Also instead of dynamically adding json just hard code the it like {"name":"test"}
$.ajax({
type: "GET",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
It's the problem with the controller mapping.
Your controller is expecting:
http://localhost:8080/MySpring/change?name=yourData
but you are calling
http://localhost:8080/MySpring/change?yourData
Consider also changing method from GET to POST according to http get length limit.
<script>
$(document).ready(function() {
$("#load").bind("click", function() {
var inputText = $("#mytext").val();
var task = {name : inputText};
$.ajax({
url : "change",
crossDomain: true,
type: 'GET',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
data: JSON.stringify(task),
traditional : true,
success: function (response) {
var result = response.name;
$("#result_text").text(result);
}
});
});
});
</script>
Added traditional : true, in Ajax call
Related
I'm trying to call my Spring controller using Ajax and submitting a form.
Function always retrieves the error window. I tried changing the URL parameter to "/profile", "profile" or "PrivateAreaController/profile", but I keep getting the same error.
My main.js file and controller are placed in the following order:
-->Mainfolder
-->src
-->java
-->controller
-->PrivateAreaController.java
-->resources
-->static
-->js
-->main.js
My controller is called PrivateAreaController
Ajax Code
$('#sampleForm').submit(
function(event) {
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var data = 'firstname='
+ encodeURIComponent(firstname)
+ '&lastname='
+ encodeURIComponent(lastname);
$.ajax({
type : "POST",
dataType: "json",
url : '#Url.Action("callingcontroller","PrivateAreaController")',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
return false;
});
Spring code
#RequestMapping(value = "/profile", method = RequestMethod.POST)
public #ResponseBody
String processAJAXRequest(
#RequestParam("firstname") String firstname,
#RequestParam("lastname") String lastname ) {
String response = "";
System.out.println("working");
return response;
}
HTML form
<form id="sampleForm" method="post" action="/profile">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<button type="submit" name="submit">Submit</button>
</form>
EDIT:
I found the answer.. i needed to add
#CrossOrigin(origins = "http://localhost:8080")
before the #RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)
I found the answer.. i needed to add
#CrossOrigin(origins = "http://localhost:8080")
before the #RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)
This worked for me using springboot with thymeleaf, made small modification to one of the answers on this post How do you get the contextPath from JavaScript, the right way?
In the HTML
<html>
<head>
<link id="contextPathHolder" th:data-contextPath="#{/}"/>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
THEN IN JS
var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + 'action_url', function() {});
What is error you are getting, Press F12 and go to Network tab and the press submit button now see the url, try adding url:"../your service URL..
Well. I never seen this part before.
#Url.Action("callingcontroller","PrivateAreaController")
I normally do like as below:
$.ajax({
type : "POST",
dataType: "json",
url : '/profile',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
But it can have a problem with the contextPath.
So, What I do is adding 'request.getContextPath()/' as below:
$.ajax({
type : "POST",
dataType: "json",
url : '${request.getContextPath()}/profile',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
The contextPath has the URL of your start page.
For instance, 'www.google.com' or 'www.naver.com'
But in general, Since I personally use the contextPath a lot, I make a value and keep it.
var context = ${request.getContextPath()};
Then, your code will look neat and easy to reuse.
And also you can figure it out with the error attribute.
error : function(err) {
console.log("not working. ERROR: "+JSON.stringify(err));
}
I hope this works out.
I am trying to upload a file and want to save in /resources/images folder. Here is my controller:
RestController.java
#Controller
//#RequestMapping("/cont")
public class RestController {
#RequestMapping(value = "/echofile", method = RequestMethod.POST)
public #ResponseBody HashMap<String, Object> echoFile(MultipartHttpServletRequest request,
HttpServletResponse response) throws Exception {
MultipartFile multipartFile = request.getFile("file");
Long size = multipartFile.getSize();
String contentType = multipartFile.getContentType();
InputStream stream = multipartFile.getInputStream();
byte[] bytes = IOUtils.toByteArray(stream);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("fileoriginalsize", size);
map.put("contenttype", contentType);
map.put("base64", new String(Base64Utils.encode(bytes)));
return map;
}
my index.jsp is:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC - Upload File</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
var isJpg = function(name) {
return name.match(/jpg$/i)
};
var isPng = function(name) {
return name.match(/png$/i)
};
$(document).ready(function() {
var file = $('[name="file"]');
var imgContainer = $('#imgContainer');
$('#btnUpload').on('click', function() {
var filename = $.trim(file.val());
if (!(isJpg(filename) || isPng(filename))) {
alert('Please browse a JPG/PNG file to upload ...');
return;
}
$.ajax({
url: "http://localhost:8080/SimpleAjaxJqueryPicUpload/api/echofile",
type: "POST",
data: document.getElementById("image"),
enctype: 'multipart/form-data',
processData: false,
contentType: false
}).done(function(data) {
imgContainer.html('');
var img = '<img src="data:' + data.contenttype + ';base64,'
+ data.base64 + '"/>';
imgContainer.append(img);
}).fail(function(jqXHR, textStatus) {
//alert(jqXHR.responseText);
alert('File upload failed ...');
});
});
$('#btnClear').on('click', function() {
imgContainer.html('');
file.val('');
});
});
</script>
</head>
<body>
<body style="font-family: calibri; font-size: 8pt">
<div>
<div id="fileForm">
<input type="file" name="file" id="image"/>
<button id="btnUpload" type="button">Upload file</button>
<button id="btnClear" type="button">Clear</button>
</div>
<div id="imgContainer"></div>
</div>
</body>
</html>
But the file is not uploaded. When I clicked the button, it has shown upload failed alert. How can I solve it?
Please include these lines:
var formData = new FormData();
formData.append('file', jQuery('input[type=file]')[0].files[0]);
data: formData
Your AJAX code look like this -
var formData = new FormData();
formData.append('file', jQuery('input[type=file]')[0].files[0]);
jQuery.ajax({
url: 'path',
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(response){
alert(response);
}
})
I am trying to create a comment section using jsp, servlet and ajax. The problem I am facing is that each comment replaces it's previous one instead of showing next to it.
Highly appreciate any kind of help.
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitBtn').click(function() {
var cmt = $('#cmt').val();
$.ajax({
type : 'POST',
data : {
cmt : cmt,
action : 'EnterMsg'
},
url : 'SubmitComment',
success : function(result) {
$('#view2').text(result);
}
});
});
});
</script>
</head>
<body>
<fieldset>
<legend>Enter Message</legend>
<form>
Ques.<input type="text" id="cmt"> <input type="button"
value="Send" id="submitBtn"><br> <span id="post1"></span>
</form>
</fieldset>
<fieldset>
<legend>View Message</legend>
<form>
<div id='view2'></div>
<br>
</form>
</fieldset>
Try
var html='';
$.ajax({
dataType: "json",
url: "SubmitComment",
error: function () {
alert('error occured');
},
success: function (result) {
for(var key in result) {
var value = result[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#view2").append(html);
}
});
Instead of
success : function(result) {
$('#view2').text(result);
}
Because of you get multiple comments from the ajax respose and you have to iterate each one of them and append to your div tag
is this wrong because i get loadData as undefined?
<head>
<script type="text/javascript">
function loadData() {
var name = $("#surname").val();
$.ajax({
url: 'checkdata.php',
type: 'POST',
data: { 'surname' : surname }
});
alert(data);
//return false;
</script>
</head>
<body onload="loadData()">
<form name="form1" method="post" action="php/save-edit.php" >
i have a form where i want to extract data from a db and display it in the form fields on form load
As per my understand you are using code code.Please try below code.
Just change <body onload="loadData()"> to <body onload="javascript:loadData();"> and try. it may help.
<head>
<script type="text/javascript">
function loadData() {
var name = $("#surname").val();
$.ajax({
url: 'checkdata.php',
type: 'POST',
data: { 'surname' : name }
});
alert(data);
//return false;
}
</script>
</head>
<body onload="javascript:loadData();">
<form name="form1" method="post" action="php/save-edit.php" >
This problem might be happened because of running the onload event before creating the HTML object.
It would be better if you use like as follow :
$( document ).ready(function() { your function });
Hope this help.
I am using a Form in a LightBox which contains some input element.
<form name="imageUploadForm" action="uploadImage.do" method="post" enctype="multipart/form-data">
<input type="text" id="id" name="id" style="display: none;" value="">
<div id="fileUploaderDiv">
<input type='file' name="file0" id ="file0" />
</div>
<input type="submit" value="Submit">
</form>
when i am submitting the form than the form redirect to it's action location. I just want to submit form without redirecting user, so user stay on lightbox without loosing his data.
I have tried jquery ajax call for this
var data = new FormData();
var $inputs = $('#imageUploadForm :input');
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
data.append(this.name, $(this).val());
});
$.ajax({
url: 'uploadImage.do',
data: data,
cache: false,
contentType: 'multipart/form-data',
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
But getting error at server side in my FileUploader servlet.
The request was rejected because no multipart boundary was found
can anybody tell me what am i missing in this ?
You need to prevent the default action of submitting the form:
$('form[name="imageUploadForm"]').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'uploadImage.do',
data: data,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
}
});
});
I believe you should set the contentType option to false when using the FormData class, forcing jQuery not to add a Content-Type header, otherwise the boundary string will be missing, and that's probably the reason for your server error.
You must also leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Here is the simplest form of a form submit using jquery Ajax. I have not tested this but it should work :-)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test form</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#sbmt').click(function(){
var text1 = $('#text1').val();
var text2 = $('#text2').val();
/// validation of inputs
///then
$.ajax(
{
url :'submit.php',
type : 'post',
data : {'text1' : text1, 'text2' : text2 },
success: function(data){
alert("form submitted . response is :"+ data);
}
}
).fail(function(){alert("Failed!!");});
});
});
</script>
</head>
<body>
<form id="myform">
<input type="text" id="text1" />
<input type="text" id="text2" />
<input type="button" id="sbmt" value="submit"/>
</form>
</body>
</html>