1

I am trying to make my page refresh on submit after it enters in the DB, It wont though.

here is the code

PHP page...

<?php
            if ($_SERVER['REQUEST_METHOD'] == 'POST')
            {

                //check if its an ajax request, exit if not
                if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

                } 

                //check $_POST vars are set, exit if any missing
                if(!isset($_POST["username"]) || !isset($_POST["message"]))
                {
                    $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
                    die($output);
                }

                //Sanitize input data using PHP filter_var().
                $username       = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);

                $message        = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);

                //additional php validation
                if(strlen($username)<4) // If length is less than 4 it will throw an HTTP error.
                {
                    $output = json_encode(array('type'=>'error', 'text' => 'Name is too short!'));
                    die($output);
                }

                if(strlen($message)<5) //check emtpy message
                {
                    $output = json_encode(array('type'=>'error', 'text' => 'Too short message!'));
                    die($output);
                }

                require('config.php');

                $sql="INSERT INTO guestbook(name, comment, datetime) VALUES('$username','$message', now())";
                header("Location:thanks.php");



            }
            ?>      

Here is the JS page

$(document).ready(function(){
                $("#submit").click(function() { 
                    //get input field values
                    var name            = $('#name').val(); 

                    var message         = $('#comment').val();
                    var flag = true;
                    /********validate all our form fields***********/
                    if(name==""){ 
                        $('#name').css('border-color','red'); 
                        flag = false;
                    }

                    if(message=="") {  
                       $('#comment').css('border-color','red'); 
                        flag = false;
                    }
                    /********Validation end here ****/
                    /* If all are ok then we send ajax request to email_send.php *******/
                    if(flag) 
                    {
                        $.ajax({
                            type: 'post',
                            url: "thanks.php", 
                            dataType: 'json',
                            data: 'username='+name+'&message='+message,
                            beforeSend: function() {
                                $('#submit').attr('disabled', true);
                                $('#submit').after('<span class="wait">&nbsp;<img src="image/loading.gif" alt="" /></span>');
                            },
                            complete: function() {
                                $('#submit').attr('disabled', false);
                                $('.wait').remove();
                            },  
                            success: function(data)
                            {
                                if(data.type == 'error')
                                {
                                    output = '<div class="error">'+data.text+'</div>';
                                }else{
                                    output = '<div class="success">'+data.text+'</div>';
                                    $('input[type=text]').val(''); 
                                    $('#guestform textarea').val(''); 
                                }

                                $("#result").hide().html(output).slideDown();           
                                }
                        });
                    }
                });

                //reset previously set border colors and hide all message on .keyup()
                $("#guestform input, #guestform textarea").keyup(function() { 
                    $("#guestform input, #guestform textarea").css('border-color',''); 
                    $("#result").slideUp();
                });
            });

I put the header information in the PHP but everytime I hit submit, it saves the data in the DB then just stays on the page... The text in the textarea also stays there.. I want it to refresh the page so it looks like a blank form again.

KevinM1990112qwq
  • 715
  • 2
  • 10
  • 23

2 Answers2

0

If you want the entire page that you're on to refresh you can use reload() at the end of your callback function making the request.

location.reload();
  • where in the code? Not familiar with JS... Only used this script. – KevinM1990112qwq Apr 26 '16 at 22:31
  • @KevinM1990112qwq try it at the end of the `success` callback, after `$("#result").hide().html(output).slideDown();`. Or better in the `else` branch of `success` callback. – Dan Costinel Apr 26 '16 at 22:40
  • @KevinM1990112qwq Ok. Then test it in another way. Put, in the `else` branch, an `alert(1)`, or `console.log(1)`, and see it, when the submit it ok, if the string `1` its displayed in alert or log. If it does, this means you need to use another js function to refresh the page. – Dan Costinel Apr 26 '16 at 22:45
  • @KevinM1990112qwq Take a look here for alternatives to `location.reload()`. http://stackoverflow.com/a/17259514/4548751 – Dan Costinel Apr 26 '16 at 22:47
  • In your javascript you say you want a json response, but your php file tells you to get redirected to a thank you page which I assume is not a json-formatted page? And from what I can tell; you are never saving the posts into the database! – Muqito Apr 27 '16 at 01:12
0

May you edit your php file like,

$sql= mysqli_query($db, "INSERT INTO guestbook(name, comment, datetime) VALUES('$username','$message', now())");
// if you using mysqli.

if($sql){
    header("Location:thanks.php");
}else{
    $output = json_encode(array('type'=>'error', 'text' => 'failed to insert data'));
    die($output);
}

Your query did not execute without mysql_query/mysqli_query or whatever you use.

and your AJAX

 $.ajax({
      type: 'post',
      url: "thanks.php", 
      dataType: 'json',
      data: 'username='+name+'&message='+message,
      beforeSend: function() {
           $('#submit').attr('disabled', true);
           $('#submit').after('<span class="wait">&nbsp;<img src="image/loading.gif" alt="" /></span>');
      },
      complete: function() {
           $('#submit').attr('disabled', false);
           $('.wait').remove();
      },  
      success: function(data)
      {
           if(data.type == 'error')
           {
                output = '<div class="error">'+data.text+'</div>';
                $("#result").hide().html(output).slideDown();
           }
           else
           {
                output = '<div class="success">'+data.text+'</div>';
                $("#result").hide().html(output).slideDown();
                $('input[type=text]').val(''); 
                $('#guestform textarea').val('');

                // reload
                location.reload();
           }      
      }
 });
sifile
  • 3
  • 3