errata
errata

Reputation: 6031

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 tutorials will be also great :)

Thanks a lot for any help!

Upvotes: 0

Views: 2435

Answers (3)

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28541

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 or jQuery.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 or jQuery.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 and jQuery.html functions.

Upvotes: 1

reggie
reggie

Reputation: 13711

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.

Upvotes: 1

cusimar9
cusimar9

Reputation: 5259

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/

Upvotes: 2

Related Questions