Saving form value to database through ajax wordpress

How can I save data to database using ajax and form. I have working this for one day but still no luck I don’t know what’s wrong with this code I came up right now. This is one is wordpress

Here is the code:

Read More

This javascript was in the header.php

<form>
<input name="MyUrlName" type="text" class="add_name" id="MyUrlName" placeholder="Name of website">
<input type="button" name="submit" id="MyUrlsubmit" value="Add URL" class="submit">
</form>
jQuery(document).ready(function(){
        jQuery("#MyUrlsubmit").click(function(){
            var name = jQuery("#MyUrlName").val();
            jQuery.ajax({
                type: 'POST',
                url: "<?php echo admin_url('admin-ajax.php'); ?>",
                data: {"action": "savedata", "MyUrlName":name},
                success: function(data){
                //alert('success');
                 console.log(data);
                }
            });
        });
    });

Here is the code in function.php

 function savedata(){
        $name = $_POST['MyUrlName'];
            global $wpdb;
            $table_name = $wpdb -> prefix . "save_url";

       $wpdb->insert( 
                $table_name, array( 
                    'name' => $_POST['MyUrlName']
                ),
                array(
                    '%s'
                )
            );
       return true;
exit();
    }
add_action('wp_ajax_nopriv_savedata', 'savedata');
add_action('wp_ajax_savedata', 'savedata');

I’m implementing it in frontend

Thank you in advance

Related posts

1 comment

  1. use this code

     <form>
        <input name="MyUrlName" type="text" class="add_name" id="MyUrlName" placeholder="Name of website">
        <input type="button" name="submit" id="MyUrlsubmit" value="Add URL" class="submit">
        </form>
        jQuery(document).ready(function(){
                jQuery("#MyUrlsubmit").click(function(){
                    var name = jQuery("#MyUrlName").val();
                    jQuery.ajax({
                        type: 'POST',
                        url: "<?php echo admin_url('admin-ajax.php'); ?>",
                       data: {action: "savedata", MyUrlName:name},               
    
                        success: function(data){
                        //alert('success');
                         console.log(data);
                        }
                    });
                });
            });
    

Comments are closed.