insert data in database return 404 error in WordPress

38 views Asked by At

I'm trying to insert simple form in database trough ajax without refreshing the page in Wordpress.

For some reason when I click on submit button I've got that the page isn't found - 404 error.

I have added this to my theme function.php

//set_data action 
add_action( 'wp_ajax_set_data', 'my_ajax_foobar_handler' );
add_action( 'wp_ajax_nopriv_set_data', 'my_ajax_foobar_handler' );

function my_ajax_foobar_handler() {

    
    $name = $_POST['name_f'];
    $email = $_POST['email_f'];
    
    $data = array("name" => $name, "email"=>$email);
    global $wpdb;
    global $table_prefix;
    $table = $table_prefix.'contact_form';

    $result = $wpdb->insert($table, array(
    'name' => $name,
    'email' => $email
));

wp_send_json_success($result);

    header("Content-Type: application/json");
    echo json_encode($data);

    

    wp_die();
}

Then I have this in the code snippets for frontend

<?php echo '<form method="POST" id="form">
<table>
<tr>
    <td>name</td>
    <td><input type="text" id="name_field" name="name"></td>
</tr>
<tr>
    <td>email</td>
    <td><input type="email" id="email_field" name="email"></td>
</tr>
<tr>
    
    <td><input type="submit" id="form_submit" name="submit"></td>
</tr>
</table>
</form>';?>



<script>


jQuery('#form').on('submit', function (event) {

        var formData = {
        action: 'set_data',
       name_f: $("#name_field").val(),
       email_f: $("#email_field").val()
      
    };

    


        $.ajax({
            url : '<?php echo admin_url('admin-ajax.php'); ?>',
            data : formData,
            type : 'POST',
            // contentType: "application/json; charset=utf-8",
            dataType : 'json',
            success : function (request) {

                console.log(typeof request);

                console.log(request);

            }
        });

        
    event.preventDefault();
    });
   
 
</script>

<?

I have got this in console log "POST https://website.com/page/?preview_id=2155&preview_nonce=865f9a58ce&preview=true 404 (Not Found)"

on form submit straight goes to the "page not found"

0

There are 0 answers