- Facebook like status update link extractor
- create gmail like app using html5 history api and hashbang
- Facebook like comment script using php jquery and ajax
You can find complete list here Ajax application example.
Today we are going to design a dynamic table, in which we can dynamically add rows to table using javascript remove rows number of times without refreshing a page even once and thats also with cool javascript animation. Say thanks to ajax.
Index.php
Lets start with few dummy rows, and dummy data. This page also contains entry form which we will be using for adding new data to the table.
1 |
<input id="add_new" type="button" value="Add Record"> |
First Name | Last Name | Phone Number | Delete | |
---|---|---|---|---|
jquery | ajax | jquery@ajax.com | 242525 | Delete |
php | mysql | php@mysql.com | 242525 | Delete |
html | css | html@css.com | 242525 | Delete |
wordpress | plugins | wordpress@plugins.com | 242525 | Delete |
1 |
Ajax.php
This file will contain all the processing, like inserting record row in mysql and deleting record row from database table. Before saving the data dont forget to sanitize the input to stop xss attacks and sql injections. We are returning data in a json format
to minimize the connection overload and make application faster. This is how it works in dynamically add rows to table using javascript.
Its a demo app so i havent added database code in it. If you are dealing with database dont forget to use mysql_real_escape_string() or PDO classes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
if(isset($_POST) && count($_POST)){ $action = $_POST['action']; $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $phone = $_POST['phone']; $item_id = $_POST['item_id']; if($action == "save"){ // Add code to save data into mysql echo json_encode( array( "success" => "1", "row_id" => time(), "fname" => htmlentities($fname), "lname" => htmlentities($lname), "email" => htmlentities($email), "phone" => htmlentities($phone), ) ); } else if($action == "delete"){ // Add code to remove record from database echo json_encode( array( "success" => "1", "item_id" => $item_id ) ); } }else{ echo json_encode( array( "success" => "0", "item_id" => "No POST data set" ) ); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
*{ font-family: verdana; font-size: 12px; } input[type='button']{ background: #5B8EEE; width: 90px; height: 30px; border: 1px solid #CBDBFA; color: white; font-weight: bold; margin-right: 10px; } .table-list{ font-family: verdana; font-size: 12px; border: 1px solid #EAEAEA; padding: 2px; } .table-list th{ background: #EDF2F6; border-bottom: 1px dotted #DDDDDD; color: #444444; font-size: 12px; font-weight: normal !important; height: 28px; line-height: 28px; padding-left: 5px; text-align: left; } .table-list td{ border-bottom: 1px dotted #EAEAEA; font-family: Arial,Helvetica,sans-serif; font-size: 12px; height: 28px; padding: 5px; text-align: left; } .table-list tr:hover{ background: #E3F3F9; } .entry-form{ background: #EDF2F6; width: 350px; padding: 10px; border: 5px solid #C5D7E2; box-shadow: 3px 3px 5px #888; position: absolute; top: 25%; left: 35%; display: none; border-radius: 5px; } .entry-form input[type='text']{ border: 1px solid #BBBBBB; box-shadow: 2px 2px 4px #C5D7E2 inset; height: 25px; width: 200px; } .entry-form input[type='text']:focus{ border: 1px solid #C5D7E2; } |
This file contains all the javascript. which includes the functionality to add remove rows in the table dynamically. Main role was played by javascript in this dynamically add rows to table using javascript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
$(document).ready(function(){ $("#save").click(function(){ ajax("save"); }); $("#add_new").click(function(){ $(".entry-form").fadeIn("fast"); }); $("#close").click(function(){ $(".entry-form").fadeOut("fast"); }); $("#cancel").click(function(){ $(".entry-form").fadeOut("fast"); }); $(".del").live("click",function(){ ajax("delete",$(this).attr("id")); }); function ajax(action,id){ if(action =="save") data = $("#userinfo").serialize()+"&action="+action; else if(action == "delete"){ data = "action="+action+"&item_id="+id; } $.ajax({ type: "POST", url: "ajax.php", data : data, dataType: "json", success: function(response){ if(response.success == "1"){ if(action == "save"){ $(".entry-form").fadeOut("fast",function(){ $(".table-list").append(""+response.fname+""+response.lname+""+response.email+""+response.phone+"<a id=""+response.row_id+"" class="del" href="#">Delete</a>"); $(".table-list tr:last").effect("highlight", { color: '#4BADF5' }, 1000); }); }else if(action == "delete"){ var row_id = response.item_id; $("a[id='"+row_id+"']").closest("tr").effect("highlight", { color: '#4BADF5' }, 1000); $("a[id='"+row_id+"']").closest("tr").fadeOut(); } } }, error: function(res){ alert("Unexpected error! Try again."); } }); } }); |
Please visit and download updated code with edit functionality and many other customization options
https://amitpatil.me/add-edit-delete-rows-dynamically-using-jquery-php
- Make sure you have enabled php PDO library, If its not enabled script will not work properly.
- Open php.ini file and edit “error_reporting” and change it to “E_ALL & ~E_NOTICE”
- Add “error_reporting(E_ALL ^ E_NOTICE);” line to your php file.
DB Table Version
[/sociallocker]
dynamically adding removing records in a table (6561 downloads )
ajax_table_edit_delete_rows_db (5963 downloads )
this is the most useful script to enhance user experience. thanks amit..
Yes, the download code was not work.
Is that possible to update the source better version using mysql?
Thanks, for reporting it, I will upload two version, one with database and one without database connectivity.
tabove code is nooot working ….in action column jxt 2 empty boxex are in each cell of table???????????:-( just extracting the data from data bese and nothing else is working in code…….kindly help me
I love your code, I’m new with PHP and im that good with Javascript can you show me how to do this with mySQL database
remove the first line on ajax.php file. and add
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
And inside
if($action == "save"){
write your “insert” query leave “echo json_encode…” statement as it is. Similarly for
if($action == "delete"){
put your delete query.Hey Amit, I have a question. Why does this message displays “Unexpected error! Try again” when I try save or delete the data? Do I need to create a database first to run this sample you have? I didn’t change anything from your code because I want to try it first if it’s working or not and there you go it displays that message. Sorry, I’m new to this. Thank you.
I just downloaded the code and run it, It working fine. You dont need to create the database, without the database it should work, its designed in that way. Which browser are you using and version ?
hello sir
can u please tell me to connect the database with this code.??
thanks
Are you familiar with php mysql ?? Add below code to your ajax.php file, before “extract($_POST);” but before that create a table in database “ajax_table” and
$host = “localhost”;
$db_uname = “root”;
$db_pass = “admin”;
$database = “ajax_table”;
if (!$conn = mysql_connect($host,$db_uname,$db_pass)){
die(‘Could not connect: ‘ . mysql_error());
}else{
mysql_select_db($database,$conn);
}
and then replace the line “// Add code to save data into mysql” with your insert query. Follow the same procedure for delete operation.
$fname = $_POST[‘fname’];
$lname = $_POST[‘lname’];
$email = $_POST[’email’];
$phone = $_POST[‘phone’];
if($action == “save”){
// Add code to save data into mysql
$con=mysql_connect(“localhost”,”root”,””,”rahul_table”);
// Check connection
if (mysql_connect_errno())
{
echo “Failed to connect to MySQL: ” . mysql_connect_error();
}
mysql_query($con,”INSERT INTO info (f_name, l_name, email, phone_no)
VALUES (”,’$fname’, ‘$lname’,’$email’,’$phone’ )”);
mysql_close($con);
Rahul : Here is the complete code, I havent tested it but it should work
$conn = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("rahul_table",$conn) or die(mysql_error());
if(isset($_POST) && count($_POST)){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$item_id = $_POST['item_id'];
$action = $_POST['action'];
if($action == "save"){
$res = mysql_query("insert into info values('','".$fname."','".$lname."','".$email."','".$phone."')");
if($res){
echo json_encode(
array(
"success" => "1",
"row_id" => mysql_insert_id(),
"fname" => htmlentities($fname),
"lname" => htmlentities($lname),
"email" => htmlentities($email),
"phone" => htmlentities($phone),
)
);
}
}
else if($action == "delete"){
$res = mysql_query("delete from info where id = $item_id");
if($res){
echo json_encode(
array(
"success" => "1",
"item_id" => $item_id
)
);
}
}
}else{
echo "No data set";
}
same error here.plz help
I have changed the code, see if it works fine now.
Hi! I tried your codes, I just downloaded it and when i’m trying to run it on my PC, i got an error,
I dont know how to fix it up. The page displays a message box whenever I click Save and Delete.
“Unexpected Error! Please try again”
Huhuhu T_T, I’m doing our thesis. And I think you’re codes will be a really big help to our group!
thank you!
Many user reported me about this erro “Unexpected Error! Please try again”, and every time i downloaded it and testeed it again and found that its working fine at my end, but i am sure now, there must be some problem. Can you please check and tell me if “short_open_tag” is on ? Those who faced this problem must be having
short_open_tag
set toOFF
…is it ?I have just uploaded new code, Please check and let me know if you still get the same error.
Hi, just downloaded the Code from your page and tried to use it. Without changes, I get the “Unexpected Error, Try again” error message.
Firebug shows me the following:
Notice: Undefined index: fname in /Applications/MAMP/htdocs/start/ajax-table/ajax.php on line 4
Notice: Undefined index: lname in /Applications/MAMP/htdocs/start/ajax-table/ajax.php on line 5
Notice: Undefined index: email in /Applications/MAMP/htdocs/start/ajax-table/ajax.php on line 6
Notice: Undefined index: phone in /Applications/MAMP/htdocs/start/ajax-table/ajax.php on line 7
{“success”:”1″,”item_id”:”1″}
Could you tell me what I can do to fix it?
I download it and it dont work. Can help me little bit?
Here is all script
http://workhour.tk/silmaring/3.rar
and here is database.
http://workhour.tk/silmaring/kool.sql
Do you see any error in it ?
hello sir
I am using the above code and again I got the same error.
whats the error ??
Hi, I’ve downloaded the code, unzipped and run, but for me it doesn’t work… Delete don’t’ delete and the save button don’t save… all without error, but it doesn’t work, why? Can you help me? Thank’s!!
Do you have firebug ? Do you see any error there ? Did you connected this code with database ?
Yes, I’ve connected the script with mysql db (I can see my record in the table), but I didn’t wrote any line of code to insert/delete record from db… is this the problem?
@Roberto : Yes thats the problem you need to write the code to make it alive. See above comments (reply to Rahul) to find the code for insertion and deletion operations.
Hi Amit, you’re right!! now all works fine, thank’s!
Glad to know, it worked….cheers !!!
Sorry Amit, I’m here again!! 🙂
This part of your code doesn’t work for me:
….
else if($action == “delete”){
$res = mysql_query(“delete from info where id = $”);
if($res){
echo json_encode(
array(
“success” => “1”,
“item_id” => $item_id
)
);
}
}
…
The error returned is:
TypeError: response is null
if(response.success == “1”){
(script.js row 36)
This means your query failed, try printing your query and run it in phpmyadmin to see whats the problem in query.
in phpmyadmin or in another scrips, for example, the query:
delete from info where id = 1366379681
is correct and do his job very well, but in your code, the query:
delete from info where id = $
return the above error… what does in means the character “$” in your query?
In the JSON response, I see :
“success†=> “1″, “item_id†=> null
Why idem_id is null if I have this code in the beginning of the file? :
$item_id = $_POST[‘$item_id’];
Thanks!
in firebug I see this post value (for example):
action delete
item_id 1366382296
Then change that “$” with $item_id.
I don’t know why, but it doesn’t work… This is the firebug output in the post section:
Parameter: application/x-www-form-urlencoded
action delete
item_id 1366386444
Source:
action=delete&item_id=1366386444
and this is my php code (the sql query work fine in phpmyadmin and the save action is ok, but the delete action don’t work):
“1”,
“row_id” => htmlentities($new_id),
“fname” => htmlentities($fname),
“lname” => htmlentities($lname),
)
);
}
}
if($action == “delete”){
$res = mysql_query(“delete from users where id = ‘$item_id'”);
if($res){
echo json_encode(
array(
“success” => “1”,
“item_id” => $item_id
)
);
}
}
}else{
echo “No data set”;
}
?>
but the JSON responde I sow on delete action si:
“success†=> “1″, “item_id†=> null
it’s a real mistery!!!
Sorry for errors in copy/paste, buy I have this line of cone in the beginnig of the file:
$item_id = $_POST[‘$item_id’];
Send me the code and database, i will take a look in to it. We are close now but lets not stretch it up.
Thank’s Amit! which is your email to send the code?
Sorry i didnt noticed that $, actually it should be “$item_id”, You also say $item_id is null, that means its not set in a code, explore the source code and check the code for Delete button it should have id attribute set, which is not set in your case. Source code should look like below
Delete
notice the ****id=”4″****
It seems to be a problem with mysql_real_escape_string(); If I’m deleting this functions in ajax.php it works. With this functions i get many errors like this, if I’m trying to save a new entry:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user ‘root’@’localhost’ (using password: NO) in /Applications/MAMP/htdocs/start/ajax-table/ajax.php on line 3
Error message : “Access denied for user”, is related to your database connection.
Ahh, I found the problem, it doesn’t work if you don’t establish a mysql connection first in ajax.php. You should make some little changes in your example files.
Script works without database connection, Demo i have created on blog is not at all connected to database.
Yes, that’s right, but: You can’t use “mysql_real_escape_string();” without a database connection. So you have to make an db connection before you use this function. At the moment your demo gives errors, because you are calling the function without a connection to the database.
The mysql_real_escape_string() function needs a live connection to the database, so it can do the right kind of escaping with respect to the connection’s character set. So you need to connect before you do escaping.
So you should change your demo, because it’s a demo without a db connection.
James, Yes thats correct, mysql_real_escape_string() works only if there is database connection, recently i upgraded the code so i might have forgot to remove it. Demo is working fine, i think i forgot to remove it from script i allowed users to download. James, Thanks for pointing it out.
No problem, thanks for this article and your great script.
Hey Amit,
would be nice to see an edit Function in your script. 😉
Its a really good suggestion, If i find time i will definitely try to add editing functionality to this script.
Hey! Its much more better if you add two downloads link. First link is use with database and link two is same what is there! Great script, i love it! But i dont get it work 🙁
Alavi, This is really a good suggestion, I will definitely add 2 script downloads.
Notice: Undefined index: item_id in /var/zpanel/hostdata/zadmin/public_html/silmaring/regkool/ajax.php on line 8
{“success”:”1″,”row_id”:1367903102,”kool”:””}
I have just added a download which is a example with a database connection, which you can directly use as is in your application.
In IE10 when you add a row it goes on an infinite loop of row additions. If you refresh the page it only adds that 1 row like it should but obviously something needs to be adjusted for IE10.
Uhh i just check the demo in IE and yes you are right, Its because IE doesnt support effect method and second reason is IE doesnt support all the good things in web programming so just put if condition before ‘effect’ like, See the updated demo its working fine now, Thanks for the bug report
if ( ! $.browser.msie ) {
$(".table-list tr:last").effect("highlight", {color: '#4BADF5'}, 1000);
}
Fatal error: Uncaught exception ‘PDOException’ with message ‘could not find driver’ in C:\AppServ\www\Mou\config.php:7 Stack trace: #0 C:\AppServ\www\Mou\config.php(7): PDO->__construct(‘mysql:host=loca…’, ‘root’, ‘123’) #1 C:\AppServ\www\Mou\index.php(2): include(‘C:\AppServ\www\…’) #2 {main} thrown in C:\AppServ\www\Mou\config.php on line 7
Please check your phpinfo() and make sure you have PDO drivers installed and enables. If not enable PDO or may be you can also replace the PDO code with plain mysql.
The work is too good. but still display error “Unexpected error! Try again.”….. can u plz sort it out….
Can you please send me your phpinfo() page as a html or image so i can check it with my configuration to tackle the issue. Because apart from that there couldnt be any other issue, as its just a simple script.
Dear Bong, when I download is not work so can you do again .
Thanks you very much for your code.
I waiting for you Becuase I have project relative to this
Because you did not edit config.php file
Dear Bong,
I download source code without data base where I don’t see where config.php file
please tell me I wait you
Thank you
Best regards
Sokkhan
What error do you get ? If you have firefug please check ajax request and see what error it returns ? or best way if you have teamviewer can we have a teamviewer session so i can directly look into the code to check whats going wrong
When I completed information on the textbox when I save it so error Unexpected error! Try again.
I thanks maybe error on the JavaScript
thank you
Best regards,
Sokkhan
Function working fine but got Unexpected error! Try again every time data not reflect on page. But if refresh the page than data show on page….Please help…
that means there is some error in return JSON data, can you please check the response in firebug ? and post it here ?
I make some correction in code and it work fine….But the correction is by heat and try method, so i am not know the exact correction..
Thanx for the code dude…:)
Pinkesh, can you please send me your code so i can compare it with my code, because many users posted this error, and unfortunately its working fine at my end so i am not able to reproduce the error and resolve it.
Please check your inbox….code sent..
please help me you’r code does not work and show this error????
Notice: Undefined variable: title in C:\wamp\www\image\index.php on line 28
Its because you have to disable error reporting in php.ini, or may be add this in your php file
error_reporting(0);
@ini_set('display_errors', 0);
Thank you dear problem solve and working code. again thank you.
Edited php.ini but still get “Unexpexted Error – try again!”
When click on ‘save’ I get the mentioned error and have to cancel or close to continue. It does save the data to my mysql table, but does not display in form. When I try to add another record, it still displays the previous data in my entry-form.
Can you check your firebug reply, so i can answer you properly
In that case you need to send me the firebug log, to i can check whats going wrong. May be you forgot to change the database connection details.
dear Amit, ur script work like a charm. perfect.
but i found my self into trouble coz my little understanding about json data. in ur ajax.php script we can save each record every time we click save button. but i dont want to do that. i want all data store into json then after that the data save into mysql database, load from json data. but i found my self no solution. could you give me an example how to save json data from ur ajax.php file into mysql database. i really gratefull for ur help.
kindly regards,
Mark Kurniawan
#sorry for bad english.
Sorry i didnt get your problem properly, Can you please explain it again, may be a image algorithm.
ok. i want to save the data after all rows in table being viewed in page. how can i do that?
hi! could you write code for update date into database.
thank you
suad
Thanks but it is not working on my pc,nothing happens when i click delete or save,and iam not using a database. i just want to see the effect when i enter data into the form and on delete.But it works on your demo ,why not on my machine?
did you read the note at the bottom, regarding php.ini file settings ?
do I really need them if Iam not going to use mysql and Iam only getting data from an array.please help me here because I want to start from A, before I can proceed to B.
Sorry, ignore the database related settings as you are using plain version, But even if you are not using the database still you have to make changes in ini file, because if error reporting settings are not ther then it will throw “undefined variable abc”, which can cause script not working properly/
Thanks very much!it worked on altering php.ini as advised.but what if I don’t save my files as .php and its just htm
if you are not using the database then you can change the extensions from php to html. It should work fine, or may be you can again make change in php.ini file and tell apache to treat .html files as php files, but this is not the right way i guess. Give it a try changing php to html and it should work with no problems at all.
I got it on second thought.It is all required as iam scripting using php.Thank You Very much again.
hello again,how can i send fields of type “file” .its like icannot see them when I try it out.how can I pick the file name in the ajax script??
There is new HTML5 feature where you can send file contents via ajax, see this tutorial, you have to pick the code that you need from this script https://amitpatil.me/drag-and-drop-multiple-file-upload-with-progress-bar/
let me try hidden form fields first
Amit, thanks for your script, very very usefull, i found the problem and fixit,
Te problem when the error message appear “Unexpected error! Try again.” is because the ajax in ajax.php didn’t found the indexs fname, lname, email etc, the solution is replacing this part of script with extract($_POST), thats all
Thanks again
Its not good to use extract() function, It may open a door for hackers to hack in to your server, so dont use extract() method, Never trust end users.
DEAR I M UNABLE TO GET RESOLVE THE ERROR FOR “UNEXPECTED ERROR, TRY AGAIN”
Did you made changes in php.ini file ? If you didnt make any changed then it will keep throwing that error, and if you check response in firebug you will see something like “Undefined variable xyz”
Hi Amit ,
i was searching for this , i havent try yet it , but will soon test it , dude can u do one more thing in t ?
You have just given and option for add and delete , can you give the option for EDIT also ? , so it will be complete form in a simple manner … please email me @ my id
Hi,
Those who facing “Undefined variable” problem , OPEN your CONFIG.PHP file and after <? just paste this and save
error_reporting(0);
@ini_set('display_errors', 0);
or UNEXPECTED ERROR, TRY AGAIN
how to add functionality to edit the information in the row
Hi amit
if am select one product to store in table using session,but if am refresh the page entire row is cleared ,please give guideline for this methods
I didnt get your problem, Please explain little more.
Amit how to do this in ASP.NET ,It’s really very usefull but it is in PHP,i Need asp.net with C#
You just have to chnage the php code, all the other code is just plain javascript which is fine with .NET as well.
Hi Amit,
I am a php developer and i need to know how can i do it with select button in each row through ajax fetching from database.
i am using your code but when i add a row, it say (Unexpected Error ! try again later)and the data is not saved in the row, but when i refresh the page i found that the data is added to the row what is the issue and how can i solve it please reply..
thanks
What exactly should be replaced with ‘extract($_POST)’? Am getting the same error “Unexpected Error! Try Again!” And in the browser ‘prepare($sql); $q->execute(array($title)); $q->setFetchMode(PDO::FETCH_BOTH); // fetch while($r = $q->fetch()){ echo ”; } ?>’ these lines are displayed before the table. Please help me with this
Did you made the changes i suggested at the end of the post ?
Hi Amit,
First many thanks for sharing this code with us.
I’m new in php and much in the code is not clear to me. I’d try to fix it myself. Anyway, I’m getting error “Unexpected Error” when trying to add or delete an entry. I’ve read all comments but have found nothing to solve my issue.
I did tried both DB and without DB versions, the same error.
The only thing I’m sure is that once I succeed to run without DB version(I don’t remember how, if I’m not mistaken I copied something from page and replaced with code in archive(I don’t remember which exact file)).
Actually I don’t understand the point how we can use “Without DB” version to remember entries, anyway, if there is a way to same data without using SQL would be much preferred.
Thanks in advance,
Ashot.
Please check the response string In fire bug, send me the error. It’s midnight and I am half a sleep, So I will reply you in the morning.
hi amit,
actually i am working as software devloper…i am creating table with two buttons add new row and submit rows data..i am doing this dynamically…when i click on add new button the row gets created…..and on submit click.the data on the texboxes and drop down will get submitted to database….i want new functionality that i want to provide one button on each dynamically created row on that button click it will delete all the row…so can help me out with this in javascript…
thankx
This code is already there, isnt it ?
ype: “POST”,
url: “ajax.php”,
data : data,
dataType: “json”,
success: function(response){
alert(response.success);
if(response.success == “1”){
program me response.success return 0
help me Please
Check if record exists ? and database connection details are correct.
Hi Amin,
The problem is solved, it was coming from MySQL.
Now I have another question and please your help.
In your code you are using SQL table with it’s indexes(fname, lname, email, phone).
In my table entries are divided into two types, and thus I added one more index here(e.g. type).
Adding an entry in entry_form does the job and adds the record in SQL where I can see that type also.
Now I have a button clicking on which I should see table having of that type of entries. SQL query would be like $sql = “SELECT * FROM info where type=gw”
I did try it while opening the page and the query works perfect.
What I did is added an action in script.js
$(“#save”).click(function(){
ajax(“save”);
});
$(“#add_new”).click(function(){
$(“.entry-form”).fadeIn(“fast”);
});
$(“#nav_pbx”).click(function(){
ajax(“show_gw”);
});
It calls function ajax with argument “show_gw”
There I have added one more else if:
function ajax(action,id){
if(action ==”save”){
data = $(“#userinfo”).serialize()+”&action=”+action;
}
else if(action == “delete”){
data = “action=”+action+”&item_id=”+id;
}
else if(action == “show_pbx”){
data = “action=”+action;
}
This is also working. Then it goes to
$.ajax({
type: “POST”,
url: “ajax.php”,
data : data,
dataType: “json”,
success: function(response){
and finally stacks here in success: function(response){.
Actually I can’t get what this row is. I’m debugging the code using firebug, what I see is the process goes to success: function(response){ then it jumps to
error: function(res){
alert(“Unexpected error! Try again.”);
Can you tell me please what is wrong in the code?
I can send you code directly if you want.
Thanks in advance,
AshotAr.
This is confusing, execution pointer should go to either success: or error:, Try adding alert() or console.log() in both the functions.
Hi,
I was facing the same issue as u r facing and i found the solution. Please put all the variable
$fname = mysql_real_escape_string($_POST[‘fname’]);
$lname = mysql_real_escape_string($_POST[‘lname’]);
$email = mysql_real_escape_string($_POST[’email’]);
$phone = mysql_real_escape_string($_POST[‘phone’]);
under if($action == “save”) clause as we are not sending all the parameters when deleting the row.
As ajax.php page expecting all the parameters and we are not providing it in case of deleting.
there is unexpected error !! try again
i need this code plz can u help me 🙂 ??
Did you try setting error_reporting(0); ??
thanx it’s worked
but delete make a problem can i send my code and u modify it for me plz ??
That code will work flawlessly at my end because i have php.ini settings in place, you have to solve it yourself, and i will help you resolve it. Just tell me what error do you see in firebug ??
just send ‘item_id’ also during save
there is no error , when i pres delete it’s only delete from html not from database
and i but the query of delete data from database
if($action == “delete”){
$res = mysql_query(“delete from info where id = ‘$item_id'”);
if($res){
echo json_encode(
array(
“success” => “1”,
“item_id” => $item_id
)
);
}
}
}
so php.ini i manipulate it !!
what can i do ??
Thank you Amit, this tutorial is very helpful for my web development
Hi Amit, Thank you very much for this tutorial, I wonder if you have the script for edit, and post it if you can 🙂
thanks.
this blog is good but it is too bad, there are no id for the buttons but in JS names are there and he passed it in ajax
this is really fantastic superb mindblowing unbelievable and last thing extrodinary…….
Amit, I want the entry form to be placed on the page and not toggle or something like that because when page is long the toggle form stays at the top and one has to scroll before enter data. Please help me, I’m a noob!
You need to make changes in css file, Just open style.css file and find “.entry-form” class and change the “position:absolute;” to “position:fixed;”
Thanks Amit, that was quite simple. However I have another issue. Case is that when I click on delete I have to click on the confirm delete about 4 times before it vanishes. I am using firefox and jquery.
Show me the code.
Your “Advice” to turn off error reporting is a complete rookie recommendation. The problem is NOT with error reporting. The problem is something in your script. Fix the problem with your script and error reporting will not report YOUR script errors.
BAD ADVICE:
Note : I noticed lot of users getting “Unexpected Error, Try again†error, Its because error reporting configuration in php.ini. There could be two solutions
Open php.ini file and edit “error_reporting†and change it to “E_ALL & ~E_NOTICEâ€Â
Add “error_reporting(E_ALL ^ E_NOTICE);†line to your php file.
Ben, thanks for visiting and really appreciate that you gave it a try, but i am not agree when you say its “rookie recommendation” because if you read other users(Tester,TAJ) comments you will notice that they are getting “Notice: Undefined variable” error which can be disabled by error_reporting, It even worked for few users.
Yes, of course turning off error reporting “worked” for them because it hides the actual problem that exists in the code, which is/was undefined variables. The correct thing to do is define them before they are used or check if they are set with isset.
Brief Example:
$fname=””;
OR
if(isset($fname))
Okay, perhaps not a “rookie recommendation”, but nevertheless still not the correct advice, except on a production server as long as you are logging errors so you can see if there are problems.
You, as a programmer should NEVER turn off any error reporting while you are developing, otherwise you wont know there are problems to be fixed. Nice job on the script though.
!!!!!!!!!!!!!!!! PROPER FIX !!!!!!!!!!!!!!!!
Here is the proper fix for your script. In ajax.php line 24, replace that line with the following:
$sql=”INSERT INTO info (fname, lname, email,phone)
VALUES (‘{$fname}’, ‘{$lname}’, ‘{$email}’,'{$phone}’)”;
mysql_query($sql);
The actual problem is that you were trying to do an insert without specifying the column names. Your orignal insert query did not account for the auto increment ID field. Since you did not specify column names, mysql was trying to put each record in the database starting with fname into the ID column.
And PLEEEZE for gawd sake, stop telling people to turn off error reporting to “Fix” something. Error reporting is your best friend and tells you when your programming is bad,
Ben, Many thanks for the solution you provided to the users. But if you download DB version and without making any changes it will work for you(i just tried). Fix you have suggested is definitely a great suggestion, Its good practice to specify column names but in my code i have added ” which inserts auto increment field, have a look at the line number 13 which says
mysql_query("insert into info values('','".$fname."','".$lname."','".$email."','".$phone."')");
. I 100% agree with the last point you suggested about bad programming, i will try to follow it, thanks.Okay, so I re-downloaded, no changes, same problem. So let me detail whats going on. If you are using a newer version of Mysql, I believe 5.0 or newer, your script will break at line 13 of ajax.php. You USED to be able to do like you did. On newer versions of mysql, they way you have it, php is trying to insert a “string” to an integer field.
The actual error this produces if you run that query is : [Err] 1366 – Incorrect integer value: ” for column ‘id’ at row 1. This is because a string is being sent, and newer Mysql wont allow that.
So, some of your users have newer mysql and some dont which explains why for some people it works, and others it does not.
1. Optimum code is to specify the column names and drop the space for the auto-increment as I previously mention in another post.
2.Second option is to Add a ZERO to the blank quotes of your script line 13 as follows:
mysql_query(“insert into info values(‘0’,'”.$fname.”‘,'”.$lname.”‘,'”.$email.”‘,'”.$phone.”‘)”);
3. Third option is to Drop the auto-increment quotes and insert NULL as follows:
mysql_query(“insert into info values(null,'”.$fname.”‘,'”.$lname.”‘,'”.$email.”‘,'”.$phone.”‘)”);
For those who want to know…
One of the changes starting with Mysql version 5.6 is that strict mode is enabled by default. Strict mode basically enforces SQL standards and will error on invalid data types attempting to be inserted into a field. This is why this script will fail for users with strict mode enabled on their Mysql installation.
To see if strict mode is enabled on your Mysql, run the following query from a Mysql command prompt: SELECT @@sql_mode
If it is enabled (which is a good thing) you will see: STRICT_TRANS_TABLES
See my previous post for simple fixes if you are having problems.
Hi – Im trying this clean and getting the “unexpected error”. No DB or anything. Im using ffox 25, jquery 1.10+. everything seems to work ok until i try save the user. Php 5.5/ apache / windows. Demo works fine tho – I have renamed ajax.js and ajax.php to autorow respectively and updated the js file to write to autorow.php (ive also tried with default names) – but same error, any ideas?
Thanks for a cool script!
Do you have firebug ? Can you please check firebug output so i can tell you whats the problem.
Hi – I managed thanks! Cant rememeber what i didi but its working now, very helpful.
For those who want it to be dynamic (PHP) –
simply change the ajax name=”name[]” <– note the two square brackets. This allows multiple input types of name on a single form: ie:
[HTML]
[PHP]
$i=0; //first in array always 0
foreach($_POST[‘name’] as $key => $val){
echo “Name $i: “.$_POST[‘name’][$i].”, Surname: “.$_POST[‘surname’][$i].””;
$i++;//loop counter for each extra box
}
hope syntax is correct
🙂
Hello Sir,
I like your code.
Thank you
Hi Can you do the Search, pagination and include image in adding records?
I need to add a new row with data in an existing table in asp page using ajax. Would anyone please help me in this regard.
Same code will work with dot net as well just change the server part
Thank You very much Sir, it is a brilliant piece of work, i was desperately in need of something similar for making multiple voucher entry
I want to add textboxs values to the table as a new row, on button click
will u plz help me?
Hi. I like this. But one more thing is that EDIT option’s on rows.
can u Guide me How to.
I am working on that, and it will be there soon on blog.
Very nice script! We are using it as an online conference room check out sheet on our company portal. I made some changes to column names and code so we have “Date” and “Time In” that sort automatically using strtotime() and then date() in different places to re-format the numbers. Works much better than the piece of paper we had taped to the conference room door.
Can’t wait for the Edit row option!
Sure, I am working in that as well,soon you will be able to see the demo on my blog, thanks for the appreciation.
Hello
Mr Amit Sir
i tried to implement this codes but still i got an error “Unexpected error! Try again”
even i followed according to your notice for changing error_reporting and also changed short tags set to off
please give me solution
I am using PDO class for database operation, Please check if you have enabled PDO library. And let me know if this works.
Hello Sir i implemented plain HTML version still not running
and i dont know about PDO Lib
There should be no problem running plain version, If you have firebug installed please the status of ajax request and let me know, so i can provide you the exact solution.
Hi Amit, It is a great tutorial. But I am having some problem when enter to the page. And the problem you had mention in the end of the post.
prepare($sql); $q->execute(array($title)); $q->setFetchMode(PDO::FETCH_BOTH); // fetch while($r = $q->fetch()){ */ $res = mysql_query(“select * from info”); while($r = mysql_fetch_assoc($res)){ echo ”; } ?>
I had follow the solution you provided, but still fail.
Still the same error 🙁
cannot get the data from database.
prepare($sql); $q->execute(array($title)); $q->setFetchMode(PDO::FETCH_BOTH); // fetch while($r = $q->fetch()){ */ $res = mysql_query(“select * from info”); while($r = mysql_fetch_assoc($res)){ echo ”; } ?>
Make sure PDO library is enabled
Hello sir,
I downloaded your code…I connected to DataBase. But i getting error when i clicked save buton.
error is “Unexpected error! Try again”. So please help me to execute that code.I installed PDO library.
I am new to php code. so please explain through steps, if is there any steps for enable PDO Library.
Thank you in Advance sir.
I am waiting to Your response.
Have a look at this http://stackoverflow.com/questions/15231676/how-to-enable-pdo-on-appserv-on-windows, Also if you have firebug installed please send me firebug response so i can suggest you some workaround
Hello sir,
Please send me PDO Library link. Which i installed may be, its not working.
I using NetBeans IDE with Xampp server.
It should be inbulit in xampp, You just need to enable it in php.ini file, I think you didnt read the link i provided in previous comment ? Google “how to enable pdo extension xampp” to know how to enable PDO lib in xampp
dear amitpatil, thanks for this amazing post and i need a help can you please tell me how to have a auto number and to keep the entered data in entry form like if i typed email or phone number for next entry i want the same phone and email i want to keep last entered phone and email for next entry thanks in advance. – See more at: https://amitpatil.me/ajax-table-adding-removing-rows-dynamically-using-javascript-animation/#comment-66020
Store the values in javascript that you want to populate in the text boxes and then edit
$("#add_new").click(function(){
this function and set value attribute for input like$(".entry-form input['fname']").val(storedvalue);
[…] my previous similar tutorial Ajax table adding removing rows dynamically using javascript animation i demonstrated how to add and delete records dynamically to the table using jquery which became one […]
thanks dear amit and how to have a auto number in first column?
[…] I'm still mastering my zend skills and not that unequivocally good in it, though we have been operative on some ideas on how can we write a formula where by it adds and removes rows boldly controlling zend horizon something tie to this….https://amitpatil.me/ajax-table-adding-removing-rows-dynamically-using-javascript-animation/ […]
How to add search textbox to make more dynamical.
You have to modify code little bit and and thead, tbody and add below search function
$("#search").keyup(function(){
_this = this;
// Show only matching TR, hide rest of them
$.each($(table+" tbody").find("tr"), function() {
if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) == -1){
if($(this).attr("id") != "newentry")
$(this).hide();
}
else
$(this).show();
});
});
thanks boss..
Hi amit,
Your codeis really nice.It helped me lot in my project. But for my project i want a functinality that after click on save from child window it display on parent window instead of directly save on database anies d then from parent window save all the entries to database at one time. Please helpme on this.I am very new to php and javascript.
Are you using iframes ?
hii m sukhbir
want your help
my problem is that i have to create a table like below Record of patient which is to be filled weekly
Patient Name…………… Email abc@gmail.com
date Weight Kcal BMI AGE
15/2 50.5 70.7 80.8 30
22/2 51.2 65.7 80.3 29
add button submit button
when i click on add button a row should be add when submit it should to go to email abc@gmail.com
and next week when to update the old table with all record should be display
and by clicking add (i can update table and submit on email with new updated weekly on mail)
Plz mail the code if possible
Thanks & Regard
Sukhbir Singh
Sukhbir, Your requirements are special, and need few modifications.
do you have the zip file for this tutorial? i need this example not your new one
how to use Dynamic combobox-listbox-drop-down using php/mysql?
what ever data i added in combo box that will be store into database how it is possible please help me..
Before loading the page, fetch dropdown options in php and print them all in page as a javascript variable and using jquery pass those values to dropdown list.
Can you please send the entire code for edit delete and adding of rows dynamically. need it badly..
There is download button at the bottom. Inside “This content is locked!”
Hello there,
I have made changes to the ajax.php page and linked my mysql but when i run index.php i get table with getRecords(); ?> $eachRecord){ ?> what is this problem?
hey its working now the ajax_table.class_nodb.php but address field when i enter and save it says undefined.
Can you post firebug console log ?
Thanks for a wonderful code. Actually I was looking for the same but with jsp and oracle database and I am new to this world. Can you help me out please ? Thanks in advance..
Thx for posting this. I set up the basic version of the form modifiying the index.php page to pull fields out of a test database (same field names) and also modifying the ajax.php script to connect to the test database. Am using script.js with no mods. I’m running into 2 problems.
1) When I add a new user ajax.php executes the call correctly and adds the person to the database; the popup dismisses but the script repeately ads new fields for this new person to the html table, visually and does not quit (to stop it I have to reload the page). I use Firebug in Firefox and looked at the JSON response. To me it looks good:
{“success”:”1″,”row_id”:15,”fname”:”Jack”,”lname”:”Hoolihan”,”email”:”jackh@hoolihan.com”,”phone”:”1234567890″}
2) When I click to Delete an item it is deleted in the database but not visually from the html row. The response is:
{“success”:”1″,”item_id”:”7″}
Reloading the page or doing a simple mysql select shows that the changes are working. I can provide snapshots or a link to the page and supporting files including a .txt version of ajax.php if this helps. Any idea?
It means operations are going fine but after ajax request completes some js error is causing problem updating client side view. Do you see any js error ?
Nothing visually on the screen. Here is a link to the demo and some new info. I was using the jquery.js file from your website. Just to see, I switched to a standard version off google and get different results. The add row now works correctly whereas the Delete row no longer calls the ajax.php file (nothing in Firebug).
http://www.dottedi.biz/demo/code/add-delete-row/index.php (google jquery)
http://www.dottedi.biz/demo/code/add-delete-row/index2.php (your jquery)
Ok, so there are 2 problems. Script uses jquery ui library for highlight effect (New row keeps adding), Second you are using latest jquery version which doesnt support “live” method, its replaced with “on”, Make changes in js file and replace “live” with “on”.
Switching ‘live’ to ‘on’ and using the current google jquery.js got it back to posting to ajax.php and deleting the rows from the database but not visually deleting the row. I don’t know much jQuery; I looked at the file and saw some lines that seemed to be relevant to IE – I commented out those lines and it now works perfectly in Firefox and Chrome.
// if ( ! $.browser.msie ) {
// $(“a[id='”+row_id+”‘]”).closest(“tr”).effect(“highlight”, {
// color: ‘#4BADF5’
// }, 1000);
// }
Someone will need to test in IE to see how it works in IE as well. Thx much.
Oops, not quite correctly yet. I found that the first time I went to add a new record it was fine, but after the first record, clicking to add another new record did not bring up the pop up new record screen. So I gambled again and commented out the other 5 lines related to MSIE and this fixed that problem.
// if ( ! $.browser.msie ) {
// $(“.table-list tr:last”).effect(“highlight”, {
// color: ‘#4BADF5’
// }, 1000);
// }
});
However there is one remaining issue. Delete works with records previously entered. If you change your mind and decide to delete the record you just added nothing happens, no ajax/post request. The JSON response looks to be adding the ID correctly. You must reload the page in order to be able to delete the unwanted new entry. See the index.php URL.
how can we do the same code in jsp
Hello admin pagination working with this setup