Why is my ajax request getting response 0?

后端 未结 3 1714
既然无缘
既然无缘 2020-12-10 04:14

I\'ve setup the basic wordpress ajax example in my wp theme. The trigger is made by modernizr.js checking the media queries on the page.

jQuery(document).rea         


        
相关标签:
3条回答
  • 2020-12-10 04:42

    Add the "exit" end of the function as shown below, this will fix the return 0 with the response in WordPress on using the ajax request.

    add_action('wp_ajax_nopriv_getStateList', 'getStateList');
    add_action('wp_ajax_getStateList', 'getStateList');
    
    function getStateList() {
        global $wpdb;
        $countryId = $_POST['countryId'];
        $results = $wpdb->get_results("SELECT id,name FROM regions where country_id ='".$countryId."' ");
        echo json_encode(array('status'=>200,'data'=>$results));
        exit;
    }
    
    0 讨论(0)
  • 2020-12-10 04:59

    Everything has to match here:

    PHP

    add_action('wp_ajax_my_action',        'my_action');
    add_action('wp_ajax_nopriv_my_action', 'my_action');
    
    function my_action() {}
    

    JS

    var data = {
        action: 'my_action',
        whatever: ajax_object.we_value 
    };
    

    Also, you're missing security checks and a better handling of the response.
    Check this examples: [ 1 ] and [ 2 ].

    0 讨论(0)
  • 2020-12-10 05:02

    Here is the full example to solve this issue:

    JavaScript:

    $(document).ready(function() {
        $("#submit").click(function(e) {
            var demo = 'demo';
            var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
            data = { action: "data_insert", demo: demo};     
            $.ajax({
                url: ajaxurl,
                data: data,
                dataType: 'json',
                type: 'post',
                success: function(response) {
                  console.log(response);  
                }
            });
        });    
    });
    

    PHP:

    add_action('wp_ajax_data_insert', 'data_insert');
    add_action('wp_ajax_nopriv_data_insert', 'data_insert');
    function data_insert() {
        $data = $_POST['demo'];
        echo json_encode($data);
        die();
    }
    
    0 讨论(0)
提交回复
热议问题