Jump to content

Nic727

Members
  • Posts

    269
  • Joined

  • Last visited

Posts posted by Nic727

  1. Hi,

     

    I have a very weird problem, but I don't see where is my error.

     

    I have a form where it suppose to send the result into the data base, but Insert into doesn't work at all.

    <?php
    $con = mysql_connect("localhost","root","");
    	mysql_select_db("databasename", $con);
    	mysql_query("SET NAMES 'utf8'");
    
    
     if(!isset($_POST["envoyer"])){
    ?>
    <form action="#action=completed" method="post">
    		<label for="nom">Nom de l'étudiant</label><br>
    			<input type="text" id="nom" name="nom" value="" placeholder="Prénom et nom" maxlength="35"><br>
    		<label for="num">Numéro de l'étudiant</label><br>
    			<input type="text" id="num" name="num" value="" placeholder="#######" maxlength="7"><br>
    							
    		<label for="motpasse">Mot de passe</label><br>
    			<input placeholder="ex:Chaise123" type="text" id="motpasse" name="motpasse" value="" maxlength="25"><br>
    			<label for="motpasse2">Confirmer le mot de passe</label><br>
    			<input placeholder="ex:Chaise123" type="text" id="motpasse2" name="motpasse2" value="" maxlength="25"><br>
    						
    		<label>Associer un milieu de stage</label><br>
    			<select id="milieu" name="milieu">
    				<option value="">Ne pas associer tout de suite</option>
    				<option value="" disabled="disabled">---Milieux de stage---</option>
    				
    				<?php
    					$sql = "SELECT * FROM employeurs";
    					$result=mysql_query($sql,$con);
    				
    					while($row = mysql_fetch_array($result)){
    						
    						echo "<option value='".$row['noemployeur']."'>".$row['nomemployeur']." - ".$row['nomcompagnie']."</option>";
    						
    					}
    				?>
    			</select><br>
    							
    		<label>Associer un superviseur</label><br>
    			<select id="superviseur" name="superviseur">
    				<option value="">Ne pas associer tout de suite</option>
    				<option value="" disabled="disabled">---Superviseurs---</option>
    				<?php
    					$sql = "SELECT * FROM superviseurs";
    					$result=mysql_query($sql,$con);
    				
    					while($row = mysql_fetch_array($result)){
    						
    						echo "<option value='".$row['noemploye']."'>".$row['nomemploye']."</option>";
    						
    					}
    				?>							
    			</select><br>
    						
    		<input type="submit" id="envoyer" name="envoyer" value="Créer"><br>
    </form>
    <?php
    }else{
    	$nom = $_POST["nom"];
    	$num = $_POST["num"];
    	$motpasse = $_POST["motpasse2"];
    	
    	$emp = $_POST["milieu"];
    	$super = $_POST["superviseur"];
    	
    	
    	$sql = "INSERT INTO stagiaires (nometudiant, noetudiant, mdpetudiant)VALUES('$nom', '$num', '$motpasse')";
    	$sql = "INSERT INTO associations (noetudiant, noemployeur, noemploye)VALUES('$num', '$emp', '$super')";
    
    Any ideas?

     

    Don't know if it's because of Wamp or not, but it's very weird since it's working well manually into phpmyadmin with the online editor. Maybe it's how I wrote my variables, but I don't think it's that.

     

    I tried like :

     

    '$num'

    '".$num."'

    $num

    ".$num."

     

    But it's not working at all.

  2. This empty($sujet) should be empty($suj), $sujet is not defined until later on further down page.

    Thank you, it fixed it.

     

    Now I need to get it only send one email instead of two...

     

    Do you think it's because there is two mail() and need to put the first one into a variable?

    mail($destinataire,$sujet,$email_content,$headers);
     
            // Send the email.
            if (mail($destinataire,$sujet,$email_content,$headers)) {
                // Set a 200 (okay) response code.
                http_response_code(200);
                echo "Thank You! Your message has been sent.";
            } else {
                // Set a 500 (internal server error) response code.
                http_response_code(500);
                echo "Oops! Something went wrong and we couldn't send your message.";
            }
    
    EDIT : It worked ;)
  3. Also, is it a good idea to add this for form validation (PHP side) as an example :

     

    $nom = htmlspecialchars(strip_tags(trim($_POST["nom"])));

     

    So in my JS I could have the pattern and validation message showing on my page, but server side I could remove html code....

     

    But still trying to figure what's wrong with http404... All my fields are not empty. Don't know why it think there is something wrong in my syntax?

  4. You have a comment that says this:

     

    // TODO: The rest of the code will go here...
    That's where your additional code should go, not after the function.

     

     

    ... Still not working. I did remove the first function and only put the variables here, but still go to contact.php with error "Oops! There was a problem with your submission. Please complete the form and try again." instead of staying on HTML page. Doesn't seem to get the AJAX working.

     

    EDIT :

     

    Nevermind, I just added the second faction into the first one. I can get the text appear on submit. GREAT!

    But still have the error... Maybe an error when checking if a field is empty? It doesn't seem like that... Also, why is it sending email two times if I remove this part?

  5. $(form) is not defined, because you defined it inside an anonymous function, so it's not available outside You should put the event listener inside the anonymous function.

    Like what?

     

    Instead of :

    $(function() {
        // Get the form.
        var form = $('#ajax-contact');
     
        // Get the messages div.
        var formMessages = $('#form-messages');
     
        // TODO: The rest of the code will go here...
    });
    

    I should have

    
        // Get the form.
        var form = $('#ajax-contact');
     
        // Get the messages div.
        var formMessages = $('#form-messages');
    
    

    only?

  6. Hi,

     

    I followed this tutorial to make contact form working without going physically to the php page.

     

    http://blog.teamtreehouse.com/create-ajax-contact-form

     

    The thing is that this code is not working. I tried on my website with my own contact form and with this code only. Both of them don't work.

     

    Here is my full code for my website :

     

    HTML

    <div id="form-messages"></div>
         
        <form id="ajax-contact" name="email" method="post" action="contact.php">
                    <p>Les champs sont obligatoires*</p>
                     
                <div class="rowform"> 
                    <div class="half gauche"> 
                        <label>Prénom*</label>
                        <input name="prenom" id="prenom" type="text" required>
                    </div>
                      
                    <div class="half droite"> 
                        <label>Nom*</label>
                        <input name="nom" id="nom" type="text" required>
                    </div>
                </div>
                     
                <div class="rowform">
                    <div class="half gauche">
                        <label>Courriel*</label>
                        <input name="courriel" id="courriel" type="email" required>
                    </div>    
                  
                    <div class="half droite"> 
                        <label>Téléphone</label>
                        <input name="phone" id="phone" type="number">
                    </div>    
                </div>
             
                <div class="rowform"> 
                    <label>Sujet*</label>
                    <input name="sujet" id="sujet" type="text" required>
                </div>
                     
                <div class="rowform"> 
                    <label>Votre message*</label>
                    <textarea name="message" required></textarea>
                </div>
                    <div class="end-form">    
                        <button id="submit" class="submit" name="submit" type="submit" value="envoyer"><i class="fa fa-paper-plane" aria-hidden="true"></i> Envoyer</button>
                    </div>    
                </form>
    

    JS

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
            // Get the form fields and remove whitespace.
            $prenom = strip_tags(trim($_POST["prenom"])); //Obligatoire
            $nom = strip_tags(trim($_POST["nom"])); //Obligatoire
            $courriel = filter_var(trim($_POST["courriel"]), FILTER_SANITIZE_EMAIL);//Obligatoire
            $phone = strip_tags(trim($_POST["phone"]));
            $suj = strip_tags(trim($_POST["sujet"])); //Obligatoire
            $nom = str_replace(array("\r","\n"),array(" "," "),$nom);
            $message = trim($_POST["message"]); //Obligatoire
     
            // Check that data was sent to the mailer.
            if (empty($prenom) OR empty($nom) OR empty($courriel) OR empty($sujet) OR empty($message) OR !filter_var($courriel, FILTER_VALIDATE_EMAIL)) {
                // Set a 400 (bad request) response code and exit.
                http_response_code(400);
                echo "Oops! There was a problem with your submission. Please complete the form and try again.";
                exit;
            }
     
            // Set the recipient email address.
            // FIXME: Update this to your desired email address.
            $destinataire = "contact@nicolas-duclos.com"; //to or recipient
     
            // Set the email subject.
            $sujet = $suj; //Obligatoire
     
            // Build the email content. (Corps du message)
            $email_content = "Prenom : $prenom \r\n";
            $email_content .= "Nom : $nom \r\n";
            $email_content .= "Courriel : $courriel \r\n";
            $email_content .= "Telephone : $phone \r\n";
            $email_content .= "Sujet : $sujet \r\n";
            $email_content .= "Message :\r\n \r\n $message \r\n";
         
            // Build the email headers.
            $semi_rand = md5(time());
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
            $headers = 'From :' .$prenom.' ' .$nom.'<' .$courriel. "> \r\n";
            $headers .= 'Reply-To : '.$courriel."\r\n";
            $headers .= "Content-type: text/plain; charset=UTF-8"."\r\n";
     
            mail($destinataire,$sujet,$email_content,$headers);
     
            // Send the email.
            if (mail($destinataire,$sujet,$email_content,$headers)) {
                // Set a 200 (okay) response code.
                http_response_code(200);
                echo "Thank You! Your message has been sent.";
            } else {
                // Set a 500 (internal server error) response code.
                http_response_code(500);
                echo "Oops! Something went wrong and we couldn't send your message.";
            }
     
        } else {
            // Not a POST request, set a 403 (forbidden) response code.
            http_response_code(403);
            echo "There was a problem with your submission, please try again.";
        }
    

    PHP

    $(function() {
        // Get the form.
        var form = $('#ajax-contact');
     
        // Get the messages div.
        var formMessages = $('#form-messages');
     
        // TODO: The rest of the code will go here...
    });
    // Set up an event listener for the contact form.
    $(form).submit(function(event) {
        // Stop the browser from submitting the form.
        event.preventDefault();
     
        // TODO
        // Serialize the form data.
        var formData = $(form).serialize();
     
        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData,
            success: function(response) {
                // Make sure that the formMessages div has the 'success' class.
                $(formMessages).removeClass('error');
                $(formMessages).addClass('success');
     
                // Set the message text.
                $(formMessages).text(response);
     
                // Clear the form.
                $('#prenom').val('');
                $('#nom').val('');
                $('#courriel').val('');
                $('#phone').val('');
                $('#sujet').val('');
                $('#message').val('');
            },
            error: function(data) {
                // Make sure that the formMessages div has the 'error' class.
                $(formMessages).removeClass('success');
                $(formMessages).addClass('error');
     
                // Set the message text.
                if (data.responseText !== '') {
                    $(formMessages).text(data.responseText);
                } else {
                    $(formMessages).text('Oops! An error occured and your message could not be sent.');
                }
            }
        })
     
    });
    

    A lot of thing doesn't work for me.

     

    1. It goes to contact.php instead of staying on my HTML page and activating the div "form-messages".

    2. The JS code is stopping at "// Check that data was sent to the mailer." so even if my input are not empty, it show (on contact.php unfortunately) the error text.

    3. If I put this section under commentary, the mail is sent, but two times instead of one, which is a big issue... Also go on contact.php instead of staying on the current page and show text in "form-messages".

     

     

    Thank you for helping me :)

  7. Thank you.

     

    I think that's the last question I have for the validation. Everything is working, but my code is a bit too big and I just don't know how to optimize my code.

    For now I'm doing a validation for each input one by one, but I just don't know where to start to reduce to number of lines in my code.

    Here is my long code... I need to make a loop, but I thought about that for 1 hour and I'm not sure how to do that.

    var regex_nom = /^[ ]*[a-zA-Z\u00C0-\u017F\-'\ ]+$/;
    var regex_prenom = /^[a-zA-Z\u00C0-\u017F\-'\ ]+$/;
    var regex_no = /^[\a-z\d\-.]{1,}$/i;
    
    function validate1(x){
    
    if (regex_nom.test(x)){ /* True if validate */
    document.getElementById('nom').style.borderColor="green";
    document.getElementById('nom').style.borderWidth="2px";
    document.getElementById('Message1').innerHTML = " ";
    }else{
    document.getElementById('nom').style.borderColor="red";
    document.getElementById('Message1').style.color ="red";
    document.getElementById('Message1').innerHTML = "ERROR MESSAGE";
    }
    }
    
    function validate2(x){
    
    if (regex_prenom.test(x)){ /* True if validate  */
    document.getElementById('prenom').style.borderColor="green";
    document.getElementById('prenom').style.borderWidth="2px";
    document.getElementById('Message2').innerHTML = " ";
    }else{
    document.getElementById('prenom').style.borderColor="red";
    document.getElementById('Message2').style.color ="red";
    document.getElementById('Message2').innerHTML = "ERROR MESSAGE";
    }
    }
    function validate3(x){
    
    if (regex_no.test(x)){ /* True if validate  */
    document.getElementById('no').style.borderColor="green";
    document.getElementById('no').style.borderWidth="2px";
    document.getElementById('Message3').innerHTML = " ";
    
    }else{
    document.getElementById('no').style.borderColor="red";
    document.getElementById('Message3').style.color ="red";
    document.getElementById('Message3').innerHTML = "ERROR MESSAGE";
    }
    }
    
    <form name="formtest" action="" method="POST">
    <label>Nom :</label> <input id="nom" type="text" name="nom"  oninput="validate1(this.value)" required><p id="Message1"></p><br>
    <label>Prénom :</label> <input id="prenom" type="text" name="prenom"  oninput="validate2(this.value)" required><p id="Message2"></p><br>
    <fieldset><legend>Adresse</legend>
    <label>No. :</label> <input id="no" type="text" name="no"  oninput="validate3(this.value)" required><p id="Message3"></p><br>
    <button type="submit" value="submit">Submit</button>
    </form>
    

    There is some people where oninput or other event are not showing in the code. Weird.

  8. ok thank you.

     

    Another question. Maybe it has nothing to do with real validation, but I was checking someone code to know more and I found some HTML5 attributes that can't be found on Google.

    <input type="text" class="form-control input-lg" placeholder="3+1=" id="captcha" required pattern="4" data-validation-required-message="Please prove you're not a robot" aria-invalid="true">
    

    so I know the pattern attribute (new in HTML5), it like regex, but what is data-validation message? I think it just doesn't exist, since there is no information on the web. Also, I don't know how you make the message appear in a specific div... I know the guy is actually using this message here when the field is empty and the message is appearing inside a <ul role="alert"></ul>.

    The same ul is used multiple time for each input.

     

     

    Also, I was thinking about is it better to add a PHP form validation?
    http://www.w3schools.com/php/php_form_validation.asp

    This page doesn't show if regex can be used in php.

  9. Hi,

     

    I'm currently building my regex to validate email and it's a bit complicated since a lot of things can work.

     

    Currently I have something like that :

    ^[a-z\d!#$%&'"*+-/=?^_`{|}~.,]+@[a-z\d-]+\.([a-z]{2,5})$/i
    

    I allowed 2 to 5 character after the final dot. But in Canada we have things like .gc.ca for the government.

     

    Also, ' and ` is the same thing right or not?

     

    One other thing I saw on Outlook login is that they are removing white space and I would like to know how.

     

    For example, " email@hotmail.com " will be the same as "email@hotmail.com" and will be valid (I'm able to login with it). White space will not work if it's in the email itself.

     

    Thank you

     

     

    PS: I would also like to know how to make character with accents working like é, à, ë, etc.

  10. thx. It's working great now!

     

    Just one thing I saw. It's not a problem, but maybe an issue with onblur itself. If I chose an autocomplete answer, it will show wrong until I click somewhere else. Maybe a workaround exist for this problem?

  11. Working weirdly...

    <script>
    function validate(x){
    var regex = /^[a-zA-Z0-9\-\_]{3,16}$/; /* ^ indique le début. $ indique la fin. */
    if (regex.test(x)){
    document.getElementById('champ1').style.borderColor="red";
    document.getElementById('Message').innerHTML = "Vous devez suivre les instructions";
    document.getElementById('Message').style.Color="red";
    }else{
    document.getElementById('champ1').style.borderColor="green";
    document.getElementById('Message').innerHTML = "Bravo!";
    document.getElementById('Message').style.Color="green";
    }
    }
    </script>
    Entrer ce que vous voulez : <input id="champ1" type="text" name="champ"  onblur="validate(this.value)"><br>
    <p id="Message"></p>

    When it's correct it show in red and when not it show in red.

     

     

    PS: What if I have multiple input? I will not be able to have the same function?

  12. Hi,

     

    I'm trying to get my input validating with my regex, but I don't know what's wrong with my code.

    It look normal, but it's not working to change the border color or add the small text.

    <script>
    function validate(x){
    
    var regex = /^[a-zA-Z0-9\-\_]{3,16}$/; /* ^ indique le début. $ indique la fin. */
    
    if (x != regex){
    document.getElementById('champ1').style.borderColor="red";
    document.getElementById('Message').document.write("Vous devez suivre les instructions");
    document.getElementById('Message').style.Color="red";
    }else{
    document.getElementById('champ1').style.borderColor="green";
    document.getElementById('Message').document.write("Bravo!");
    document.getElementById('Message').style.Color="green";
    }
    }
    </script>
    <form name="formulaire" action="" method="post">
    Entrer ce que vous voulez : <input id="champ" type="text" name="champ"  onblur="validate(this)"><br>
    </form>
    <p id="Message"></p>
    

    My goal is that when I "unblur" the field, it check if it match the regex variable. If it's not the same (where my x != regex) the border color is red and the message is appearing with red text. If it's correct, it should be green.

     

    For now it's not working and I don't know why.

     

    Thank you

  13. Hi,

     

    For the moment I have this as directory :

     

    - Animal

    - People

    --- Number1.html

    --- Number2.html

    - test.php

     

    That's just an example, but I would like to get a form showing options to select a folder in the current location.

     

    Here is my code for now :

    <select name='choice'>
    	<option value="" disabled selected hidden>Folders</option>
    		<?php 
    			$folder = getcwd(); 
    			echo $folder;
    			$element = scandir($folder);			
    			foreach($element as $file){
    				if($file != '.' && $file!= '..'){
    			echo "<option>".$file."</option><br/>";}}
    		?>
    </select>
    
    

    For now it show all files/folders in my current location in directory. So it show my test.php in the list.

     

    I would like to only get folders and when I select a folder and click the submit button, it should show another select options with the files inside the chosen folder.

    After when you click the submit button again with the selected file, it should open this file in the browser.

     

    Thank you.

  14. 1. Stay on the same page and just clear the form

    add this : header('location : your_form_page.php');

    after the folowing :

     mail($to, $object, $message, $headers);
    
    2. Remove form and show a message like "Thank you".

    you can do that using sessions in php or using Ajax calls to send the form data to contact.php

     

    http://www.w3schools.com/ajax/

    http://www.w3schools.com/php/php_sessions.asp

     

    Good luck

     

     

    I was thinking about using javascript or jQuery to verify form and make something with that.

     

    Not sure it will work if I will do that :

    header('location : index.html);
    

    It will just reload the page from the top.

     

    I will try to find something with JavaScripts to make the form clear or remove form to show a success message.

  15. The form submits to contact.php. If that's your PHP code, then after sending the email you can show some HTML or redirect to another page.

     

    For the From header, the RFC for email contains several examples of formatting the address in that header. You can write the name then the email address in angle brackets:

     

    https://tools.ietf.org/html/rfc2822#appendix-A.1

     

    Thank you, but for my contact.php I just want to :

     

    1. Stay on the same page and just clear the form

    or

    2. Remove form and show a message like "Thank you".

     

    These thing I can find on the web, but how can I avoid redirecting to contact.php?

  16. Hmm... Weird. What about my form?

    <form method="post" action="contact.php">
    				<p>Les champs sont obligatoires*</p>
    				
    			<div class="rowform">	
    				<div class="half gauche">	
    				    <label>Prénom*</label>
    				    <input name="prenom" id="prenom" type="text">
    				</div>
    				 
    				<div class="half droite">	
    				    <label>Nom</label>
    				    <input name="nom" id="nom" type="text">
    				</div>
    			</div>
    				
    			<div class="rowform">
    				<div class="half gauche">
    					<label>Courriel*</label>
    					<input name="courriel" id="courriel" type="courriel">
    				</div>	
    			 
    				<div class="half droite">	
    					<label>Téléphone</label>
    					<input name="phone" id="phone" type="text">
    				</div>	
    			</div>
    		
    			<div class="rowform">	
    				<label>Sujet*</label>
    				<input name="sujet" id="sujet" type="text">
    			</div>
    				
    			<div class="rowform">	
    				<label>Votre message*</label>
    				<textarea name="message"></textarea>
    			</div>
    				<div class="end-form">	
                        <button id="submit" class="submit" name="submit" type="submit" value="envoyer"><i class="fa fa-paper-plane" aria-hidden="true"></i> Envoyer</button>
    				</div>	
    			</form>
    

    For the other thing :

     

    1464290101-000123.png

  17. I finally found a way to do this : http://www.internetkultur.at/simple-hamburger-drop-down-menu-with-css-and-jquery/

     

    The only probem is that there is no way to do smooth transition between clicked and not clicked.

     

    What I mean is that I have that in my CSS and JQuery :

    jQuery(function($){
        	     $( '.navbar-toggle' ).click(function(){
        	     $('.nav').toggleClass('collapse')
        	     })
            })
    
    @media screen and (max-width: 800px) {
    .nav {
        display:none;
        height:0%;
        transition:all 1s;
    }
    
    .collapse {
     display: block !important; 
     background-color:#252525;
     width:100%;
     text-align:center;
     height:auto;
     right:0px;
     left:0px;
     position:relative;
     overflow:hidden;
    }
    

    I added a transition to make the height of navigation from 0% to auto to kind of "collapse" naturally, but nothing happen. It's just a switch on/off without animation.

  18. Hi,

     

    When I fill my contact form with informations and click on the submit button, I'm redirected to the contact.php file. How can I avoid that?

     

    My current code for my form is that :

    <?php
    
    if(isset($_POST['submit'])){
    	
        $to = 'contact@nicolas-duclos.com';
    
    	/***** Valeurs du formulaire *****/
    	
        $name = $_POST['name']; //Required
        $lastname = $_POST['lastname'];
    
        $email = $_POST['email']; //Required
        $phone = $_POST['phone'];
    
        $object = $_POST['object']; //Required
        $message = $_POST['message']; //Required
    
        $headers = "From: " .$name. "\r\n";
        $headers .= "Reply-To: ".$email."\r\n";
    	$headers .= "Content-type: text/plain; charset=UTF-8" . "\r\n"; 
    
    	$message = " Name: " . $name . "\r\n Last Name: " . $lastname . "\r\n Email: " . $email . "\r\n Telephone: " . $phone . "\r\n Object: " . $object . "\r\n message: " . $message;
    
        mail($to, $object, $message, $headers);
    	
    }
     ?>
    

    Also, there is some stuffs I don't understand when receiving emails.

    Instead of having : FROM [Name, Last Name] with object [Object]

    I have : FROM [Name@server12332.com] Object [Object]. Anyway to do this?

     

    Finally, is there a way to seperate the message from all other informations in $message? Maybe a line or something else.

     

    thank you.

     

     

×
×
  • Create New...