Adding rows to MySQL db and showing DIVs with jQuery without refreshing a page
I am using some PHP script to add some data from a complex form to MySQL db and then showing it all in some HTML table. Everything works just fine, but I would like to 'upgrade' my script with jQuery and (I suppose) AJAX.
What I would like to do is when user submits data, the row (or <div>
) shows up in the HTML table without refreshing a page. Form and table are on same page, of course...
Some guidelines would be really helpful because I'm not sure should I even use AJAX or something else for my needs. Links for some tutoria开发者_JAVA技巧ls will be also great :)
Thanks a lot for any help!
An easy way to do this is using jQuery POST method
http://api.jquery.com/jQuery.post/
When the user submits the data, you use jQuery to post the data to a PHP handler, which saves the data to the database and returns a HTML formatted row to add to your table.
Here's a good example: http://www.jensbits.com/2009/10/04/jquery-ajax-and-jquery-post-form-submit-examples-with-php/comment-page-1/
I had used this tutorial to implement a comment system on one of my projects. It uses ajax and works really well. I believe that this is what you need.
You'll need:
A php page where to submit the form. Ideally this page will return the result as a JSON object (PHP has some handy JSON functions to convert PHP arrays and objects directly to a proper JSON string). Don't forget to include some error information in the JSON object you return. This can have the form:
{ "errorCode": 0, "result": { "var1": value1, "var2": value2 } }
Some javascript to submit the form. This can be done nicely with
jQuery.ajax
,jQuery.post
orjQuery.get
functions.Some javascript to handle the result from the PHP script. This will be a callback function that you give to the
jQuery.ajax
,jQuery.post
orjQuery.get
functions. This script will either:- display the errors to the user (you can set some text in a div for example using
jQuery("#error").html("My error message");
) - Insert the row in your table. You can build HTML elements dynamically using
jQuery.append
andjQuery.html
functions.
- display the errors to the user (you can set some text in a div for example using
精彩评论