调用jQuery ajax函数

Please bear with me; I've been battling with this for days.

I have a little bit of jQuery code in my jQuery(document).ready function as follows:

        jQuery(document).ready(function($) {
        jQuery.post(ajaxurl, data, function(response) {
          alert(response);
        });
    });

I have a text input field which I want sent to my Ajax function (using the Wordpress API)

    <input type="text" name="input" id=input onkeydown="if (event.keyCode == 13) {send_message(this.value);}">

If the user presses the key, the text is sent to the javascript 'send_message' function (below).

function send_message(value){
  data[txt]=value;
  jQuery.post(ajaxurl, data, function(response) {
    alert(response);
  });
}

BAsically, I've added a 'txt' key/value pair to my data object and I now want this submitted to my ajax function.

The 'document ready' part works fine, but I can't get it to accept the changed data object.

As you can probably tell, I'm not following the logic behind the jQuery code very well.

The data parameter in your function is not initialized. You should probably see a javascript error if you inspect your page using chrome or firefox.

Basically the data parameter in jquery's post function accepts either a serialized form query string or JSON string/object.

Also, please check the api: http://api.jquery.com/jquery.post/

Try below modified code:

function send_message(value){
    var data={txt:value};
      jQuery.post(ajaxurl, data, function(response) {
        alert(response);
      });
    }
function send_message(value){

    if(!value){
        alert('value is empty');
    } 

    if(!data){
        alert('data is empty');
    }

    data.txt=value;

    jQuery.post(ajaxurl, data, function(response) {
       alert(response);
    });
}

if you check your console, you were probably getting txt is not defined you were missing the '' around them. Generally use the .dot notation for known object keys and save [] for dynamic keys if you believe in good practice.

Also you haven't mentioned what browser you are using...i cant swear this is current but firefox uses event.which instead of keycode...so:

 onkeydown="var code= event.which || event.keyCode; if (code == 13) {send_message(this.value);}"

edit

Solution for this instance.

You were enqueuing the js files on the hook 'enqueue_scripts' it should be 'admin_enqueue_scripts' and also specify it needs jQuery.

add_action( 'admin_enqueue_scripts', 'load_chat_me_styles' ); //-->note changed hook!

I've also updated the js file to allow for console logs and the php file to allow for better feedback.

Jsfile - save as a new file name to rule out caching http://pastebin.com/NyqGqhG0

Phpfile - note any notes... http://pastebin.com/N7LQg0Zi