I want to display user input with ajax . but still is executed function fail in js file. I dont know where the problem might be. I read http://codex.wordpress.org/AJAX_in_Plugins and I saw http://pippinsplugins.com/using-ajax-your-plugin-wordpress-admin/
EDIT:I gave e.preventDefault();
on the top of jquery code in js .Its works (I received message from php file). but i dont know how its possible that the code works for me.
my form in main file
<div id="wrap">
<div id="chat" >
</div>
<div id="message">
<form method="post" action="" id="sendformtoDB">
<input type='text' id="text" name="text"/>
<input id='send' type='submit' name="send" class="button-primary" value='Submit' />
</form>
</div>
</div>
in my constructor add_action
add_action('wp_ajax_InsertIntoDB',array($this,'InsertIntoDB'));
add_action('wp_ajax_nopriv_InsertIntoDB',array($this,'InsertIntoDB'));
I load jquery library at first and the my js file
public function load_scripts() {
wp_register_script( 'jquery', plugins_url( 'jq/jquery.js', __FILE__ ));
wp_enqueue_scripts('jquery');
wp_register_script( 'sendToDB', plugins_url('jq/sendToDB.js',__FILE__ ),array( 'jquery' ));
wp_enqueue_script('sendToDB');
wp_localize_script( 'sendToDB', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
}
php file
public function InsertIntoDB(){
if(isset($_POST['message'])){
$messages=$_POST['message'];
# global $wpbdb;
/* $wpbdb->insert('wp_userlogin',
array(
"message"=>$message
),
array(
'%s'
)
);*/
echo "$messages";
}
die();
}
js file
jQuery( document ).ready( function($) {
$( " #sendformtoDB" ).submit( function() {
var text;
text = $( "#text" ).val();
console.log(text);
$.ajax({
type: 'POST',
url: MyAjax.ajaxurl,
data:{"action":'InsertIntoDB',message:text},
success:function(msg){
alert(msg);
}
// $(':input').not(":submit").val('');
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus+jqXHR );
});
} );
} );