I am creating a simple form using php, mysql and javascript. The idea is to have the user input the text, then the text is saved to the database, at the same time the latest text that the user have input returns from the database and shows on the same page without refreshing the page. The submitting function worked before I manually added the id column to the table. Please take a look of my codes and help me fix it, thank you.
submit.php ↓
<?php
$conn = mysql_connect('localhost','root','') or die (mysql_error);
$db = mysql_select_db('qinglish_nihaoemilie') or die (mysql_error);
$lastname = $_POST['lastname'];
$table = 'emilieinfo_lastname';
mysql_query("INSERT INTO $table VALUES('$lastname',NULL)");
?>
return.php ↓
<?php
$conn = mysql_connect('localhost','root','');
$db = mysql_select_db('qinglish_nihaoemilie');
$res = mysql_query ("SELECT * FROM emilieinfo_lastname ORDER BY id DESC LIMIT 1");
$result = array();
while ($row = mysql_fetch_array($res)) {
array_push($result, array('lastname' => $row[0]));
}
echo json_encode(array('result' => $result));
?>
Javascript ↓
$('.lastname-container i').click(function(){
var lastnameInput = $('.lastname').val();
var lastnameInputLength = lastnameInput.length;
if (lastnameInputLength > 0) {
$('.lastname').hide();
$(this).hide();
var data = {
lastname: $('.lastname').val(),
};
$.ajax({
type: "POST",
url: "../php/submitinfo-lastname.php",
data: data,
});
$(this).parent().parent().find('p .fa-pencil-square-o').addClass('inline-table');
$(this).parent().parent().find('p .fa-pencil-square-o').show();
// $.getJSON("../php/returninfo-lastname.php", function(result){
// $.each(result, function(i, lastname){
// $(this).parent().parent().find('span').append(lastname + '');
// });
// });
// $.getJSON("../php/returninfo-lastname.php", function(returndata){
// $.each(returndata.result, function(){
// $(this).parent().parent().find('span').append("a"+this['lastname']);
// });
// });
};
if (lastnameInputLength == 0) {
$('.lastname').addClass('red-underline');
$(this).addClass('red-color');
};
});
Database screenshot ↓
HTML ↓
<h2>
<p>last name:
<span></span>
<i style="position:static; display: none;padding-left:5px;" class="fa fa-pencil-square-o"></i>
</p>
<div class="lastname-container">
<input class="lastname" name="lastname" type="text">
<i class="fa fa-check-square-o"></i>
</div>
</h2>