Here is the solution of the problem. Thanks to all, and special thanks to Alessandro G. for the private help.
I made load() on jsp URL thinking to load the elaboration with permutation.
The right way is to do load() on the SERVLET URL, passing parameterized data from the form. load() does a GET with data to java servlet, the java servlet elaborates the permutation and his response contain the jsp used as template to print the HTML code with permutations
$(document).ready(function(){
$("form").submit(function(event){
console.log("submit effettuato");
event.preventDefault();
var formData = $(this).serialize();
console.log(formData);
$("#aggiornare").load( "anagrammiajax", formData , function(responseTxt, statusTxt, xhr){
if(statusTxt=="success"){
alert("contenuto esterno cariato correttamente");
}
if(statusTxt=="error"){
alert("error: " + xhr.status + ": " + xhr.statusText);
}
});
});
});
i'm studing web application and i'm trying to create an application to display permutations of a string.
I use an html page called "index.html" with a form that send the word to servlet
the servelt is called "anagrammiajax" and it works correctly
the servlet elaborates the permutations ad dispatch them to jsp page called "anagrammi- partial.jsp
the jsp page just use a foreach to print all the permutations
i want use ajax load() method in the index.html page to show into a div the content of the jsp page
problems:
i don't want a redirect to jsp page after servlet elaboration, but i wont show again the idex.html wht the updated div (maybe with another redirect from jsp to index.html and adding a setInterval method to auto refresh the page with a timer and load the content?)
the jquery load() method don't load the content in the div from jsp page (the permutations printed by forEach) and it returns me a 0 error
please, help me to resolve it and
here is my code:
index.html
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Anagrammi su JSP usando JSTL, jQuery, AJAX</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="update.js"></script>
</head>
<body>
<h1>Anagrammi su JSP usando JSTL, jQuery e AJAX</h1>
<p>visualizza gli anagrammi (permutazioni) della parola inserita</p>
<div>
<form action="anagrammiajax" name="anagrammi" method="post">
<input type="text" name="parola">
<input id="submit" type="submit" value="genera anagrammi">
</form>
</div>
<div>
<h2>Risultati</h2>
<h3>pagina aggiornata con AJAX e jQuery</h3>
<div id="aggiornare">
</div>
</div>
</body>
</html>
update.js code:
$(document).ready(function(){
$("#submit").click(function(){
alert("click");
$("#aggiornare").load("anagrammi-partial.jsp", function(responseTxt, statusTxt, xhr){
if(statusTxt=="success"){
alert("contenuto esterno cariato correttamente");
}
if(statusTxt=="error"){
alert("error: " + xhr.status + ": " + xhr.statusText);
}
});
});
});
here is the servlet code:
package anagrammiAjax;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.*;
#SuppressWarnings("serial")
public class AnagrammiAjaxServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String parola = req.getParameter("parola");
parola = parola.toLowerCase();
System.out.println(parola);
ArrayList<String> anagrammi = permutations(parola);
for(int i=0; i<=anagrammi.size()-1; i++){
System.out.println(anagrammi.get(i));
}
req.setAttribute("parola", parola);
req.setAttribute("anagrammi", anagrammi);
try {
getServletContext().getRequestDispatcher("/anagrammi-partial.jsp").include(req, resp);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static ArrayList<String> permutations(String s) {
ArrayList<String> ret = new ArrayList<String>();
permutation(s.toCharArray(), 0, ret);
return ret;
}
public static void permutation(char[] arr, int pos, ArrayList<String> list){
if(arr.length - pos == 1)
list.add(new String(arr));
else
for(int i = pos; i < arr.length; i++){
swap(arr, pos, i);
permutation(arr, pos+1, list);
swap(arr, pos, i);
}
}
public static void swap(char[] arr, int pos1, int pos2){
char h = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = h;
}
}
and in the end the jsp code:
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<c:forEach items="${anagrammi }" var="indice">
<c:out value="${indice}"/>
</c:forEach>
You are triggering the Ajax request when the user clicks on a submit button.
The JavaScript runs, then the form is submitted, a new page loads and the execution environment for the JavaScript goes away and is a replaced by a new one.
You need to stop the form from submitting.
$(document).ready(function(){
// Capture the event object in an argument
$("#submit").click(function(evt) {
// Prevent the default action
evt.preventDefault();
Try with this code, and use "console.log" and browser's devtools instead of "alert" for debugging
$(document).ready(function(){
$("form").submit(function(event){
console.log("submit form");
event.preventDefault();
var thisForm = $(this);
var jqxhr = $.post("anagrammi-partial.jsp", thisForm.serialize())
.done(function(data){
console.log("contenuto esterno caricato correttamente");
$("#aggiornare").html(data);
})
.fail(function(xhr, textStatus){
console.log("error: "+textStatus );
})
.always(function(){
console.log("finished");
});
});
});
Related
My problem is, that I have to implement an AJAX function to display whether the selected item is out of stock or not. However, instead of displaying my error message it kind of duplicates the site completely and I'm very, nothing I've tried seems to work.
My idea behind the code was, that I have a dropdown form with action set to a controller (Webservlet) that handles both doGet and doPost, and an onchange event showing to a javascript function which invokes the AJAX stuff (You can see I'm not very confident in these aspects, I don't know nearly enough about it).
The JSP part that is relevant would be this:
<%#page contentType="text/html" pageEncoding="UTF-8" import="PCConfigurator.*"%>
<%
session.setMaxInactiveInterval(0);
ConfController ctrl = new ConfController();
%>
...
<script type="text/javascript">
var xmlHttpObject = new XMLHttpRequest();
function checkArticle(selectedArticleId) {
var url = '?id=' + selectedArticleId.value;
xmlHttpObject.open('GET', url);
xmlHttpObject.onreadystatechange = handleStateChange;
xmlHttpObject.send();
}
function handleStateChange() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
var result = document.getElementById("errorDiv");
result.innerHTML = response;
}
}
</script>
<form method="POST" action="ConfController" >
<table>
<h1>PC Konfigurator GO Inc.</h1>
<tr>
<td><br><br></td>
</tr>
<tr>
<td>Welchen Prozessor wollen Sie haben?:</td>
<td><select name="cpuId" onchange="checkArticle(this)">
<%
for (Article article : ctrl.getCertainArticles("CPU")) {
out.print("<option value=\"" + article.getId() + "\">" + article.getName() + "</option>");
}
%>
</select>
</td>
</tr>
...
And the Controller looks something like this:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
int id = Integer.parseInt(req.getQueryString().split("=")[1]);
if (findArticle(id).getCapacity() < 1) {
resp.getWriter().write("<p><font color=\"red\">Leider ist dieser Prozessor nicht mehr verfügbar.</font></p>");
} else {
resp.getWriter().write("");
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
This is how the site looks on startup. So far so good.
But as soon as I choose another item in the dropdown, well, this happens...
I mean at least the id is right.
Its just the stupid AJAX I cant get to work.
In your code you did not specified the controller for your AJAX request. This is the reason you are getting same as the response and the response shown using AJAX.
In console you can also see the full url which is being called AJAX request by hovering on the ?id=2.
function checkArticle(selectedArticleId) {
var url = 'myController?id=' + selectedArticleId.value;
xmlHttpObject.open('GET', url);
xmlHttpObject.onreadystatechange = handleStateChange;
xmlHttpObject.send();
}
In above code replace myController with your actual controller name which points to your servlet.
I am developping an ASP MVC 5 application and I am heading up a problem with the showing of a Toast's Notifaction.
The toast notifaction appears after updating the informations of a user in order to confirm the success of operation.
Unfortunately it disappears quickly (in 2 seconds) after the loading of the next page. I think this is due to the using of server side code (C# in this case), where the entire page reloads, including the javascript files. This is why the toastr disappears too.
Is there any way to keep it a lil longer ?
I tried to o pass the necessary information to the next page, so that page two would know to display the toastr instead of page1 but it didn't work.
This is the code's snippet :
View :
#using (Html.BeginForm("Edit", "Client", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<input type="submit" value="Save" class="btn btn-default" onclick="Update()">
}
<script src="/template/web/js/jquery-2.2.3.min.js"></script>
<script src="~/Scripts/toastr.js"></script>
<script>
function Update() {
toastr.success("Your infos are updated with succes !");
}
</script>
Controller :
[HttpPost]
public ActionResult Edit(int id, Client cmodel)
{
try
{
ClientManagement cdb = new ClientManagement();
if (cdb.UpdateDetails(cmodel))
{
ViewBag.Message = "Client Details Edited Successfully";
}
return RedirectToAction("Profil");
}
catch
{
return View();
}
}
Profil :
public ActionResult Profil()
{
ClientManagement dbhandle = new ClientManagement();
ViewBag.Message = TempData["Message"];
return View(dbhandle.GetClientsInfo());
}
In View Profil (buttom of page) :
<link href="~/Content/toastr.min.css" rel="stylesheet" />
script src="~/scripts/toastr.js"></script>
<script src="~/scripts/toastr.min.js"></script>
#if (ViewBag.Message != null)
{
<script type="text/javascript">toastr.success("#ViewBag.Message");</script>
}
If you want to pass one-time message from an action method to another action method, you will need to use TempData.
[HttpPost]
public ActionResult Edit(int id, Client cmodel)
{
try
{
ClientManagement cdb = new ClientManagement();
if (cdb.UpdateDetails(cmodel))
{
TempData["Message"] = "Client Details Edited Successfully";
}
return RedirectToAction("Profil");
}
catch
{
return View(cmodel);
}
}
You then retrieve it at the next page either inside action method or view. Please note that it would be cleared out at the end of the request after you read it.
Profil.cshtml
#if (TempData["Message"] != null)
{
<script type="text/javascript">toastr.success("#TempData["Message"]");</script>
}
Update
Above code works. If you use default ASP.NET MVC Layout, please make sure you place the script inside Scripts section, so that it renders after jQuery.
#section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet" />
#if (TempData["Message"] != null)
{
<script type="text/javascript">toastr.success("#TempData["Message"]");</script>
}
}
FYI: If you use toastr in other places, you might want to consider bundle and minfy them with other scripts and styles.
If you don't need to redirect to "Profil", then I agree you could use Ajax and on the success callback you could show your toastr. If you need to redirect then you can set the ViewBag.Message as you do and then do something like
#if (ViewBag.Message != null)
{
<script type="text/javascript">toastr.success("#ViewBag.Message");</script>
}
I need to call confirmation message box from codebehind as the user select data from dropdown list and when the selected data is 1 for example a confirmation box will appear to the user to confirm his action
so I did that as below in the code behind I called this JavaScript method:
if (dropdownlist1.SelectedValue == 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "CallConfirmBox", "CallConfirmBox();", true);
}
The script function:
<script type="text/javascript">
function CallConfirmBox() {
if (confirm("هل تريد ان تفصل الباليت؟")) {
alert("سيتم فصل الباليت!");
PageMethods.getdata(onSuccess, onError);
function onSuccess() {
alert(data);
}
function onError() {
alert(errorMessage);
}
}
} else {
//CANCEL – Do your stuff or call any callback method here..
alert("done!");
}
}
And I've added the below line at the beginning of the HTML code:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
and Here is the code behind function that is called from script :
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static void getdata()
{
int nRowsCheck = cMDP.Update_Segregation_PalletPart(nPalletNo);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Update_Segregation_Pallet(nPalletNo, nUserID);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Delete_Segregation_PalletPart_Delete(nPalletNo);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Delete_Segregation_Pallet_Delete(nPalletNo);
}
}
}
}
But I've got the below error:
Page Methods is undefined when run the script !!
Please help as I need some support
First, you'll have to remove one } before the else in your JavaScript.
Change in your code-behind:
if (dropdownlist1.SelectedValue == "1")
For the main problem: Page Methods is undefined:
It seems from your comment that you're using a User Control (ascx). Page Methods cannot be used in a User Control. Please refer to these questions:
PageMethods is not defined
ASP.NET AJAX Page Methods from UserControl
The easiest solution is to use an aspx WebForm instead of an ascx User Control. That's what I've tested and worked.
Or you can use a WebService, as specified in the following question:
Alternate way to use page method inside user control asp.net
But the link to the sample is not working anymore.
Or you can try to use this project that tries to bring ASP.NET AJAX Page Methods to UserControls:
Control Methods for ASP.NET AJAX
You have two problems:
Change you javascript code:
PageMethods.getdata(onSuccess, onError);
function onSuccess(data)
{
alert(data);
}
function onError(data)
{
alert(data);
}
And you code behind getdata method must be a public static string function:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string getdata()
{
//Do some things
return " Operations done successfully!";
}
I am having some issues with just wanting to output some data to the page without having all the HTML load. I am using AJAX to call the same ASPX page in order to populate some data to be returned to the AJAX call. However, it currently does call and it does populate with the correct data BUT it does not seem to want to place that data onto the page.
It currently has an error loading the page of "This webpage is not available: ERR_CONNECTION_RESET"
When I load the page like so:
http://localhost:2765/Default.aspx?Data=viewData
is where I receive the error of "This webpage is not available: ERR_CONNECTION_RESET". Placing some code breaks in, I can confirm that it does populated the needed data but never seems to display it on the page and it also seems to call the page at least 2 times before finally stopping (possibly causing the error above).
The default.aspx code is this:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="AdminPanel._default" %>
<% If loadHTMLPage Then %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8" />
....[more HTML code here]....
<script type="text/javascript">
$(document).ready(function () {
var clickedButtonName = "";
$('#dashboardData, #viewData, #updateData, #addData, #deleteData').click(function() {
clickedButtonName = '#' + $(this).attr("id");
$.ajax({
url: $(this).attr("id") + ".aspx",
dataType: 'html',
timeout: 10000,
success: function (html) {
$("#jQueryLoadHere").html(html);
$('#dashName').html("<strong>" + $(clickedButtonName).data("title") + "</strong> Page");
$('#dashboardData_LI, #viewData_LI, #updateData_LI, #addData_LI, #deleteData_LI').attr('class', 'nav-parent');
$(clickedButtonName + '_LI').attr('class', 'nav-parent nav-active active');
}
});
});
});
</script>
</form>
</body>
</html>
<% Else %>
<% =pageData %>
<% End If %>
The codebehind is this:
Public Class _default
Inherits System.Web.UI.Page
Dim whatData As String = Nothing
Public loadHTMLPage As Boolean = True
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
whatData = Request.QueryString("Data")
Response.Write(whatData)
If whatData = "viewData" And hasLoaded = False Then
loadHTMLPage = False
hasLoaded = True
Call workingGetFEBList()
End If
End Sub
Private Sub workingGetFEBList()
Dim request As WebRequest = WebRequest.Create(apiURL & appID & "/" & formID & "?format=text/xml")
request.Method = "GET"
request.Credentials = CredentialCache.DefaultCredentials
Dim response1 As WebResponse = request.GetResponse()
Dim dataStream As Stream = response1.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim serverResponse As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
Response.Close()
Dim theOutput As String = parseXML2JSON(serverResponse)
pageData = theOutput
End Sub
If I comment out:
Call workingGetFEBList()
pageData = theOutput
and refresh the page - it works just fine loading the page (blank white page with just viewData text on it).
Likewise, just loading the page:
http://localhost:2765/Default.aspx
Loads up the page with the normal HTML just fine.
So what could I be missing??
This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 3 years ago.
so I have a Servlet that retrieves some data from the database. For each row of this data I created an object and added all objects to an ArrayList of that object.
Now, I need the Servlet to pass the ArrayList back to the caller JSP, and print each attribute from each object in the ArrayList.
Do you guys would suggest the best way to do this? They way I am doing it obviously isn't working.
This is my JSP:
<%--
Document : ChartData
Created on : Feb 11, 2014, 11:44:09 PM
Author : fabiolanza
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<script>
function myFunction() {
var request = new XMLHttpRequest();
request.open("GET", "http://localhost:8080/Test/Servlet2", true);
request.onreadystatechange = function() {
if (request.readyState === 4) {
<%
java.util.ArrayList<objects.Data> DataArray = (java.util.ArrayList<objects.Data>) request.getAttribute("DataArray");
for(objects.Data d: DataArray){
out.print(d.type);
out.print(d.value);
out.print(d.month);
}
%>
}
};
request.send(null);
}
</script>
<button onclick="myFunction()">Try it</button>
<br>Home
</body>
</html>
This is my Servlet:
package servlet;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.ArrayList;
/**
*
* #author fabiolanza
*/
public class Servlet2 extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ArrayList<objects.Data> DataArray = new ArrayList<objects.Data>();
request.setAttribute("DataArray", DataArray);
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/Tests";
// Database credentials
String USER = "fabio";
String PASS = "hacking";
Connection conn = null;
Statement stmt = null;
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM data";
ResultSet rs = stmt.executeQuery(sql);
out.println("<html><body>");
// Extract data from result set
while (rs.next()) {
objects.Data d = new objects.Data(rs.getString("Type"), rs.getInt("Value"), rs.getString("Month"));
DataArray.add(d);
}
String link = "/Test/Database.html";
out.println("Database");
out.println("</body></html>");
// request.getRequestDispatcher("ChartData.jsp").forward(request, response);
// Clean-up environment
out.close();
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Thanks!
By the way you are not Setting Any Attrubute (request.setAttribute("<somename>",DataArray)) after getting table datas and not forwarding to correspoting page from servlet [
RequestDispatcher view=request.getRequestDispatcher("ChartData.jsp")
view.forward(request, response)
].
you did this stuf by Ajax method in jsp page. (sorry to say, i don't know if it is possible and i didn't saw any jsp pgmr do it this way yet)
function myFunction() {
------
----
-----
if (request.readyState === 4) { // ?--- what is meant by '===' (or) you mean '==' instead
-----
----
}
Any way..
Two ways u could do this:
1. Using jstl
2. Using scriptlet in jsp (which is depreciated or not a standard nowadays)
-Using Jstl (query more about Jstl in Google if Don't get below mentioned code)
1. In servlet
request.setAttribute("dataArray",DataArray); // set array list
RequestDispatcher view=request.getRequestDispatcher("ChartData.jsp"");
view.forward(request, response);
2. In Jsp page
<c:forEach items="${dataArray}" var="item">
<tr>
<td><c:out value="${item.type}" /></td> //
----
---
</c:forEach>
Using Scriptlet in jsp (Again am Saying it is not a Standard or doing so is Depreciated. Refer this link why JSTL, by BalusC (stackoverflow)):
in jsp page:
1 <% Query database as u mentioned in Servlet page after that
Below mention code is from ur servlet page just apply it to ur Jsp page as shown:
while (rs.next()) { %>
<tr>
<td> <%= rs.getString("Type") %> </td> (or) u could do column number of needed 'field' in u database ie: if "Type" is at 3rd column <%= rs.getString(3) )
<br> <td> <%= rs.getString("Value") %> </td>
<br> <td> <%= rs.getString("Month") %> </td>
%< } %>
2 and just run ur jsp in ur Jsp page in server. its done.
Hope this helps you man.