0

I have this form

<form id="home"  class="validate-form" method="post" enctype="multipart/form-data">
<!-- Form Item -->
<div class="form-group">
    <label>How much money do you need? (Kenya Shillings)</label>
    <div class="input-group">
        <div class="input-group-addon">Ksh</div>
        <input id="moneyAmount" type="number" id="amount" name="amount" class="form-control slider-control input-lg" value="100000" min="10000" max="1000000" data-slider="#moneySlider" required>
    </div>
    <div id="moneySlider" class="form-slider" data-input="#moneyAmount" data-min="10000" data-max="1000000" data-value="100000"></div>
</div>
<!-- Form Item -->
<div class="form-group">
    <label>How long? (months)</label>
    <div class="input-group">
        <input id="monthNumber" type="number" id="duration" name="duration" class="form-control slider-control input-lg" value="10" min="6" max="12" data-slider="#monthSlider" required>
        <div class="input-group-addon">months</div>
    </div>
    <div id="monthSlider" class="form-slider"  data-input="#monthNumber" data-min="6" data-max="12" data-value="10"></div>
</div>
<div class="form-group">
    <label>Telephone Number</label>
    <!-- Radio -->
    <input type="number" id="telephone" name="telephone" class="form-control" required/>
</div>
<!-- Form Item -->
<div class="form-group">
    <label>3 Months Bank or Paypal or Mpesa Statements</label>
    <!-- Radio -->
    <input type="file" name="image" class="ml btn btn-primary btn-lg" /><span>Upload</span>
</div>
<!-- Form Item -->
<div class="form-group">
    <label>Monthly repayment</label>
    <span id="formResult" class="form-total">Ksh<span>262.99</span></span>
</div>
<div class="form-group form-submit">
    <button type="submit" class="btn-submit btn-lg"><span>Send a request!
</span></button>
</div>
</form>

This is the Jquery Script.

$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
alert('subsequent clicks');
function chek(fData) {
    var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
    return reg.test(fData)
     }    

    var phone = $('#telephone').val();
    var amount = $('#amount').val();
    var duration = $('#duration').val();
    var ch = chek(phone);

    if(phone == ""){
      alert('phone cannot be empty');
      return;
    }
    if(amount == ""){
      alert('amount cannot be empty');
      return;
    }
    if(duration == ""){
      alert('duration cannot be empty');
      return;
    }
    if(ch == false){
        alert("Phone number must be a number");
        return;
    }
    if(phone.length < 10 || phone.length > 12 ){
        alert("Phone number must have 10 digits");
        return;
    }
    if(ch == true &&  phone !== "" && amount !== "" && duration !== "" && phone.length == 10){
        var s = phone;
        s = s.replace(/^0+/, '');
        var cc = 254;
        var p = cc+s;
        var pn = p.toString();
        $('#telephone').val(p.toString());
        var formData = new FormData($(this)[0]);
           $.ajax({
        url: 'http://example.com/home.php',  //<== just add it to the end of url ***
        type: 'POST',
        data: formData,
        async: true,
        success: function (data) {
            console.log(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });    
    return false;     
}
    });

This is my PHP code:

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");

  function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyz')
    {
    $str = '';
    $max = mb_strlen($keyspace, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $str .= $keyspace[random_int(0, $max)];
    }
    return $str;
    }

$pass = random_str(4);
/**
Generic Customer Shown Interest
*/

$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "algo";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//Posted Variables

$amount = $_POST['amount'];
$duration = $_POST['duration'];
$telephone = $_POST['telephone'];
$date = date('Y-m-d H:i:s');


//Check If User Exists
$result = $conn->query("select id from users where telephone=$telephone");
if($result->num_rows == 0) {
     //Insert New User
$sql = "INSERT INTO users (telephone, password, service_name,date_submitted) VALUES ('$telephone', '$pass', 'loans','$date')";

if ($conn->query($sql) === TRUE) {
    echo "User Is Inserted";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

} else {
    //Insert New User
$sql2 = "INSERT INTO loans (amount, duration, telephone,documents,status,date)
VALUES ('$amount', '$duration','$telephone','logan2','on-hold','$date')";

if ($conn->query($sql2) === TRUE) {
    echo "Loan Is Inserted";
} else {
    echo "Error: " . $sql2 . "<br>" . $conn->error;
}

$conn->close();
}

?>

As you can tell the form is pretty basic and its only posting data to the server. When I load the page, I am able to insert data into the database but when I click the link again, nothing is inserted.

Is form data blocking me from posting duplicate data to the server?

always-a-learner
  • 3,671
  • 10
  • 41
  • 81
  • F12, console, what are the errors? – Matt Jun 21 '17 at 04:25
  • @mkaatman I am returning `data` from server and if something was inserted, i get the text successfully inserted or an error if there was one. When i submit for the first time the page is loaded, i am able to insert. If i submit again, nothing is posted so there was no error displayed in teh developer console either. –  Jun 21 '17 at 04:27

2 Answers2

0

change ajax part of your code and replace to this code shown below:

<script type="text/javascript">
$.ajax({
type:'POST',
url:'testing2.php',     
data:new FormData($('#svf-form-4')[0]),
cache: false,
contentType: false,
processData: false,
success:function(msg){
 $('#message').html(msg);
}
});
return false;
</script>

Hope it will work .

Harsh Panchal
  • 308
  • 1
  • 8
0

I cant explain what really worked but it seems clearing the form did allow for more post submission although i relied on this comment What does "async: false" do in jQuery.ajax()?

and this page What does "async: false" do in jQuery.ajax()? for inspiration.

This is the success callback

 success: function (data) {
            $("#home").trigger('reset');
            console.log(data);
        },