Reputation: 445
I'm trying to make table insert new row with ajax, php, mysql. So far I was able to make the table and on correct data in the fields to submit and save data to database.
Now I'm trying to make some validations and display errors if any but I don't see errors on the page.. I see them only under developer console.
This is my insert row on the table
<tr id="new_row">
<td></td>
<td><input type="text" id="new_name"></td>
<td><input type="email" id="new_email"></td>
<td>
<input type="button" id="insert" value="Insert Row" onclick="insert_row()">
</td>
</tr>
ajax part
function insert_row()
{
var name=document.getElementById("new_name").value;
var email=document.getElementById("new_email").value;
$.ajax
({
type:'post',
url:'insert.php',
data:{
insert_row:'insert_row',
name_val:name,
email_val:email
},
success:function(response) {
if(response!="")
{
var id=response;
var table=document.getElementById("user_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td id='name:"+id+"'>"+name+"</td><td id='email:"+id+"'>"+email+"</td>";
document.getElementById("new_name").value="";
document.getElementById("new_email").value="";
}
}
});
}
And PHP part insert.php
if (isset($_POST['insert_row'])) {
$name=$_POST['name_val'];
$email=$_POST['email_val'];
if($name < 4) { echo 'please enter the name';exit(); }
if($email < 4) { echo 'please enter email';exit(); }
$value = $pdo->prepare('SELECT * FROM client WHERE name= ?');
$value->bindParam(1, $name, PDO::PARAM_STR);
$value->execute();
$result = $value->fetch();
$value1 = $pdo->prepare('SELECT * FROM client WHERE email= ?');
$value1->bindParam(1, $email, PDO::PARAM_STR);
$value1->execute();
$result1 = $value1->fetch();
if ($result > 0)
{
echo 'Name already exist';
exit();
}
elseif ($result1 > 0)
{
echo 'Email already exist';
exit();
}
else
{
// query for insert here
I see none of the errors on the page. Can you show me how to pass them?
Upvotes: 0
Views: 64
Reputation: 2329
As example you can add a div here:
<td>
<input type="button" id="insert" value="Insert Row" onclick="insert_row()">
<div id="error" style="display:none"></div>
</td>
in your ajax:
success:function(response) {
if(response!="")
{
var id=response;
var table=document.getElementById("user_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td id='name:"+id+"'>"+name+"</td><td id='email:"+id+"'>"+email+"</td>";
document.getElementById("new_name").value="";
document.getElementById("new_email").value="";
//just in case the error has been shown before
$('#error').hide()
}else{
$('#error').html(response);
$('#error').show()
}
I Hope this will let you go on.
Upvotes: 1