how to raise the prompt event and post to jsp?

Viewed 84

I want to post a prompt value to a jsp.. but I can't run the jsp page... Are there any mistakes in my code? I want to make a prompt for a user to insert a value, then straight away submit it to a JSP to run the calculation... but it can't run...

html

<html>
<head>
    <title>Lab Exercise 1 for Lab 3</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <script>
        var celcius = prompt("Pleae enter current temperature in celcius.");
        if(celcius!==null){
            $.post("calculation.jsp",
            {temp:celcius},
            );
        }
    </script>
</body>

Jsp

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Temperature Converter</title>
</head>
<body>
    <h1>Celsius to Fahrenheit:</h1>
    <%
        String celsius = request.getParameter("temp");
        double thecelsius = Double.parseDouble(celsius);
        double fahrenheit = ((9/5)*thecelsius + 32);
    %>
    The temperature in Fahrenheit for <%=celsius%> celsius is <%=fahrenheit%>F.
</body>
1 Answers

You are using ajax so you need to return response back and then you can show result inside callback of ajax i.e :

var celcius = prompt("Pleae enter current temperature in celcius.");
if (celcius !== null) {
  $.post("calculation.jsp", {
    temp: celcius
  }, function(data) {
    //here data will come back ..
    $("#result").text(data) //you can set some data to divs..    
  });
}

and your jsp will look like below :

<%
   //other codes
  //below will send back to ajax ...
out.println("The temperature in Fahrenheit for "+celsius+"celsius is "+fahrenheit+"F");
%>

Other way :

You can simply redirect to that page using window.location.href = "calculation.jsp?temp="+celcius . But , this will be GET request not POST .

Related