0

This might be a broad answer to give but i'l try to shorten it up. What i am trying to do is use a form to get some information from the user and "validate the form" using JavaScript. If the validation is a success the form gets submitted. Once this has happened , i am trying to retrieve the data that was entered to the form using java script and display on the same page.(using a modal)

Although i think my logic behind this is wrong. Once the form validates it gets submitted ? once it is submitted the page refreshes ? thus the input data is lost? could this be the reason why i keep on getting empty empty values in the modal ?

Heres the html for the form

<div class="feedback-background">
<div class="feedback-content">
    <div class="close">+</div>
    <img src="../Images/Images2/feedbackimg1.jpg" alt="Givefeedback" style="width:100px;height:100px;">

    <form name="FeedbackForm" action="/action_page.php" onsubmit="return validateForm();displayContent();"
          method="get">
        Name:
        <input id="Name" name="Name" type="text" placeholder="Name">
        E-Mail:
        <input id="E-mail" name="E-mail" type="email" placeholder="E-mail">
        What do you think about us?<br>
        <textarea id="comment" rows="6" cols="33" name="comment"></textarea>
        <br>
        How would you rate us ?
        <br>

        <label><input type="radio" name="rating" id="rating1" value="Excellent" checked>Excellent</label>
        <label><input type="radio" name="rating" id="rating2" value="Very Good">Very Good</label>
        <label><input type="radio" name="rating" id="rating3" value="Average">Average</label>
        <label><input type="radio" name="rating" id="rating4" value="Poor">Poor</label>
        <label><input type="radio" name="rating" id="rating5" value="Extreamly Poor">Extremely Poor</label>
        <input type="submit" id="submit" value="Submit">
    </form>
</div>

Here is the HTML for the modal where the input data will be shown again to the customer

<div class="popup">
    <div class="popuptext" id="myPopup"><p>Thank you <span id="username"></span> ,<br>Your feedback has been
        recorded.<br>
        <br>You commented that"<span id="usercomment"></span>" <br><br>and rated our website "<span
                id="userrating"></span>".
        <br><br>Thank you
        for taking your time to do so.<br><br>You will now be re-directed automatically</p>
    </div>
</div>

Here is the css i used for the form

/*----------comment form----------*/

.feedback-background{
 width: 100%;
 height: 100%;
 background-color: rgba(0,0,0,0.7);
 position: absolute;
 top: 0px;
 display: flex;
 align-items: center;
 justify-content: center;
 display:none;
 }
 .feedback-content{
  width: 500px;
  height: 550px;
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  position:relative;


  }
 #submit{text-transform:uppercase;
 padding:6px 2px;
 margin-right: 40px;
 margin-top: 20px;

 background: #ee0c6e;
 font-weight:600;
 color:white;
 border-radius: 3px; 
 font-size: 10px;
 min-width: 100px;
 text-decoration:none
 }

 input {
 width: 50%;
 display: block;
 margin: 10px 0px;

   }

   label {
   display: block;
  }

 input[type="radio"]{
 width: auto;
 display: inline;
  }
 input[type="submit"]{
 width:10em;height: 2em;
 cursor:pointer;

 }
.close{
position:absolute;
top:0px;
right:14px;
transform:rotate(45deg);
font-size:42px;
cursor:pointer;
 }
#feedbacksubmit{
margin-left:600px;
margin-bottom:50px;
background-color:#484848;
border-radius:14px;
padding:10px;
cursor:pointer;
color:white;
outline:none;
}

This is the CSS i used for the pop up modal

/*-----popup----*/
.popup{
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
position: absolute;
top: 0px;
display: flex;
align-items: center;
justify-content: center;
display:none;

 }
.popuptext{
  width: 100px;
 height: 350px;
 background-color: #000025;
 border-radius: 4px;
 padding: 20px;
 position:relative;
 color:#fff;
 width: 20%;
 height:30%;
 display: block;
 margin: 10px 0px;
 text-align:center;
 margin-left:0px;
 margin-bottom:80px;
 }

 #logo{

margin-right:100px;
float:left;
}

Here are the javascripts i have used.

/*------comments form-----*/

document.getElementById('feedbacksubmit').addEventListener('click',
    function () {
        document.querySelector('.feedback-background').style.display = 'flex';
    }
)


document.querySelector('.close').addEventListener('click',
    function () {
        document.querySelector('.feedback-background').style.display = 'none';
    }
)


function displayContent() {
    var name = document.getElementById("Name").value;
    var comment = document.getElementById("comment").value;

    var ratings = document.getElementById('rating');
    var rate_value;
    for (var i = 0; i < rating.length; i++) {
        if (rating[i].checked) {
            rate_value = rating[i].value;
        }
    }

    /*these lines are used to write the details into the new modal*/
    document.getElementById("username").textContent = name;
    document.getElementById("usercomment").textContent = comment;
    document.getElementById("userrating").innerHTML = rate_value;

    return "";
}


function closePopup() {

    document.querySelector('.popup').style.display = 'none';
}

/*-------validation-----*/
function validateForm() {
    var x = document.forms["FeedbackForm"]["Name"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }
    var z = document.forms["FeedbackForm"]["E-mail"].value;
    if (z == "") {
        alert("Please enter your E-mail address to proceed");
        return false;
    }
    var y = document.forms["FeedbackForm"]["comment"].value;
    if (y == "") {
        alert("Comment section can not be empty");
        return false;
    }

    var a = 0, rdbtn = document.getElementsByName("rating")
    for (i = 0; i < rdbtn.length; i++) {
        if (rdbtn.item(i).checked == false) {
            a++;
        }
    }
    if (a == rdbtn.length) {
        alert("Please select a rating according to you");
        return false;
    }


    document.getElementById('submit').addEventListener('click',
        function () {
            document.querySelector('.feedback-background').style.display = 'none';
            document.querySelector('.popup').style.display = 'flex';
        }
    )
}

Is there a better way ? how can i go about doing this? what have i done wrong

V. Sambor
  • 8,155
  • 4
  • 32
  • 52
Anjula S.
  • 586
  • 5
  • 17
  • 1
    See https://stackoverflow.com/a/34347610/3347968 on how to prevent a form from being submitted and page refresh – Bert Maurau Jul 24 '18 at 22:31
  • 2
    When a normal form submits, the page is reloaded with the response from the endpoint that the form submitted to. Everything about the current page that does not exist in a persistent medium (such as cookies, or Storage) is destroyed, and replaced with the new page. – Taplar Jul 24 '18 at 22:31
  • 2
    You would have to prevent the normal submition with `event.preventDefault();` in order to remain in the same page, and if you want to send data to the endpoint, you can do it with XHR and meanwhile you can display your modal. – V. Sambor Jul 24 '18 at 22:33
  • Thank you @Taplar for your input ,i have taken it into consideration and have gone about to do necessary changes – Anjula S. Jul 25 '18 at 17:22

4 Answers4

2

Without looking at your code too closely, here is the requested "big picture" overview of what happens when a form is submitted, and how to validate a form.

First, the form and what happens when it is submitted.

When you click the submit button, your form data will be sent to the file specified on the form tag - in your case, "/action_page.php". What arrives there are a number of variables (aka "key-value pairs" - but they are variables with a name and a value). Note that the "variable name" is what is specified in the name= attribute of the (for e.g.) input field, and the "variable contents" is whatever is typed into the (for e.g.) input field.

Your back-end PHP file will need to create proper PHP $variables for each of these items, using either the $_POST or $_GET command, depending what method you used in the "method=" attribute of the form tag. As an example, your form has a textarea element called name=comment. On the PHP side, you can write:

$cmt = $_GET['comment'];

and presto! you have the user's comment in a PHP variable $cmt.

You can do the validation at this stage, or you can validate the code in javascript before the file is even submitted (note that javascript can intercept the form submit process and stop it, or continue it.

Then, your PHP file can either send the user back to the same page (in which case, you need a <? php> section at the top to handle that), or on to another page entirely.

IMPORTANT NOTES:

  1. Important: From your specified action= location of the PHP file, you might have some trouble because you started it with a slash. That sends the OS back to the root of the file system to find your file, and is probably not what you want. For now, put the "action_page.php" file in the same location as your index.php file and drop the leading slash.

  2. At the beginning, do not use the same PHP file to receive the form that you are using to display the form to the user. Same goes for AJAX (getting to that). Do things at first so it is easy for you to understand the process, then make it cooler.

  3. You can validate the user data either in JS before you submit, or in PHP after submitting. However, javascript can be read, debugged, and even changed in the DevTools (F12) console - so other than super basic stuff like "Was the field left blank", do not do your important validation in javascript.

  4. NEVER TRUST USER DATA. Some users are hackers and they can OWN you if you do not sanitize the data they enter. Research sanitizing user data and this also will get you started on the understanding part.

AJAX

When you submit a form, the screen will refresh. So what about those websites where you fill-in a form, submit, and nothing refreshes but the changes are updated on the existing page. That is done through AJAX.

AJAX is really very simple - almost simpler than a form. The cardinal rule of getting started with AJAX is the same as my note above: have a different back-end PHP file than the one the user is presently on.

Frankly, these days, we don't really use forms very much anymore. Almost everything we used to do with forms we now do with AJAX - and It Is Easy!

So how does AJAX work? Essentially, javascript sends the form data (see below examples!) to the specified PHP file, which processes the data and echo's back a response. You receive that response, break it up into variables, and change the page accordingly. See references below for more.

NOTE: If you take ten minutes to try the examples in the referenced posts below, you will save yourself HOURS of head scratching. Just reproduce the examples on your own server and play with them a bit.

REFERENCES:

How a form works

HTML Forms vs Ajax

Simple overview of AJAX

Simple login system with ajax

Community
  • 1
  • 1
cssyphus
  • 31,599
  • 16
  • 79
  • 97
  • + Javascript is client-side, and should **never** be trusted to validate inputs. Always validate server-side too. – David Jul 24 '18 at 22:38
  • Thanks, David, I was getting to that... It would be a great help to be able to type as fast as my daughter drives... – cssyphus Jul 24 '18 at 22:40
1

You need to use event.preventDefault() to prevent the default action of the form, which is submitting.

Change

document.getElementById('submit').addEventListener('click',
 function(e){
 document.querySelector('.feedback-background').style.display='none';
 document.querySelector('.popup').style.display='flex';
}

To

document.getElementById('submit').addEventListener('click',
function(e){
 document.querySelector('.feedback-background').style.display='none';
 document.querySelector('.popup').style.display='flex';
 e.preventDefault();
 }

However, preventing the form from submitting will prevent the data from the form from being sent to the server to be processed and saved in the database. To be able to process data sent to the server, you will need to use some server-side programming language and you will need to set the form's action attribute; Javascript is not sufficient for this task.

iota
  • 34,586
  • 7
  • 32
  • 51
1

First off, you want to validate data in a form using JavaScipt. That is simple you could run all of your checks and validate, but the problem that comes next is what do you want your site to do. You want the data to reflect on the page but you haven't mentioned to us the goal of your website. See if I had something simple and wanted to run checks on a form and output somewhere else on the website it is as simple as:

Same Page Validation

  • Grabbing data from form
  • In the form submit code run validate checks on your inputs either using functions or if statements. (google each for best practices).
  • What if a validation fails? you have to handle that by appending notices to the html to show the user that an error validating has occurred.
  • Once your form is finished validating, you have to e.preventDefault() which will prevent site from loading.
  • If the validation worked, grabbed the values of the form input and append them to a html element so you could output them.

Ok but as you can see there are 100's of ways for you to do this even without having a form go through the submission process. Why not just run a function on a onClick that runs the same validation and returns you the data then you could append that to the html.

But on another note, the reason why your data gets deleted is because the form is trying to do something with the data and when the page refreshes nothing happened with it so everything is lost. The proper way to do this is you were trying to build an application would go like this:

Normal Form Submission

  • Once input from user is entered and submit button clicked. Run validation, if any errors prevent form from submitting but if no errors continue
  • Run back end validation on your lets say php file. Run the same validation you did in JS but in PHP or your preferred back end language. If there are any errors you need to study up on displaying php errors on form submission to the user.
  • If everything works you could store the user information in a database, then query for a specific user.
  • If you want same page no reloading information showing you need to study on ajax with php. It's good practice and really cool once you have it working.
  • in order to show the user information you also have to think about when grabbing data from backend. if you are going to show the user that was just entered then you can grab last user of the list.

There are so many ways to go about it and to put the code for all of it to work will take way more time but I hope I gave you an idea of what you could do.

Gianni
  • 126
  • 1
  • 13
0

If you want to validate data before submitting, you need to listen for the submit event of the form. Inside the listener you can retrieve the data from inputs, validate it, set appropriate warnings, if necessary and so on. If the validation failed, you can prevent submitting returning false from the listener.

Andrew Vershinin
  • 1,880
  • 9
  • 13
  • is it possible for me to validate the data before submitting and they display and after that submit??If so could you please explain to me with a simple piece of code to how to go about this , – Anjula S. Jul 24 '18 at 22:36