sourcecode

Wordpress에서 ajax와 함께 양식 제출

codebag 2023. 3. 9. 22:03
반응형

Wordpress에서 ajax와 함께 양식 제출

워드프레스에서 Ajax 요청 결과를 가져오려고 하는데 javascript의 Alert box에 "0" 결과가 나와 폼은 다음과 같습니다.

<form class="form" id="ajax-contact-form" action="#">                            
        <input type="text" name="name" id="name"  placeholder="Name" required="">
        <button type="submit" class="btn">Submit</button>
</form>

Javascript는 다음과 같습니다.

$('#ajax-contact-form').submit(function(e){

    $.ajax({ 
         data: {action: 'contact_form'},
         type: 'post',
         url: ajaxurl,
         success: function(data) {
              alert(data); // This prints '0', I want this to print whatever name the user inputs in the form. 

        }
    });

})

그리고 PHP:

add_action('wp_ajax_contact_form', 'contact_form');
add_action('wp_ajax_nopriv_contact_form', 'contact_form');

function contact_form()
{
echo $_POST['name'];    
}

위 코드가 맞는지 아는 사람 있나요?$_REQUEST ['name']도 시도해 봤지만 작동하지 않습니다.

정말 감사합니다.

이와 같은 것을 시도해 보세요.당신은 추가하지 않았습니다.namePHP에서 기대하는 파라미터contact_form기능하기 때문에, 그것을 에 추가할 필요가 있습니다.datajQuery ajax 함수 호출의 속성.

$('#ajax-contact-form').submit(function(e){
    var name = $("#name").val();
    $.ajax({ 
         data: {action: 'contact_form', name:name},
         type: 'post',
         url: ajaxurl,
         success: function(data) {
              console.log(data); //should print out the name since you sent it along

        }
    });

});

다시 생각해보면 2022년이다.승인된 답변은 WordPress Nonces를 확인하지 않고 AJAX 요청을 맹목적으로 받아들이는 것입니다.AJAX 요청은 알 수 없는 불량 행위자의 잠재적인 악의적인 요청이 아닌 합법적인 요청으로 검증되어야 합니다.

AJAX 핸들러의 첫 번째 조작은 jQuery에서 전송된 난스를 와 함께 확인하는 것입니다.이 값은 스크립트가 큐잉되었을 때 현지화된 값과 같아야 합니다.

먼저 AJAX URL을 전달하고 난스를 생성하여를 전달합니다.wp_localize_script()를 사용하여 스크립트를 등록한 후 호출해야 합니다.wp_register_script()또는wp_enqueue_script().

<?php

wp_localize_script( 'script', 'localize',
    array(
        '_ajax_url' => admin_url( 'admin-ajax.php' ),
        '_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
    )
);

델에서script.js파일 우리는 AJAX 함수를 선언합니다.

$(function(){
    $('button').click(() => {
        $.ajax({
            type: 'POST',
            url: localize._ajax_url,
            data: {
                _ajax_nonce: localize._ajax_nonce,
                test: 'test',

                /**
                 * The action parameter is the The dynamic portion of the wp_ajax_{$action} action hook (Ajax action callback being fired).
                 * 
                 * @see https://developer.wordpress.org/reference/hooks/wp_ajax_action/
                 * @see https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/
                 */
                action: '_POST_action',
            },
            success: (res) => {
                console.log(res);
            }
        });
    });
});

그리고 결과를 처리하여 JSON 응답을 Ajax 요청으로 반송합니다.

<?php

add_action( 'wp_ajax__POST_action', function () {

    if ( check_ajax_referer( '_ajax_nonce' ) ) {

        $test = $_POST['test'];

        //...

        wp_send_json_success();

    } else {
        
        wp_send_json_error();

    };

} );

javascript에 name 속성도 추가해야 합니다.

이렇게 보일 수 있습니다......

$('#ajax-contact-form').submit(function(e){

$.ajax({ 
     data: {action: 'contact_form', name:name},
     type: 'post',
     url: ajaxurl,      
     success: function(data) {
          alert(data); 
    }
});

})

이 스크립트는 함수에 포함해야 합니다.php

wp_register_script('my_script_handle','');
wp_add_inline_script('my_script_handle', "var techy_ajaxurl = '".admin_url( 'admin-ajax.php' )."';"  );
wp_enqueue_script( 'my_script_handle' );

그리고 js는 이것을 변경한다.

$.ajax({ 
     data: {action: 'contact_form', name:name},
     type: 'post',
     url: techy_ajaxurl,      
     success: function(data) {
          alert(data); 
    }
});

100% 테스트 완료

언급URL : https://stackoverflow.com/questions/18777728/submitting-a-form-with-ajax-in-wordpress

반응형