简体   繁体   中英

success/error message keeps disappearing while submitting form

I have an application (editsessionadmin.php) where the user displays their assessment's name, date and time in the relevant text inputs. Now when the user submits, it will display a confirmation, when the user confirms, then by using ajax, it navigates to the updatedatetime.php where it will update the assessment's time and date in the database and display the success or error message at the top of the editsessionadmin.php page.

But I have a small problems.

Problem : Using a div tag, I am able to retrieve the error or success message after the update from the updatedatetime.php script and display it in the editsessionadmin.php script by using this jquery code $("#targetdiv").html(data) . Problem is though is that when the user submits the form, it displays the message and then the message disappears after form is submitted. I want the message to be displayed at the top of the editsessionadmin.php page and not disappear. Why is it disappearing?

Below is the code for editsessionadmin.php

        <script>

    function submitform() {    

    $.ajax({
        type: "POST",
        url: "/updatedatetime.php",
        data: $('#updateForm').serialize(),
        success: function(html){
            $("#targetdiv").html(html);
        }
     });        
}

         function showConfirm(){

          var examInput = document.getElementById('newAssessment').value;
          var dateInput = document.getElementById('newDate').value;
          var timeInput = document.getElementById('newTime').value;

          if (editvalidation()) {

         var confirmMsg=confirm("Are you sure you want to update the following:" + "\n" + "Exam: " + examInput +  "\n" + "Date: " + dateInput + "\n" + "Time: " + timeInput);

         if (confirmMsg==true)
         {
         submitform();   
     }
  }
} 

$('body').on('click', '#updateSubmit', showConfirm); 

            </script>   

        <h1>EDIT AN ASSESSMENT'S DATE/START TIME</h1>   

        <p>You can edit assessment's Date and Start time on this page. Only active assessments can be editted.</p>

        <div id="targetdiv"></div>

        <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validation();">
        <table>
        <tr>
        <th>Course: INFO101</th>
        <th>Module: CHI2513</th>
        </tr>
        </table>
        <p><input id="moduleSubmit" type="submit" value="Submit Course and Module" name="moduleSubmit" /></p>

        </form>


        ....


        <?php
        $editsession = "<form id='updateForm'>

        <p><strong>New Assessment's Date/Start Time:</strong></p>
        <table>
        <tr>
        <th>Assessment:</th>
        <td><input type='text' id='newAssessment' name='Assessmentnew' readonly='readonly' value='' /> </td>
        </tr>
        <tr>
        <th>Date:</th> 
        <td><input type='text' id='newDate' name='Datenew' readonly='readonly' value='' /> </td>
        </tr>
        <tr>
        <th>Start Time:</th> 
        <td><input type='text' id='newTime' name='Timenew' readonly='readonly' value=''/><span class='timepicker_button_trigger'><img src='Images/clock.gif' alt='Choose Time' /></span> </td>
        </tr>
        </table>
        <div id='datetimeAlert'></div>

<button id='updateSubmit'>Update Date/Start Time</button>


        </form>
        ";

        echo $editsession;


        }

        ?>

Below is the code for updatedatetime.php:

<?php

 // connect to the database
 include('connect.php');

  /* check connection */
  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    die();
  }

echo 'sumbit successful';

$sessionname = (isset($_POST['Assessmentnew'])) ? $_POST['Assessmentnew'] : ''; 
$sessiondate = (isset($_POST['Datenew'])) ? $_POST['Datenew'] : ''; 
$sessiontime = (isset($_POST['Timenew'])) ? $_POST['Timenew'] : ''; 

$formatdate = date("Y-m-d",strtotime($sessiondate));
$formattime = date("H:i:s",strtotime($sessiontime));

$updatesql = "UPDATE Session SET SessionDate = ?, SessionTime = ? WHERE SessionName = ?";                                           
$update = $mysqli->prepare($updatesql);
$update->bind_param("sss", $formatdate, $formattime, $sessionname);
$update->execute();

echo 'update successful';

$query = "SELECT SessionName, SessionDate, SessionTime FROM Session WHERE SessionName = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s", $sessionname);
// execute query
$stmt->execute(); 
// get result and assign variables (prefix with db)
$stmt->bind_result($dbSessionName, $dbSessionDate, $dbSessionTime);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();

echo 'select successful';

if ($numrows == 1){

echo "<span style='color: green'>Your Assessment's new Date and Time have been updated</span>";

}else{

echo "<span style='color: red'>An error has occured, your Assessment's new Date and Time have not been updated</span>";

}

        ?>

Ok, to weed through your code, to perform the form submit, this is all you need for the ajax call

function submitupdate() {    

    $.ajax({
        type: "POST",
        url: "/updatedatetime.php",
        data: $('#updateForm').serialize(),
        success: function(html){
            $("#targetdiv").html(html);
        }
     });        
}

This assumes the

/updatedatetime.php

Calculates correctly and echos either the success or failure of the update,

Here is a FIDDLE to show you the minimum you need for the form itself. You don't need to put any method, or action on the form itself, just the form tags.

As far as the button to submit...you can put that anywhere, make it anything, just make sure you give it an ID and attach a click handler to it to submit the form.

You must remove the line that submits the form again in the post call and is exaclty this line updateFormO.submit(); . With the post method you make an ajax call and in the success function you resubmit the form again.

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