简体   繁体   中英

HTML5 onclick button opens new page (but I don't want it to do that)

I have a HTML web form that links to a database. I have to use the "type="submit" in order to use the validation function for the required fields. When I do this the page opens a new page. Using "type="button"" does not open the new page but doesn't validate the required fields. I am trying to get AJAX to insert the response from the servlet onto the current page and not open a new page. This is the HTML form.

<form id="EnrollmentForm">
  <p><i>Please complete the form. Mandatory fields are marked with a </i><em>*</em></p>
  <fieldset>
    <legend>New Course Enrollment</legend>
    <label for="StudentID"> Student ID <em>*</em></label>
    <input ID="StudentID" name = "StudentID" autofocus placeholder="12345" required><br>
    <label for="CourseID"> Course ID <em>*</em></label>
    <input id="CourseID" name="CourseID" placeholder="CS4900" required><br>
  </fieldset>
  <p><input onclick="newEnrollment();" type="submit" value="Enroll"></p>
  <p id="result"></p>
</form>

The newEnrollment() function is javascript.

function newEnrollment() {
    validateForm();
    if (validateForm()){
        document.getElementById("result").innerHTML = "The request has been sent.";
        var studentID = document.getElementById("StudentID").value;
        var courseID = document.getElementById("CourseID").value;
        var dataToSend = "?StudentID=" + studentID + "&CourseID=" + courseID;
        req.open("GET", "http://localhost/examples/servlets/servlet/NewEnrollment" + dataToSend, true);
        req.onreadystatechange = handleServerResponse;
        req.send(); 
    }
 }

function handleServerResponse() {
    if ((req.readyState == 4) && (req.status == 200)) {
            var result = req.responseText;
            document.getElementById("result").innerHTML = result;
   }
 }

I will include the Java servlet just for reference. The SQL statement returns an error at the moment that it is not ended properly, but the problem that I want to fix is the new page on submit.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class NewEnrollment extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

// class to write out to the log files
   ServletContext sc = getServletContext();
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();

// Get the Data from the Database 
   try {
Class.forName("oracle.jdbc.OracleDriver");
    System.out.println("Driver loaded");
    String url="jdbc:oracle:thin:@localhost:1521:CS3600";
    String user = "XXXXXXX";
    String pwd = "XXXXXXX";
    String Course_ID = request.getParameter("CourseID");
    String Student_ID = request.getParameter("StudentID");

    Connection DB_mobile_conn = DriverManager.getConnection(url,user,pwd);
    System.out.println("Database Connect ok");//STUDENT_SEQ.CURRVAL
    PreparedStatement prep_stmt = DB_mobile_conn.prepareStatement("INSERT INTO ENROLLMENT VALUES (?, ?)");
    prep_stmt.setString(1,Course_ID);
    prep_stmt.setString(2,Student_ID);
    prep_stmt.executeUpdate();

    String query = "select Student.Student_Last_Name, Student.Student_First_Name, Courses.Course_Name"+
        " from Courses,enrollment,student where enrollment.Student_ID = '"+Student_ID+
        "' and enrollment.course_id = '"+Course_ID+"' and student.student_id = enrollment.student_id"+
        " and courses.course_ID = enrollment.course_ID;";
    Statement query_stmt=DB_mobile_conn.createStatement();
    ResultSet query_rs=query_stmt.executeQuery(query);
    query_rs.next();

    String result = "Student: "+query_rs.getString(1)+", "+query_rs.getString(2)+
        " was enrolled in course: "+query_rs.getString(3)+".";
    query_rs.close();
    query_stmt.close();     
    out.println(result);

  } catch (Exception exp) {
    out.println("Exception = " +exp);
    System.out.println("Exception = " +exp);
  } 
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        doGet(request, response);
    }
}

The prepared statement works. The query returns an SQL error. The result should be "Student: Doe, John was enrolled in Course: CS4900." Looking just for help with the onclick button issue everything else is just for complete awareness of the environment. Thank you for any assistance.

Add an event parameter to newEnrollment . then at the top of that method, call event.preventDefault()

function newEnrollment(event) {
    event.preventDefault();
    .
    .
    .
}

I'd use a listener to register the event handler:

form = document.getElementById("EnrollmentForm");
form.addEventListener('submit', newEnrollment, false);

I think you are over complicating the matter. Try this, target="_self"

reference http://www.w3schools.com/tags/att_a_target.asp

The problem was using a form. By removing the form and fieldset tags and using the onclick button it allows the innerHTML to write back to the page. This solution does not perform validation but it is no longer needed for what I am doing so this works.

<div> 
  <p><i>Enroll a student in a course. </i></p>

    <legend>New Course Enrollment</legend>
    <label for="StudentID"> Student ID </label>
    <input ID="StudentID" name = "StudentID" autofocus placeholder="12345"><br>
<label for="CourseID"> Course ID </label>
    <input id="CourseID" name="CourseID" placeholder="CS4900"><br>

  <p><button id="zero" onclick="newEnrollment()">Enroll</button></p>
  <p id="result"></p>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM