The request for ajax wordpress form does not work?

advertisements

Here is the code..I think action i ajax not working and getting 403 error! using Wamp and running Wordpress on it

js code jQuery('#InsertionForm').submit(

function (){
var x = jQuery('#nm').val();
var y = jQuery('#em').val();

jQuery.ajax({
type:"POST",

url: "<?php echo admin_url('admin-ajax.php'); ?>",

data: {
        action: 'get_my_option',
        namo: x,
        emao: y
    },

success:function(){
    alert("working");
}
});

return false;

});

main plugin code ..please can anyone tell me ...the given bellow code is in right sequence or not?

    <?php

/*

Plugin Name: lucky

*/

//adding script files in HTML

wp_enqueue_script('myscript', plugins_url('myscript.js', __FILE__), 

array('jquery'), '', true);

wp_localize_script( 'myscript', 'my_ajax_object',

            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

function get_my_option()

{

    //do something

   alert("this is a function action: in ajax");

}

add_action("wp_ajax_nopriv_get_my_option", "get_my_option");

add_action("wp_ajax_get_my_option", "get_my_option");

    #Shortcode function.........................................

function html_form_code() {

    global $wpdb;

    # Input form fields.....

    echo '<form method="post" id="InsertionForm">';

    echo '<h3>Insertion Form</h3>';

    echo '<p>Your Name (required) <br/>';

    echo '<input id="nm" type="text" name="namel" value="" size="40" />';

    echo '</p>';

    echo '<p>';

    echo 'Your Email (required) <br/>';

    echo '<input id="em" type="email" name="emaill" value="" size="40" />';

    echo '</p>';

    echo '<p><input type="submit" name="submitbtn" value="Send"> ';

    echo '</form>';
}

function my_ajax() {

    $nom = $_POST['namo'];

    $emo = $_POST['emao'];

    global $wpdb;

    $wpdb -> insert( 'lucky_wpdb', array('namel' => $nom, 'emaill' => $emo) 

);

echo 'Submitted';

}

    //Shortcode working here....

add_shortcode( 'sitepoint_contact_form', 'html_form_code' );

?>


To make ajax action work you need to defined the separate actions for logged in and not-logged in users.

add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );

where wp_ajax_nopriv_ means for not logged in user and wp_ajax_ means logged in user also my_action is your actual action. they can call to send action method or different depending on your requirements