2016-08-18 8 views
-1

jquery ajaxを使用してフォームを送信しようとしていて、そのページをリロードしたり更新したりしないでください。私は何か不足していますか?フォームが送信されておらず、またページがリロードされています

フォーム

<form method="POST" id="formReviews"> 
<div> 
    <label><b>Name</b></label> 
    <input style="width:400px;" type="text" class="form-control" placeholder="Enter your name" name="txtName" required> 
    </div> 

    <div> 
    <label><b>Area</b></label> 
    <input style="width:400px;" type="text" class="form-control" placeholder="Enter the area you would want to improvise" name="txtArea" required> 
</div> 

<div> 
<label><b>Details</b></label> 
<textarea style="width:400px;" type="comment" class="form-control" row="5" placeholder="Enter the some details" name="txtDetails" required></textarea> 
</div> 
<br> 
<div> 
    <button type="submit" class="btn btn-primary">Submit</button> 
</div> 
</form> 

jqueryの:

$(document).on('submit','formReviews',function(e){ 
    $.ajax({ 
    url: $(this).attr('action'), 
    type: $(this).attr('method'), 
    data: $(this).serialize(), 
    success: function(html){ 
     alert('Review Submitted'); 
    } 
    }); 
    e.preventDefault(); 
    }); 

reviews.php

<?php 
$servername = "localhost:3306"; 
$username = "mebe"; 
$password = "bethe"; 
$dbname = "SpecsCompare"; 

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

$sql="INSERT INTO reviews (Name, Area, Details) VALUES 
    ('".$_POST['txtName']."','".$_POST['txtArea']."','".$_POST['txtDetails']."')"; 

if ($conn->query($sql) === TRUE) { 
echo "New record created successfully"; 
} else { 
echo "Error: " . $sql . "<br>" . $conn->error; 
} 

$conn->close(); 
?> 
+0

変更ボタンタイプのボタンと、それはIDですので、javascriptを使用onclickの機能に –

+1

あなたのjQueryのセレクタは「#formReviews」でなければなりません – Nick

答えて

1

フォームIDを選択しているので、あなたが前に#記号を使用する必要があります。

また、最初の行にe.preventDefaultを使用します。

$(document).on('submit','#formReviews',function(e) { 
    e.preventDefault(); // Add it here 
    $.ajax({ 
    url  : $(this).attr('action'), 
    type : $(this).attr('method'), 
    data : $(this).serialize(), 
    success : function(html){ 
     alert('Review Submitted'); 
    } 
    }); 
}); 
関連する問題