简体   繁体   English

数据库中的Ajax插入在WordPress中返回404错误

[英]Ajax insert in database return 404 error in WordPress

I'm trying to insert simple form in database trough ajax without refreshing the page in Wordpress. 我正在尝试在数据库槽ajax中插入简单表单,而不刷新Wordpress中的页面。

For some reason when I click on submit button I've got that the page isn't found - 404 error. 由于某些原因,当我单击“提交”按钮时,我发现页面未找到-404错误。

I have added this to my theme function.php 我已经将此添加到我的主题function.php

add_action('wp_enqueue_scripts', 'my_ajax_scripts'); 
function my_ajax_scripts(){
    wp_enqueue_script( 'myscript', get_template_directory_uri().'/assets/js/formSubmit.js', array('jquery'), '1.0', true );
    wp_localize_script( 'myscript', 'myajax', array( 'ajaxurl' =>   admin_url( 'admin-ajax.php' ) ) );
}

function applyform(){
        global $wpdb;
        $table = jobs;
        $data = array(
            'name' => $_POST['name'],
            'email'    => $_POST['email'],
            'form_id'    => $_POST['form_id']
        );
        $format = array(
            '%s',
            '%s',
            '%s'
        );
        $success=$wpdb->insert( $table, $data, $format );
        if($success){
            //wp_redirect( site_url('/') );
            die;
        }
}

//ADD THE AJAX HOOKS IN WORDPRESS
add_action('wp_ajax_applyform', 'applyform');
add_action('wp_ajax_nopriv_applyform', 'applyform');

Then I have this in the formSubmit.js 然后我在formSubmit.js有这个

jQuery(document).ready(function($){ 

    $('#submit').submit(function(e){ // Updated            

        var applicantform = $(this).serialize(); // serializing the form data

        e.preventDefault();

        //ajax call
        $.ajax({
            type:   'POST', 
            action: 'applyform', 
            url:    myscript.ajaxurl, // the functional url     
            data:   myscript.applyform, // all the data of the form (serialized)

            // Displaying succes message
            success: function( data ){
                $('#result').html( 'Success : '.data );
                // for debugging purpose in browser js console
                console.log(data);
            },

            // Displaying error message     
            error: function( error ){
                $('#result').html( 'Error! : '. error );
                // for debugging purpose in browser js console
                console.log(error);
            }               
        });
    });
});

And this is the form in modal window on the page 这是页面上模态窗口中的表格

<form method="post" id="applicantform">
     <input type="text" name="name" placeholder="Nmae" />
     <input type="hidden" name="form_id" value="<?php echo $post->ID; ?>">
     <input type="email" name="email" placeholder="Email" />
     <input type="submit" name="submit" id="submit" value="Send" />
</form>

I don't see anything in the console log. 我在控制台日志中什么都没有看到。 Not console.log(data) nor console.log(error) . 不是console.log(data)也不是console.log(error) On form submit it goes straight to not found page. 在表单提交时,它直接进入未找到的页面。

Try this instead. 试试这个吧。 You're not serializing the form data by targeting the submit. 您不是通过定位提交来序列化表单数据。

$('#applicantform').submit(function(e){        

    var applyformData = $(this).serialize(); // serializing the form data

    e.preventDefault();

    //ajax call
    $.ajax({
        type:   'POST', 
        url:    myajax.ajaxurl, // the functional url     
        data:   {
            data: applyformData, // all the data of the form (serialized)
            action: 'applyform',
          } 

        // Displaying succes message
        success: function( data ){
            $('#result').html( 'Success : '.data );
            // for debugging purpose in browser js console
            console.log(data);
        },

        // Displaying error message     
        error: function( error ){
            $('#result').html( 'Error! : '. error );
            // for debugging purpose in browser js console
            console.log(error);
        }               
    });
});

First, check your ajax call structure! 首先,检查您的ajax调用结构!
To make this ajax call work, you have to send your action within "data" object. 为了使此ajax调用有效,您必须在“数据”对象内发送操作。 The form data you've collected and dumped into a variable "applicantform" is missing also. 您收集并转储到变量“ applicantform”中的表单数据也丢失了。

Update it looks like you are confusing your assigned ajax url! 更新它似乎使您混淆了分配的ajax URL! Instead of using myscript.ajaxurl you have to use myajax.ajaxurl 不必使用myscript.ajaxurl ,而必须使用myajax.ajaxurl

Ajax Call 阿贾克斯电话

 //ajax call
        $.ajax({
            type:   'POST', 
            url:    myajax.ajaxurl, // ajax url you assigned!   
            data: {
                 action: 'applyform',   // send your action within data 
                 formdata: applicantform, // all the data of the form (serialized)
            },

            // Displaying succes message
            success: function( data ){
                $('#result').html( 'Success : '.data );
                // for debugging purpose in browser js console
                console.log(data);
            },

            // Displaying error message     
            error: function( error ){
                $('#result').html( 'Error! : '. error );
                // for debugging purpose in browser js console
                console.log(error);
            }               
        });

Javascript including ajax 包含ajax的Javascript

Your form id -> applicantform doesn't match the selector, so you have to change your selector like this! 您的表单ID->申请人表单与选择器不匹配,因此您必须像这样更改选择器!

jQuery(document).ready(function($){ 

    $('#submit_form').click(function(e){        

        var applyformData = $('#applicantform').serialize(); // serializing the form data

        e.preventDefault();

        //ajax call
        $.ajax({
            type:   'POST', 
            url:    myajax.ajaxurl, // ajax url you assigned!   
            data: {
                 action: 'applyform',   // send your action within data 
                 formdata: applyformData, // all the data of the form (serialized)
            },

            // Displaying succes message
            success: function( data ){
              window.location.replace("https://example.org");
            },

            // Displaying error message     
            error: function( request ){
                $('#result').html( 'Error! : '. error );
                // for debugging purpose in browser js console
                console.log(request); 
            }               
        });
    });
});

Serverside PHP 服务器端PHP

since you've serialized your data you have to use parse_str on php side. 由于已经序列化了数据,因此必须在php端使用parse_str。 https://www.w3schools.com/php/func_string_parse_str.asp https://www.w3schools.com/php/func_string_parse_str.asp


function applyform(){
        global $wpdb;

        if (!check_ajax_referer( 'my_nonce' )){
        wp_die();
        }

        $table = jobs;

    // serialized data from ajax
        $formdata = $_POST['formdata'];

   // use parse_str to unserialize
        parse_str($formdata, $formdata_array);

   // accessing your data like...
        $data = array(
            'name' => $formdata_array['name'],
            'email' => $formdata_array['email'],
            'form_id' => $formdata_array['form_id']
        );

        $format = array(
            '%s',
            '%s',
            '%s'
        );
        $success=$wpdb->insert( $table, $data, $format );
        if($success){
        // do something
            die();
        }
die();
}

Security 安全

For security reasons you should consider using wp_nonce_field('my_nonce'); 出于安全原因,您应该考虑使用wp_nonce_field('my_nonce'); .
https://codex.wordpress.org/Function_Reference/wp_nonce_field https://codex.wordpress.org/Function_Reference/wp_nonce_field

Using the following snippet inside your form creates a security nonce you have to verify serverside. 在表单中使用以下代码段可创建一个安全随机数,您必须验证服务器端。

<form method="post" id="applicantform" enctype="multipart/form-data">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<input type="hidden" name="form_id" value="<?php echo $post->ID; ?>">
<?php wp_nonce_field( 'my_nonce' ); ?>
</form>
<button type="button" id="submit_form">Send</button>

Serverside inside your function applyform just check like... 您的函数applyform只需检查...


if (!check_ajax_referer( 'my_nonce' )){
wp_die();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM