Reputation:
I want to store data into database using jquery ajax using php but when i click on submit button a empty alert shows up and a message below submit button submitted succesfully but no data is added on my databse.i am at very beginer level in jquery and ajax...Any Help will be appreciated.
Here is my HTML
<form method="POST" >
<pre>
<label for="">Enter Post Topic</label><input type="text" id="txt_topic_name" name="txt_topic_name"><br>
<label for="">Enter Detail</label><textarea id="txt_detail" name="txt_detail"></textarea><br/>
<label for=""></label><input type="button" id="btn_submit" name="btn_submit" value="submit"><br>
</pre>
</form>
<div id="results"></div>
And here is my javascript
$(document).ready(function(){
$('#btn_submit').on('click',function(){
var topic_name = $('#txt_topic_name').val();
var detail = $('#txt_detail').val();
$.ajax({
url : "ajax/add_topic.php",
type : "POST",
data : {'txt_topic_name' : topic_name ,'txt_detail' : detail},
success : function(data){
alert(data);
console.log(data);
$('#results').html("submitted succesfully");
},
error : function(data){
// alert(data);
// console.log(data);
}
});
// return false;
});
});
And PHP
if (isset($_POST['btn_submit'])) {
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$topic_name = mysql_real_escape_string($_POST['txt_topic_name']);
$detail = mysql_real_escape_string($_POST['txt_detail']);
$sql = "INSERT INTO Topics(name,detail) VALUES('$topic_name','$detail')";
$query = mysql_query($sql);
if ($query) {
echo "Sucess";
}
else{
echo "Failed";
}
}
Upvotes: 2
Views: 609
Reputation: 118
if (isset($_POST['txt_topic_name'])) {
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$topic_name = mysql_real_escape_string($_POST['txt_topic_name']);
$detail = mysql_real_escape_string($_POST['txt_detail']);
$sql = "INSERT INTO Topics(name,detail) VALUES('$topic_name','$detail')";
$query = mysql_query($sql);
if ($query) {
echo "Sucess";
}
else{
echo "Failed";
}
}
Upvotes: 1
Reputation: 1331
The data object should be like this
data: {txt_topic_name : topic_name ,txt_detail : detail}
instead of this
data: {'txt_topic_name' : topic_name ,'txt_detail' : detail}
And for a better check for a post, use a hidden input
<input type='hidden' value='true' name='submission' />
Then in php check for submission
if(isset($_POST['submission']) && $_POST['submission'] == 'true'){
//the rest of your code
}
Upvotes: 0