0

Currently if a user leaves the exercise title input blank and has text input in the exercise text, an alert is shown telling the user to complete the full form and vice versa. When the alert appears and ok is pressed the form data is lost and the user has to add all the input again. How would I make the alert appear and pressing ok keeps the user on the same page? I'm unsure if its because I have a hide and show div on clicking 'create new exercise' or something else.

My code is below

CourseA.php

html:

<script>
function showDiv(el1,el2){
    document.getElementById(el1).style.display = 'block';
    document.getElementById(el2).style.display = 'none';
}
</script>
<div class="right">
        <h2 id = 'course_admin_titleA'>Course A</h2>
        <button id= 'create_btnA' onClick="showDiv('is', 'ie')">Create new session</button>
        <button id= 'create_btnB' onClick="showDiv('ie', 'is')">Create new exercise</button>
</div>

<div id= "ie">
    <!-- input form for admin -->
    <form action="courseA.php" method="post" enctype="multipart/form-data"> 
        <table class ="table_exercise">
                <td id = "exercise_titles"><strong> Exercise Title:</strong></td>
                <td><input type="text" name="exercise_title" value="<?php if(isset($_SESSION['a'])){echo $_SESSION['a'];} ?> " size="60" /></td>
            </tr>
            <tr>
                <!-- input text area for admin to type exercise content -->
                <td id = "exercise_titles"><strong> Exercise Text:</strong></td>
                <td><textarea name="exercise_text"  rows="15" cols="50"  ><?php if(isset($_SESSION['b'])){echo $_SESSION['b'];} ?></textarea></td>
            </tr>   
        </table>
        <!-- button with input type 'submit' which is referenced by the php code -->
        <button id= 'create_btnB'input type="submit" name="submit1" > Publish Exercise Now</button>
        <!-- Hide if not clicked -->
        <input type="hidden" value="ie" name="type">
    </form>
</div>

php:

        <?
        session_start();
        //if submit button is set i.e 'publish exercise now' pressed then:
        if(isset($_POST['submit1'])){
            $_SESSION['a'] = $_POST['exercise_title'];  //assign to session variable
            $_SESSION['b'] = $_POST['exercise_text'];
            //local variables taking the input names from the html forms above
            $exercise_title = $_POST['exercise_title'];
            $exercise_text = $_POST['exercise_text'];
                //validation
                if($exercise_title =='' OR $exercise_text==''){
                    echo "<script>alert('Please make sure the exercise has a title and exercise info')</script>";
                    //exit();

                } else {
                    //query to insert the form data from the admin into the exercises table
                    $insert_exercises = "insert into exercises (exercise_title,exercise_text) 
                    values ('$exercise_title','$exercise_text')";
                    //runs query
                    $run_exercises = mysqli_query($con,$insert_exercises); 
                    //JS to tell user exercise has been published
                    echo "<script>alert('Exercise Has been Published!')</script>";
                    //returns to courseA page on the admin panel
                    echo "<script>window.open('courseA.php','_self')</script>";
                } //end of else 
        } //end of IF
        //end of if & end of PHP
        } ?>

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Davidaj
  • 235
  • 3
  • 14
  • 1
    Yes it is what code says to do. Would suggest you to validate form using JavaScript, not using PHP. You used here PHP(form validates when you submit data) to validate your form. – divy3993 Sep 21 '15 at 18:41
  • You can't trust JavaScript alone for form validation. You're going to have to do validation in PHP anyway. – harris Sep 21 '15 at 18:51
  • Do you use this html inside a php file?? – Subin Thomas Sep 21 '15 at 19:02

4 Answers4

1

When the page refreshes, and validation fails, you need to put the failed values back in the field. For example:

<input type="text" name="exercise_title" size="60" />

Should be:

<input type="text" name="exercise_title" values "$_POST['exercise_title']" size="60" />
Andrew
  • 11
  • 1
  • Echoing the results doesn't work since after the alert is pressed courseA is refreshed and the form appears empty when the 'ie' button is clicked. May need to revise my design – Davidaj Sep 21 '15 at 19:01
  • If you're submitting the form to the same page, it will work, since the values exist in the `POST` data. This answer needs a little work, but it's on the right track. – harris Sep 21 '15 at 19:04
1

I don't know the other risks in this, but you can use sessions for this as below. In php use session and assign data entered to a session variable

<?php
session_start();  //start session for using session variable
//if submit button is set i.e 'publish exercise now' pressed then:
if(isset($_POST['submit1'])){
$_SESSION['a'] = $_POST['exercise_title'];  //assign to session variable
$_SESSION['b'] = $_POST['exercise_text'];   //assign to session variable
//local variables taking the input names from the html forms above
$exercise_title = $_POST['exercise_title'];
$exercise_text = $_POST['exercise_text'];

and at html, call these session variables as values of text input and area.

<input type="text" name="exercise_title" value="<?php if(isset($_SESSION['a'])){echo $_SESSION['a'];} ?> " size="60" />
<textarea name="exercise_text"  rows="15" cols="50"  ><?php if(isset($_SESSION['b'])){echo $_SESSION['b'];} ?></textarea>

More validations you required has to be done.

Subin Thomas
  • 1,408
  • 10
  • 19
  • Using a session seems a tad excessive if the data doesn't need to persist beyond that one page. – harris Sep 21 '15 at 19:38
  • @SubinThomas the form data is remaining, however when ok is pressed on the alert box the user is brought to a courseA.php except it is blank(completely white) – Davidaj Sep 21 '15 at 20:00
  • it is coming back to the page after I click into the url and press enter (refresh) but pressing ok on the alert goes to a blank page which should be courseA.php – Davidaj Sep 21 '15 at 20:07
  • @SubinThomas updated my code :) yes it seems to be: echo ""; – Davidaj Sep 21 '15 at 20:35
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/90264/discussion-between-davidaj-and-subin-thomas). – Davidaj Sep 21 '15 at 20:39
1

Andrew is on the right track with his answer, but the code is a bit off, and it doesn't take in to account everything mentioned in the question.

The reason the data is lost is because submitting the form will trigger a POST request to the target page defined in the form's action attribute.

From you're question I understood that you're submitting the form to the same page, so you can retrieve the values from the POST data, as you're you're doing when checking if they're empty.

Your PHP part should be before your html:

<?php
    if(isset($_POST['submit1'])){
        $exercise_title = $_POST['exercise_title'];
        $exercise_text = $_POST['exercise_text'];

        if($exercise_title =='' OR $exercise_text==''){
            // Do your stuff
        } else {
            // Do your other stuff
        }
    } else {
        // Define the variables as empty strings
        // so they can be used when the form hasn't been submitted yet
        $exercise_title = '';
        $exercise_text = '';
    }
?>

Note: You should avoid using short tags such as <? as not every environment supports them.

Then in your HTML handle your divs visibility depending on if the form has been submitted or not:

<div id= "ie" <?php if(!isset($_POST['submit1'])) { echo 'style="display:none"'; } ?>>

And finally echo the values of the input fields:

<input type="text"
  name="exercise_title"
  value="<?php echo htmlentities($exercise_title, ENT_QUOTES, 'UTF-8'); ?>"
  size="60" />

And

<textarea name="exercise_text" rows="15" cols="50">
  <?php echo htmlentities($exercise_text, ENT_QUOTES, 'UTF-8'); ?>
</textarea>

Update: Forgot to mention, that your code is open to SQL injection, so you should take a look at this post

Community
  • 1
  • 1
harris
  • 251
  • 3
  • 12
  • Ok this is definitely along the right lines the user form inputs remain as the alert comes up however pressing ok on the alert brings them to a blank page. the url off the blank page suggesting it should be courseA.php but this is not displaying. Thanks for taking the time to help me. – Davidaj Sep 21 '15 at 19:49
0

This can be done following your way to do it if you are using JQuery. Anyways, it is better to validate the form using Javascript so that you reduce accesses to server.

<?
//if submit button is set i.e 'publish exercise now' pressed then:
if(isset($_POST['submit1'])){
    //local variables taking the input names from the html forms above
    $exercise_title = $_POST['exercise_title'];
    $exercise_text = $_POST['exercise_text'];
        //validation
        if($exercise_title =='' OR $exercise_text==''){
            echo "<script>alert('Please make sure the exercise has a title and exercise info');
                  $('input[name=\"exercise_title\"]').val($exercise_title);
                  $('input[name=\"exercise_text\"]').val($exercise_text);</script>";
            //exit();

        }else{....
pablito.aven
  • 1,135
  • 1
  • 11
  • 29
  • You can just echo the values into the input fields directly, so no need to leave the addition to the client. Also judging from the code in the question, he's not using jQuery. – harris Sep 21 '15 at 18:57
  • After the alert courseA.php is still being refreshed which has the 'ie' div hidden before being clicked. When clicked, the form appears empty again – Davidaj Sep 21 '15 at 18:58
  • haven't used jquery but open to further suggestions – Davidaj Sep 21 '15 at 19:03
  • Using JavaScript for validation doesn't remove the need for validation server side. – harris Sep 21 '15 at 19:41
  • @harris Of course it doesn't, client may have disabled javascript. But it is still a must-do to reduce unnecesary accesses to server. – pablito.aven Sep 22 '15 at 14:16