使用AJAX将数据POST到PHP数据库,然后刷新

问题描述:

Currently I have a button:

<ul>
    <li><button onclick="display('1')">1</button></li>
    <li><button onclick="display('2')">2</button></li>
    <li><button onclick="display('3')">3</button></li>
</ul>

That when pressed, calls a javascript function, and displays PHP based on which button is pressed using AJAX. I figured this out all on my own. The AJAX gets a PHP file with a postgres query that outputs a table of data to a div.

Now I want to be able to add, via form, new data and have it refresh (without reloading the page, yannknow?). I've tried a couple of things, and have hit roadblocks every time.

My initial idea was to have the form submit the data using a javascript function and AJAX, then call my "display()" function after the query to reload the content. I just can't figure it out using GoogleFu.

Based on my current idea, I'd like help with the following:

  1. How do I pass the form data to a javascript function.
  2. How do I use POST to pass that data to PHP using AJAX?

I'm super new to javascript and AJAX. I've looked into jquery as it seems like that's the way to go, but I can't figure it out. If there's a better way to do this, I'm open to suggestions. Please forgive any misuse of nomenclature.

EDIT: Once I solve this problem..., I'll have all the tools needed to finish the project preliminarily.

This example is copied directly from the jQuery API docs for $.post. When in doubt, first place to look is in the API

http://api.jquery.com/jQuery.post/

Example: send form data using ajax requests

$.post("test.php", $("#testform").serialize(), function(data){
   /* success- do something with returned data*/
});

Now extend the concept further and wrap the post in a submit handler for the form

$("#testform").submit(function(){
/* code from above, changing form selector to "this" */
  $.post("test.php", $(this).serialize(), function(data){
       /* success- do something with returned data*/
    });    
/* prevent browser default submit*/
  return false;
})

Refer to jQuery.post method. It does what you want (sends AJAX request with POST data).

To grab values from inputs, use val() method for nodes that have value (textarea, input, .. )