Trying to display a value from database without refreshing the webpage using JQuery and Ajax was successful in displaying this however “Served at: /Project name” is getting appended to the value displayed
Script:
$(document).ready(function() {
$('#AESASJOBRUNOPTION').change(function() {
var AESASJOBRUNOPTION = $('#AESASJOBRUNOPTION').val();
$.ajax({
type:'POST',
url: "AESASJobCurrentOpenPeriod",
data: {AESASJOBRUNOPTION: AESASJOBRUNOPTION},
cache: false,
success: function(result) {
$("#result1").html(result);
$("#result1").html(result).slideDown('slow');
}
});
});
});
Servlet:
try{
if(ASCOGSRS.next()){
//System.out.println("Open Peiod is :"+ASCOGSRS.getString(1));
HttpSession OpenPeriodsession=request.getSession();
OpenPeriodsession.setAttribute("ASCOGSCurrentOpenPeriod", ASCOGSRS.getString(1));
PrintWriter out =response.getWriter();
String ASCOGSOpenPeriod=ASCOGSRS.getString(1);
out.print(" The Current Open Period is: "+ASCOGSOpenPeriod);
}
}
If your project is using JET Template from Eclipse, looks like the doPost method appends the extra Served at: <PATH>.
If JET Template is used, following are possible solutions:
Skip using JET Template in Eclipse Window -> Preferences -> Java EE
If Skipping JET Template is not possible and your AJAX request only retrieves the data, change the request type to GET instead of POST
If JET Template is not used, following is a solution at the Javascript level:
$(document).ready(function() {
$('#AESASJOBRUNOPTION').change(function() {
var AESASJOBRUNOPTION = $('#AESASJOBRUNOPTION').val();
$.ajax({
type:'POST',
url: "AESASJobCurrentOpenPeriod",
data: {AESASJOBRUNOPTION: AESASJOBRUNOPTION},
cache: false,
success: function(result) {
result_without_path = result.replace(/Served at:[\/a-zA-Z0-9]*/i,'');
$("#result1").html(result_without_path);
$("#result1").html(result_without_path).slideDown('slow');
}
});
});
});
You may also look for response writer in your servlets which may write the response it should be something like:
response.getWriter().append("Served at: ").append(request.getContextPath());
And then you can comment this line from your servlet.
Related
So I am loading my page using ajax, and everything is working fine using below
$( document ).ready(function() {
menuLoad('auction');
});
function menuLoad(page){
$.ajax({
type: 'post',
url: '/content/'+page+'/'+page+'.php',
async : false,
success: function (response) {
location.hash = page;
$("#contentLoad").html(response);
}
})
};
however if i try loading the same page multiple times, all buttons click events will fire multiple times.. I understand that every time I am loading the content, I am re-assigning a new event to the button while it already have one which cause each event to fire when a user click on it.. but how to fix this?
inside page content, the button will be something like below
<input type="button" value='New Sold' id='soldaddbtn' >
$( document ).on("click", "#soldaddbtn", function(){
$.ajax({
type: "POST",
url: "/content/sold/loadSoldAdd.php",
dataType: 'html',
success: function(response){
bootbox.dialog({message: response});
}
});
})
define a global variable and check for its existence.
if(!soldaddbtnClickEventisAdded) { // check if the variable is defined file is already loaded
$( document ).on("click", "#soldaddbtn", function(){
$.ajax({
type: "POST",
url: "/content/sold/loadSoldAdd.php",
dataType: 'html',
success: function(response){
bootbox.dialog({message: response});
}
});
});
}
var soldaddbtnClickEventisAdded = true; // add a global variable
I didn't understand your problem completely but try using following code:
As on() will bind the click event, so there might be the case that event is bounded multiple times. So unbind the click event then bind it again.
$("#soldaddbtn").off("click").on("click", function(){});
its javascript not java, you need event to fire once, the replace
$( document ).on("click", "#soldaddbtn", function(){
with
$("#soldaddbtn").on("click", function(){
I am new to ExtJS. I designed a login page using ExtJS where a value is successfully returned from servlet response back to JS file as shown below.
LoginServlet.java
String user_role = "User1 - Admin";
myObj.addProperty("success", true);
myObj.addProperty("user_role", user_role);
out.println(myObj.toString());
out.close();
login.js
buttons: [{
text: 'Login',
handler: function(button)
{
var formData = this.up('form').getForm();
formData.submit({
clientValidation: true,
url: '/LoginServlet',
method: 'POST',
success: function(form, action) {
user_role = Ext.JSON.decode(action.response.responseText);
Ext.MessageBox.alert('User_Role', user_role.user_role);
window.location = 'userhome.jsp';
},
failure: function(form, action) {
}
});
}
}
Here in Ext.MessageBox.alert('User_Role', user_role.user_role);, i am getting a alert message as shown.
My need is to assign the value to a global variable so that I can access it in my entire ExtJS application (I have a common js file named header.js which is included in all JSP files in the application, I want to display the value of 'user_role' in header.js so that it will be displayed in all JSP files).
Note: I have defined 'user_role' variable as a global variable in a separate file globalVar.js (code below) and I have included globalVar.js as the first js file in all JSP files).
var user_role;
I am using ExtJS 4.2. Please suggest a way to achieve this.
Add a singleton class over your application in utility.
Ext.define('MyApp.utilities.GlobalVar', {
singleton : true,
user_role : null
}
buttons: [{
text: 'Login',
handler: function(button)
{
var formData = this.up('form').getForm();
formData.submit({
clientValidation: true,
url: '/LoginServlet',
method: 'POST',
success: function(form, action) {
user_role = Ext.JSON.decode(action.response.responseText);
Ext.MessageBox.alert('User_Role', user_role.user_role);
**MyApp.utilities.GlobalVar.user_role = user_role.user_role;**
window.location = 'userhome.jsp';
},
failure: function(form, action) {
}
});
}
}
Assign global variable on success of form submit, and you can use the global variable anywhere in your application. [using MyApp.utilities.GlobalVar.user_role]
It will be good if you use a store with storeId to keep the entire user data at one place.
Once you get response back from server. Update your Store with that value.
That store can be accesed from entire application.
Just do Ext. getStore('storeId') where store if is the id of store
it will keep your user data organises as well.
I am trying to display text (or html) that is received from a servlet response in a qTip2 tooltip within a jsp. I have almost everything working and have verified with Firebug that the servlet is being invoked and text is being returned, but when I try to use the 'html' (or data) variable in my ajax call, I get an error: HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy.
I've tried displaying the html in a JavaScript alert, and this is what displays: [object XMLDocument].
Here is the sequence of events:
1.User clicks on a section of HTML text, which has a link defined that points to the servlet and passes parameters
2.The ajax invokes the servlet which does some processing and returns text or html
3.The text is displayed as a tooltip with qTip2
How can I properly handle the response from the servlet and manipulate the text that is received from it?
Ajax call:
$(".ajax_link").click(function(e) {
e.preventDefault();
var $this = $(this);
var link = $(this).attr('href'); //Gets link url
$.ajax({
type: "GET",
url: link,
cache: false,
}).done(function(html) {
$this.qtip({
content: {
text: html //<--this causes error above
//text: "<table><tr><th>Team</th></tr></table>" <--this works fine
}
});
$this.qtip('toggle', true);
});
});
Servlet Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("inside doGet");
String var1 = "<table><tr><th>Team</th></tr></table>";
//var1 = request.getParameter("var1");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(var1);
out.flush();
out.close();
}
pass dataType as html in ajax request
i.e.
$.ajax({
type: "GET",
url: link,
cache: false,
dataType : "html"
}
I have a problem in my spring boot app with the csrf token.
I have a form where I can edit a Person. A Person can have
Let us now imagine that the person has a car and enter this and store it. The next time he wants to delete this car and enter another one. I have created that so that there is a list of all of his cars -- he has the option to remove this from the list. Now I'm starting from these pills and want to send with the corresponding ID to the server a POST. When I try I get a 403 forbidden and I have no idea why.
If I change from POST to GET, then it works.
My JavaScript (taken from this site: http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#the-csrfmetatags-tag)
var csrfParameter = $("meta[name='_csrf_parameter']").attr("content");
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
var csrfToken = $("meta[name='_csrf']").attr("content");
// using JQuery to send a non-x-www-form-urlencoded request
var headers = {};
headers[csrfHeader] = csrfToken;
$.ajax({
url: "./delete/car",
type: "GET",
headers: headers,
});
$.ajax({
url: "./delete/car",
type: "POST",
headers: headers,
});
My controller methods:
#RequestMapping(value = "/{login}/delete/car", method = RequestMethod.GET)
public ModelAndView delete(#PathVariable("login") final String login) {
System.out.println("Stop");
return new ModelAndView("redirect:" + WebSecurityConfig.URL_PERSONS_OVERVIEW);
}
#RequestMapping(value = "/{login}/delete/car", method = RequestMethod.POST)
public ModelAndView deleteInstEmp(#PathVariable("login") final String login) {
System.out.println("Stop");
return new ModelAndView("redirect:" + WebSecurityConfig.URL_PERSONS_OVERVIEW);
}
Any suggestions?
Thanks in advance.
OK, after strugglin with all that, I get the following result.
I added the fail method to the Ajax construct and get the following message:
"Failed to execute 'setRequestHeader' on 'XMLHttpRequest': '${_csrf.headerName}' is not a valid HTTP header field name."
the official spring site advises that you have to put this: <sec:csrfMetaTags /> or from other sources, this: <meta name="_csrf" th:content="${_csrf.token}"/> in your html file.
After this, you should be able to access these attributes in your JavaScript, but in my case I get undefined and ${_csrf.headerName}.
A last try was to take the value from the hidden value (chapter 24.5: http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#the-csrfmetatags-tag).
Now, I have the following:
$(function () {
var token = $("input[name='_csrf']").val();
var header = "X-CSRF-TOKEN";
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
});
$.ajax({
url: "./delete/car",
type: "POST",
success:function(response) {
alert(response);
}
});
With this it works like a charm.
Another way, you can use the following code:
$.ajax({
url : './delete/car',
headers: {"X-CSRF-TOKEN": $("input[name='_csrf']").val()},
type : 'POST',
success : function(result) {
alert(result.msgDetail);
}
})
I suggest you first check if a valid csrf token and the header have been generated using chrome debugger. If not, then have you added the <sec:csrfMetaTags /> in the <head>?(you will need to import the spring security taglibs). If using Apache tiles, you will have to add this at the <head> section of the template file being used for the view.
If the token is not empty, then in your security-context/configuration file, check if you have disabled csrf security by any chance. By default it is enabled and needs to be for this process to work.
var urlUpload = "${root}manager/uploadFile.html";
var params = $('#topicForm').serialize();
$.ajax({
type: 'POST',
url: urlUpload,
data: params,
contentType: 'multipart/form-data',
processData: false,
success: function(data) {
alert("success");
}
});
#RequestMapping(value="/manager/uploadFile.html", method = RequestMethod.POST)
public String uploadFile(#ModelAttribute("topicForm") TopicForm topicForm,
#RequestParam("topicDoc") MultipartFile multipartFile ModelMap model) { ... }
I am getting the below exception
org.springframework.web.multipart.MultipartException: Could not parse
multipart servlet request; nested exception is
org.apache.commons.fileupload.FileUploadException: the request was
rejected because no multipart boundary was found.
The plugin is working fine thank you.
var urlUpload = "${root}manager/uploadFile.html?categoryId="+$("#category").val()+"&topicName="+$("#topicName").val();
$.ajaxFileUpload({
url:urlUpload,
secureuri:false,
fileElementId:'fileupload',
dataType: 'html',
success: function (data, status) {
alert("success");
}
});
The plugin is working fine, now i need to send few form fields to the controller along with the input file. in the above ajax call i appended the values to url. Is there any other solution for this?
The problem is that you're attempting to upload a URL-encoded serialization of the form, while claiming that it's multipart (see documentation of JQuery's serialize() function).
You need to use a plugin that will create the proper request. Here's one that I've used.
Alternatively, you can use HTML5 to upload files. I haven't done this.