-4

I have a form that is responsible for inserting values in the database. It is working fine but when ever the values are submitted the page gets refreshed, I tried to take help from here, but it didn't worked in my case. can anyone please tell how I can submit the values without refreshing the page.

Code that I have for now is

<?
    if($_POST['submit'])
        {
            $sender_id = mysqli_real_escape_string($con, $_POST['sender_id']);
            $receiver_id = mysqli_real_escape_string($con, $_POST['receiver_id']);
            $message = mysqli_real_escape_string($con, $_POST['message']);

            // execute insert query here
        }
?>

<form class="form-horizontal"  enctype="multipart/form-data" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
    <input type="hidden" name="sender_id" value="<? echo $recruiterid; ?>">
    <input type="hidden" name="receiver_id" value="<? echo $recv_id; ?>">
    <textarea name="message" class="form-control" ></textarea>
    <button type="submit" value="submit" name="submit" class="btn btn-greensea btn-ef btn-ef-7 btn-ef-7b b-0 br-2"><i class="fa fa-envelope"></i> Send Message</button>
</form>
Community
  • 1
  • 1
darcy
  • 85
  • 2
  • 8
  • Remove/rename `name="submit"`, you are overriding default submit DOM method – A. Wolff Dec 04 '15 at 12:36
  • And sorry for the dupe (not really checked it) but that's a wrong dupe, using click event of submit button instead of submit event of the form – A. Wolff Dec 04 '15 at 12:39
  • 1
    @A. Wolff k will check that, the link you have given under duplicacy.. i tried that, but my values are not getting carried to the other script through this code – darcy Dec 04 '15 at 12:41
  • *"Code that I have for now is"* - if that is your full code, you're missing the connection/query. If you are querying, check for errors http://php.net/manual/en/mysqli.error.php on your query and make sure you are using the same MySQL API to connect with as your functions. You also have not given us any JS/jQuery code here. Also make sure that short tags are enabled ` echo` and if not, you'll need to change all of those instances to ` – Funk Forty Niner Dec 04 '15 at 12:52
  • Plus, if you're using your entire code in the same file, you're probably trying to echo before anything was assigned. Use error reporting http://php.net/manual/en/function.error-reporting.php – Funk Forty Niner Dec 04 '15 at 12:53
  • well, this question seems to have gone stale. – Funk Forty Niner Dec 04 '15 at 13:10

1 Answers1

1

You need to use AJAX to submit forms without refreshing. Add this in your JavaScript:

$("form").submit(function (e) {
  e.preventDefault();
  $.post($(this).attr("action"), $(this).serialize(), function () {
    alert("Submitted!");
  });
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252