-2

Here I am using a contact form. When I click on the submit button instead of displaying "message sent successfully" on the same page, it redirects to blank page.

html

<div class="form">
<div style = "font-size:11px; color:#cc0000; margin-top:10px"></div>
<div id="sendmessage" style="display:none">Your message has been sent successfully.</div>
<div id="errormessage"></div>
<form action="contact.php" method="post" role="form" id="myForm"  class="contactForm">
<div class="form-group">
<input type="text" name="name" required="required" class="form-control input-text" id="clientname" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control input-text" name="email" required="required" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="tel" class="form-control input-text" min="0" maxlength="10" required="required" name="phone" id="subject" placeholder="Phone Number" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control input-text text-area" name="msg" rows="5" required="required" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>

<div class="text-center"><button type="submit" class="input-btn" onclick="sendMsg(2000)">Send Message</button></div>
</form>
</div>

contact.php

<?php
        include("config.php");
        if(!$db)
            echo mysql_error($db);

        $name = mysqli_real_escape_string($db, $_POST['name']);
        $email = mysqli_real_escape_string($db, $_POST['email']);
        $phone = mysqli_real_escape_string($db, $_POST['phone']);
        $message = mysqli_real_escape_string($db, $_POST['msg']);
        $id = uniqid() . sha1($name);

        $sql="INSERT INTO contact (id, Name, Email, Phone, Message) VALUES ('$id', '$name', '$email','$phone','$message');";

        if (!mysqli_query($db,$sql)) 
        {
            die('Error: ' . mysqli_error($db));
        }
?>

contact.js

function sendMsg(duration)
{
   var usr = document.getElementById().value;
   var email = document.getElementById().value;
   var phone = document.getElementById().value;
   var msg = document.getElementById().value;
   if(usr.length < 1 && email.length < 1 && phone.length < 1 && msg.length < 1)
   {
      document.getElementById('sendmessage').style.display = "block";
      setTimeout(function() {
      $('#sendmessage').fadeOut('fast');
      }, 5000);
      var form = document.getElementById("myForm");
      form.reset();
   }     

}

i've added the js code now.

Ujjawal
  • 35
  • 1
  • 5
  • 1
    It navigates to contact.php which performs an action. Since there is no output there, nothing is displayed. You probably want to add a redirect from contact.php to a location of your choosing. If you want to stay on the same page you have to use AJAX. – Jay Blanchard Mar 08 '17 at 16:50
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Mar 08 '17 at 16:51
  • undifined index : $firstnm – Masivuye Cokile Mar 08 '17 at 16:57
  • mixing `mysqli` with `mysql` echo mysql_error($db) – Masivuye Cokile Mar 08 '17 at 17:07
  • where's your js code? – Masivuye Cokile Mar 08 '17 at 17:08
  • @JayBlanchard I think he have some js code that he's not showing us, reading from his button `onclick="sendMsg(2000)` – Masivuye Cokile Mar 08 '17 at 17:11
  • You have a tendency of not accepting answers on your questions – Masivuye Cokile Mar 08 '17 at 17:13
  • we will not be able to help u until u show us your full code including `sendMsg() ` js function – Masivuye Cokile Mar 08 '17 at 17:22
  • that js code is for auto hiding the message after successfully sent of message nothing else.. and it is working fine. i just want to prevent redirection of page. – Ujjawal Mar 08 '17 at 17:26
  • if you dont want to go to another page use php_self as action / or ajax – Masivuye Cokile Mar 08 '17 at 17:31

2 Answers2

3

if you don't want form to redirect to another page, you have two ways, 1. use php_self as a form action or use AJAX(Page will not even refresh with this one), also use prepared statements to prevent sql injections as Jay have suggested above.

Option 1 : PHP_SELF

<?php
include("config.php");

$successMessage = "";

if (isset($_POST['submit'])) {


    //validated your inputs fields
    $name    = $_POST['name'];
    $email   = $_POST['email'];
    $phone   = $_POST['phone'];
    $message = $_POST['msg'];
    $id      = uniqid() . sha1($name);

    $sql = "INSERT INTO contact (id, Name, Email, Phone, Message) VALUES ('$id', '$name', '$email','$phone','$message');";

    //prepare and bind 
    $sql = $db->prepare("INSERT INTO contact (id, Name, Email, Phone, Message) VALUES(?,?,?,?,?)");
    $sql->bind_param("sssss", $id, $name, $email, $phone, $message);

    if ($sql->execute()) {

        $message = "Your message has been sent successfully.";

    }

    $sql->close();
    $db->close();


}

?>
<div class="form">
    <div style = "font-size:11px; color:#cc0000; margin-top:10px"></div>
    <div id="sendmessage"><?php echo $message;?></div>
    <div id="errormessage"></div>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" role="form" id="myForm"  class="contactForm">
        <div class="form-group">
            <input type="text" name="name" required="required" class="form-control input-text" id="clientname" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
            <div class="validation"></div>
        </div>
        <div class="form-group">
            <input type="email" class="form-control input-text" name="email" required="required" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
            <div class="validation"></div>
        </div>
        <div class="form-group">
            <input type="tel" class="form-control input-text" min="0" maxlength="10" required="required" name="phone" id="subject" placeholder="Phone Number" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
            <div class="validation"></div>
        </div>
        <div class="form-group">
            <textarea class="form-control input-text text-area" name="msg" rows="5" required="required" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
            <div class="validation"></div>
        </div>
        <div class="text-center"><button type="submit" name="submit" class="input-btn" onclick="sendMsg(2000)">Send Message</button></div>
    </form>
</div>

Option 2 : AJax

 <div class="form">
    <div style = "font-size:11px; color:#cc0000; margin-top:10px"></div>
    <div id="sendmessage"></div>
    <div id="errormessage"></div>
    <form action="contact" method="post" role="form" id="myForm"  class="contactForm">
        <div class="form-group">
            <input type="text" name="name" required="required" class="form-control input-text" id="clientname" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
            <div class="validation"></div>
        </div>
        <div class="form-group">
            <input type="email" class="form-control input-text" name="email" required="required" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
            <div class="validation"></div>
        </div>
        <div class="form-group">
            <input type="tel" class="form-control input-text" min="0" maxlength="10" required="required" name="phone" id="subject" placeholder="Phone Number" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
            <div class="validation"></div>
        </div>
        <div class="form-group">
            <textarea class="form-control input-text text-area" name="msg" rows="5" required="required" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
            <div class="validation"></div>
        </div>
        <div class="text-center"><button type="submit" name="submit" class="input-btn" id="mybtn">Send Message</button></div>
    </form>
</div>

<script type="text/javascript">

    $('document').ready(function(){
        $('#myForm').on('submit',function(e){
            e.preventDefault(); //prevent default form submition
            var FormData = $('#myForm').serialize();

        $.ajax({

            type : 'post',
            url : 'contact.php';
            data : FormData,
            dataTYpe : 'json',
            encode : true,
            beforeSend : function(){

                $('$mybtn').html('<span class="glyphicon glyphicon-repeat fast-right-spinner"></span> Sending');
            },
            success : function(response){

                response = JSON.parse(response);

                if(response== "ok"){

                    $('sendmessage').html('Your message has been sent successfully.');
                }else{

                    $('errormessage').html(response);
                }

            }

        });

        });


    });


</script>

contact.php

<?php
include("config.php");

$message = "";

if (isset($_POST['submit'])) {

    //validated your inputs fields
    $name    = $_POST['name'];
    $email   = $_POST['email'];
    $phone   = $_POST['phone'];
    $message = $_POST['msg'];
    $id      = uniqid() . sha1($name);

    $sql = "INSERT INTO contact (id, Name, Email, Phone, Message) VALUES ('$id', '$name', '$email','$phone','$message');";

    //prepare and bind 
    $sql = $db->prepare("INSERT INTO contact (id, Name, Email, Phone, Message) VALUES(?,?,?,?,?)");
    $sql->bind_param("sssss", $id, $name, $email, $phone, $message);

    if ($sql->execute()) {

        $message = "ok";

    }else{

        $message = "could not send/ insert";
    }

   echo json_encode($message);


}

?>
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34
  • yes i need help but on the different issue [link](http://stackoverflow.com/questions/42659886/css-effect-on-daterangepicker-not-working?noredirect=1#comment72446976_42659886) if you can help me on this that would be great. – Ujjawal Mar 08 '17 at 18:09
0

Well this can be possible by targeting iframe and hide it. something like this

<iframe name="myframe" id="frame1" src="thankyou.php" style="display:none"></iframe>
<form action="../thankyou.php" method="post" target="myframe">
<input type="submit" name="DoIt" value="DoIt">
</form>    
Prosenjeet Paul
  • 284
  • 2
  • 8