0

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"

3
  • Did you try jQuery.ajax instead of $.ajax? Commented Oct 20, 2023 at 4:49
  • yes I have tried and still 404 [not found] Commented Oct 20, 2023 at 5:03
  • First off: Make event.preventDefault(); the first line of your outer anonymous function (right before var formData) so the form does not get submitted if the javascript fails and you can actually see any debug output in console. Commented Oct 20, 2023 at 5:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.