简体   繁体   中英

Form upload with PhP and AJAX to stop reloading the page

I have a PHP form which reloads after submission. I used Ajax to stop reloading it and now it is not submitting the data in the database. Am I missing something here? Like I said if I remove the AJAX it works fine but page reloads. I know I am making a very tiny error.

Form

<form class="form-horizontal" method="post" role="form">
  <div class="form-group">
    <div class="col-sm-6">
       <label for="name" class="control-lable" style="font-size:15px;">Name* :</label>
       <input type="text" class="form-control" name="query_name" id="name" required>
    </div>
    <div class="col-sm-6">
       <label for="email" class="control-lable" style="font-size:15px;">Email* :</label>
       <input id="email" type="email" class="form-control" name="query_email" required>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-12">
      <label for="comments" class="control-lable" style="font-size:15px;">Message*:</label>
      <textarea id="comments"  class="form-control" name="query_message" rows="5" required></textarea>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-12">
      <input type="submit" class="btn btn-block btn-danger" name="contactus" value="Submit">
    </div>
  </div> 
</form>

AJAX

 jQuery(function($) {

    $('form').on('submit', function (e) {
      e.preventDefault();
      var str = $(this).serialize();

$.ajax({
       type: "POST",
       cache: false,
       data:str,
       url:window.location.origin+'/post-page/',
       success:function() {
         console.log('email sent');
         $("#result").html('<div class="alert alert-success"><button type="button" class="close">×</button>Thank you for posting query, You will be replied in next 24 hours</div>');
         $("form").trigger("reset");
       }
      });
    });
  });

PHP

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

    $query_date = date('Y-m-d G:i:s');
    $query_name = strip_tags($_POST['query_name']);
    $query_email = strip_tags($_POST['query_email']);
    $query_message= strip_tags($_POST['query_message'], '<p><br>');

    $ins_query = $conn->prepare("INSERT INTO query (query_date, query_name, query_email, query_message) VALUES (?,?,?,?)");

    $ins_query->bind_param("ssss", $query_date, $query_name, $query_email, $query_message);

    $ins_query->execute();
    $ins_query->close();

   }

You are not specifying the filename extension in ajax url . Change to your-php-form-handling-page.php

In you form page, add id to form

<form class="form-horizontal" id="FrmSubmit" method="post" role="form">
<input type="hidden" name="path_uri" value="<?php echo get_template_directory_uri(); ?> id="path_uri">

In your ajax page

jQuery(function($) {
    $("#FrmSubmit").submit(function(e) {
        e.preventDefault();
        var uri = $('#path_uri').val();

        $.ajax({
            type: "POST",
            url: uri+'/single-palliative.php',
            cache: false,
            data: $('#FrmSubmit').serialize(),
            success: function() {
                console.log('email sent');
                $("#result").html('<div class="alert alert-success"><button type="button" class="close">×</button>Thank you for posting query, You will be replied in next 24 hours</div>');
                $("#FrmSubmit").trigger("reset");
            }
        });
    });
});

In your filename.php

if(isset($_POST['query_name']) && isset($_POST['query_date']) && isset($_POST['query_email']) && isset($_POST['query_message'])){

    $query_date = date('Y-m-d G:i:s');
    $query_name = strip_tags($_POST['query_name']);
    $query_email = strip_tags($_POST['query_email']);
    $query_message= strip_tags($_POST['query_message'], '<p><br>');

    $ins_query = $conn->prepare("INSERT INTO query (query_date, query_name, query_email, query_message) VALUES (?,?,?,?)");

    $ins_query->bind_param("ssss", $query_date, $query_name, $query_email, $query_message);

    $ins_query->execute();
    $ins_query->close();

}

UPDATE : Added hidden field in form and change uri in AJAX url.

1.) give the form an ID:

<form class="form-horizontal" id="formsid" method="post" role="form">

2.) edit your Ajax-function with the correct path to your php file, set data with the id of your form.

    $.ajax({
       type: "POST",
       cache: false,
       data: $("#formsid").serialize(),
       url:path/to/phpfile.php,
       success:function() {
         console.log('email sent');
         $("#result").html('<div class="alert alert-success"><button type="button" class="close">×</button>Thank you for posting query, You will be replied in next 24 hours</div>');
         $("#formsid").trigger("reset");
       }
      });

3.) in PHP change if-statment:

if(is_array($_POST) && isset($_POST)) {
    //your code
} else {
    throw new Exception('Post is empty'.var_dump($_POST));
}

this should work!

try this,

<form class="form-horizontal" method="post" role="form">
<input type="hidden" name="action" value="contactus">
  <div class="form-group">
    <div class="col-sm-6">
       <label for="name" class="control-lable" style="font-size:15px;">Name* :</label>
       <input type="text" class="form-control" name="query_name" id="name" required>
    </div>
    <div class="col-sm-6">
       <label for="email" class="control-lable" style="font-size:15px;">Email* :</label>
       <input id="email" type="email" class="form-control" name="query_email" required>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-12">
      <label for="comments" class="control-lable" style="font-size:15px;">Message*:</label>
      <textarea id="comments"  class="form-control" name="query_message" rows="5" required></textarea>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-12">
      <input type="submit" class="btn btn-block btn-danger" name="contactus" value="Submit">
    </div>
  </div> 
</form>

and then,

if(isset($_POST['action']) && $_POST['action']=="contactus"){

    $query_date = date('Y-m-d G:i:s');
    $query_name = strip_tags($_POST['query_name']);
    $query_email = strip_tags($_POST['query_email']);
    $query_message= strip_tags($_POST['query_message'], '<p><br>');

    $ins_query = $conn->prepare("INSERT INTO query (query_date, query_name, query_email, query_message) VALUES (?,?,?,?)");

    $ins_query->bind_param("ssss", $query_date, $query_name, $query_email, $query_message);

    $ins_query->execute();
    $ins_query->close();

   }
    $.ajax({
           type: "POST",
           cache: false,
           data:{query_name:'query_name',query_email:'query_email',query_email:'query_email'},
           url:window.location.origin+'/post-page/',
           success:function() {
             console.log('email sent');
             $("#result").html('<div class="alert alert-success"><button type="button" class="close">×</button>Thank you for posting query, You will be replied in next 24 hours</div>');
             $("form").trigger("reset");
           }
          });
        });
      });

You should add data: {<your data>} in ajax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM