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??
Related
I have a function in js file(exp : validateMyfile.js) that get a string parameter, this String has a value in myFile.properties and I need this value.
Now I want to get parameter value by spring message source.
How to use spring message source inside js file?
function validate(msg){
-- so I need msg value (value iside myFile.properties);
}
We normally read the message into a javascript variable in jsp file before passing it to a js function as follows
<%#taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<script type="text/javascript">
var successmsg = "<fmt:message key='message.key'/>";
function validate(){
alert(successmsg);
}
</script>
Sometimes, we also pass it as a message from the Controller for a ajax call.
#Controller
public class EmployeeController{
#Value("${employee.add.success}")
private String successMessage;
#Value("${employee.add.failure}")
private String failureMessage;
#ResponseBody
#RequestMapping("/addEmployee")
public String addEmployee(...){
...
if(added){
StatusObject status = new StatusObject();
status.setCode(..);
status.setMessage(successMessage);
}else{
StatusObject status = new StatusObject();
status.setCode(..);
status.setMessage(failureMessage);
}
//return status object
}
}
And access it as follows
$.ajax({
...
success: function(status){
$("#result").text(status.message);
}
});
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");
});
});
});
I'm working inside an iframe and when i finish my job I want to change page (NOT inside iframe) but out side of this iframe, in the main window.
For this I use the following Sub:
Public Sub ChangePage(sender As Object, e As EventArgs)
Dim myNewAsp As New AspNetSqlProvider
Dim dbHandler As New DBHandler
Dim srvHandler As New ServerHandler
Dim aspProvider As New MyAspNetSqlMembershipProvider
Dim errAnswer As New Register
Dim assit As New Assistance
Dim currentUser As MembershipUser = Nothing
Dim message As String = Nothing
Dim msg As String = Nothing
Try
Dim url As String = "/Pages/Account/Login.aspx"
Dim postWindow As Object ' "/Pages/Account/Assistance.aspx"
Dim startWindow As Object ' "/Pages/Support/Asp/Help01.aspx"
Dim urlURI As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim urlPath As String = HttpContext.Current.Request.Url.AbsolutePath
Dim myServerName As String = Strings.Left(urlURI, urlURI.Length - urlPath.Length)
url = myServerName + url
startWindow = Me.GetType().FullName
postWindow = Assistance.PageUrlType
msg = "Hellow World"
'msg = "<script type='text/javascript'> $(document).ready(function(){ window.location.href='" + url + "'; }); </script>"
Dim script As Type = Me.Page.GetType() ' Assistance.PageType.BaseType
Dim postmsg As String = "ChangePage('" & startWindow & "', '" & postWindow & "', '" & msg & "')"
If Not Page.ClientScript.IsStartupScriptRegistered(Me.GetType(), "sendMessage") Then
Page.ClientScript.RegisterStartupScript(script, "sendMessage", postmsg)
End If
Catch eq As SqlException
srvHandler.ErrorAnswer = DBHandler.GetError(1, Nothing, Nothing, eq, Nothing)
srvHandler.ErrorAnswer = srvHandler.ErrorAnswer & "\r\n Asp.SQLProvider.ResetPassword "
ServerHandler._InnerError += srvHandler.ErrorAnswer
Register.errorCall = True
Return
Catch Ex As Exception
srvHandler.ErrorAnswer = DBHandler.GetError(3, Ex, Nothing, Nothing, Nothing)
srvHandler.ErrorAnswer = srvHandler.ErrorAnswer & "\r\n Asp.SQLProvider.ResetPassword"
ServerHandler._InnerError += srvHandler.ErrorAnswer
Register.errorCall = True
Return
End Try
End Sub
I use the following script in the Page inside the iFrame:
<script type="text/javascript">
function ChangePage(startPage, sendPage, message) {
var sPage = document.getElementById(startPage);
sPage.contentWindow.postMessage(message, sendPage);
}
</script>
I also use the following script in the Page I want to change (parent Page):
<script type="text/javascript">
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
event.origin !== message;
event.source.postMessage("'" + message + "'", event.origin);
return;
}
what I got from the above is to have the desired page (the message in the example) BUT inside of the frame.
The scrip in the Help01.aspx page is executed just fine. But in this window, and not in the parent one (Assistance,aspx)
As a result I can't get out of the iFrame (which is inside of a table).
Is someone to know what to do about it?
I think you'll need to use something like postMessage here. It depends on the browsers you need to support, but support is pretty good. That will let you "talk" between the main window and the iFrame.
That link will walk you through how to set it up, but the gist of it is that you'll need to attach an event listener to the main window and then post a message from the iFrame to the outer window. Then do your redirect in the outer window when the message comes in.
So where you have Dim msg As String... you'll want that to be some code that posts a message to the outer frame. Something like window.postMessage(..)
i have a pop up on the index change of a combo box and i need to get the result of the confirm box in the code behind:
Protected Sub service_list_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles service_list.SelectedIndexChanged
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "confirm", x.javaMsg("Do you
want to choose a date?"), True)
If user clicks ok
GridView1.DataSource = x.selectCNT(service_list.SelectedValue)
GridView1.DataBind()
End Sub
this is my function:
Public Function javaMsg(ByVal message As String) As String
Dim sb As New System.Text.StringBuilder()
sb.Append("window.onload=function(){")
sb.Append("confirm('")
sb.Append(message)
sb.Append("')};")
Return sb.ToString()
End Function
note that i'm using asp.net with vb.net
Here is a link that shows how to do it: Call VB method from JavaScript
It basically says there are 2 ways, Ajax or Postback. Here is the postback method:
aspx file:
<script type="text/javascript">
<!--
function callServersideFunction()
{
var someValueToPass = 'Hello server';
__doPostBack('CustomPostBack', someValueToPass);
}
// -->
</script>
aspx.vb file:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Insure that the __doPostBack() JavaScript method is created...
Me.ClientScript.GetPostBackEventReference(Me, String.Empty)
If Me.IsPostBack Then
Dim eventTarget As String
Dim eventArgument As String
If ( (Me.Request("__EVENTTARGET") Is Nothing)
eventTarget = String.Empty
Else
eventTarget = Me.Request("__EVENTTARGET"))
If ( (Me.Request("__EVENTARGUMENT") Is Nothing)
eventArgument = String.Empty
Else
eventArgument = Me.Request("__EVENTARGUMENT"))
If eventTarget = "CustomPostBack" Then
Dim valuePassed As String = eventArgument
' Call your VB method here...
End If
End If
End Sub
Greetings,
Upon a javascript button click, I'm using jquery to post to a url:
$(".optionClick").click(function () {
var caseOption = $(this).attr('title');
$.post("../tracking/RecordClick.aspx?page=gallery&item=" + caseOption);
});
On the page being called, I'm using the following vb.net code to retrieve the querystring variables and write them to a database:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Request.QueryString("page") Is Nothing Then
Dim trackingPage As String = Request.QueryString("page")
Dim trackingIP As String = Request.UserHostAddress
Dim trackingItem As String = Request.QueryString("item")
Dim trackingDate As String = Date.Now().ToString("G")
Try
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
Select Case trackingPage
Case "gallery"
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO UserTrackGallery VALUES ('" & trackingIP & "', '" & trackingItem & "', '" & trackingDate & "')"
cmd.Connection = sqlCon
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Case "products"
Case "search"
End Select
Catch ex As Exception
End Try
Response.Close()
End If
End Sub
In local development, this works perfectly for me recording one database write per button click. On the server however, each post generates anywhere from 1 to 7 database writes.
I've been searching for a solution for a couple of days to no avail. Any help is greatly appreciated!
------------------------------Update--------------------------------
I tried to simplify the process by creating a VB.Net page with only a single button:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="javascript.aspx.vb" Inherits="gallery_javascript" %>
<!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 runat="server">
<title></title>
<script src="../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({ async: false });
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" class="optionClick" value="button" />
</div>
</form>
</body>
</html>
But the problem persists. Firebug reports "Aborted" and the page is called multiple times. I also tried this javascript:
$(document).ready(function () {
$.ajaxSetup({ url: '../tracking/RecordClick.aspx' });
$(".optionClick").click(function () {
$.ajax({ data: 'page=gallery&type=click&item=XYZ' });
});
});
Tried this also:
url = "../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ";
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
try {
req.open("POST", url, false);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.open("POST", url, false);
req.send();
}
}
Each of the javascript blocks above worked locally as intended but failed in the same manner with multiple DB writes and Firebug "Aborted" status.
If I call the url+querystring directly via the browser, everything works as expected.
Could this be related to a delay of some sort since it works locally?
Thanks for the help thus far!
(Edit) Also tried using the full path url in the code above - no improvement.
I found a solution to my problem. It appears that the more recent versions of .Net prevent HTTP POST calls, but this is allowed for localhost (which is why it worked perfectly locally). HTTPWatch and Firebug both showed the .aspx page connection but no response returned. It appears as though the multiple calls were retry attempts to receive a response.
My solution was to create a web service:
Option Strict On
Imports System.Data.SqlClient
Imports System.Data
Imports System
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Web.HttpContext
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://mywebsite.com/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class RecordClick
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function RecordClick() As String
Dim trackingPage As String = ""
Dim trackingIP As String = ""
Dim trackingType As String = ""
Dim trackingItem As String = ""
Dim trackingDate As String = ""
With HttpContext.Current
trackingPage = .Request.Params.Item(0)
trackingIP = .Request.UserHostAddress
trackingType = .Request.Params.Item(1)
trackingItem = .Request.Params.Item(2)
trackingDate = Date.Now().ToString("G")
End With
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
cmd.Connection = sqlCon
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "spInsertRecordClick"
cmd.Parameters.Add("#IPAddress", SqlDbType.NVarChar, 50)
cmd.Parameters("#IPAddress").Direction = ParameterDirection.Input
If trackingIP = "" Then
cmd.Parameters("#IPAddress").Value = DBNull.Value
Else
cmd.Parameters("#IPAddress").Value = trackingIP
End If
cmd.Parameters.Add("#CaseOption", SqlDbType.NVarChar, 50)
cmd.Parameters("#CaseOption").Direction = ParameterDirection.Input
If trackingItem = "" Then
cmd.Parameters("#CaseOption").Value = DBNull.Value
Else
cmd.Parameters("#CaseOption").Value = trackingItem
End If
cmd.Parameters.Add("#TimeDate", SqlDbType.DateTime)
cmd.Parameters("#TimeDate").Direction = ParameterDirection.Input
If trackingDate = "" Then
cmd.Parameters("#TimeDate").Value = DBNull.Value
Else
cmd.Parameters("#TimeDate").Value = trackingDate
End If
cmd.Parameters.Add("#ViewType", SqlDbType.NChar, 10)
cmd.Parameters("#ViewType").Direction = ParameterDirection.Input
If trackingType = "" Then
cmd.Parameters("#ViewType").Value = DBNull.Value
Else
cmd.Parameters("#ViewType").Value = trackingType
End If
cmd.Parameters.Add("#Page", SqlDbType.NVarChar, 50)
cmd.Parameters("#Page").Direction = ParameterDirection.Input
If trackingPage = "" Then
cmd.Parameters("#Page").Value = DBNull.Value
Else
cmd.Parameters("#Page").Value = trackingPage
End If
Try
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
End Try
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Return "Success"
End Function
End Class
This is the javascript I used to call the web service:
$.ajax({
type: "POST",
url: "../tracking/RecordClick.asmx/RecordClick",
data: "page=" + DMOriginatingPage + "&type=" + DMType + "&item=" + DMtitle
});
I had to add the following to the system.web section of the web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
It works perfectly now. I'm not very experienced in this area so there's probably a better solution for what I'm trying to do. However, maybe this will help someone else - took me two weeks to figure this out. :)
I would suggest tracing the problem.
1) Use Firefox + Firebug, open the NET tab and watch how many requests are sent.
2) Paste your AJAX URL in your browser's address bar and see what happens on the server. This way you are sure only one request is made.
Have you tried using the full path from the root of the site in the post call...instead of using the "../"?
Suspect code:
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
try removing the ".." and replacing it with the actual path...I am suspicious that that could be causing your problem.