阿贾克斯wordpress前端?

时间:2018-11-07 19:43:06

标签: php jquery ajax wordpress

在我的wordpress主题中,我制作了一个表单,并使用ajax来操纵表单输入。问题是如何使用form.serialize()而不是获取每个input.val并将其发送到data_to_pass中的json对象中。
我要用这个

'data_to_pass' : $('#my_form').serialize();

代替此

'data_to-pass' : {user_id : user_input,user_id2:user_input2}

这是my-script.js文件中的我的ajax代码

    $(function(){

   $('#search_user_id').on('submit', runMyAjax);   
function runMyAjax(e){     
   e.preventDefault();
  var user_input = $('#search_user_id #user_input').val();
  var user_input2 = $('#search_user_id #user_input2').val();
  var form_data= $('#my-form').serialize();//this sent string not url i cannot use $_POST['field'] in my functions.php handler
  var data = {
        'action': 'my_ajax_function', //the function in php functions to call
    //i want to pass form_data to my functions to handle 
        'data_to_pass': {user_id : user_input,user_id2:user_input2},
        'nonce': frontEndAjax.nonce
    };
    //send data to the php file admin-ajax which was stored in the variable ajaxurl
   $.post(frontEndAjax.ajaxurl, data, function( response ) {
       $('#search_user_id').append(response.data_from_backend);
           //simple test. if new string brought back doesn't match old string.


        }, 'json' );

   } //end runMyAjax


    });

和我的functions.php代码在这里

    function shukr_scriptFiles(){
/*jquery js files*/
wp_deregister_script('jquery');
wp_register_script("jquery",get_template_directory_uri()."/js/jquery-3.3.1.slim.min.js",array(),false,true);
wp_enqueue_script("jquery");

/*ajax-scripts.js*/
wp_enqueue_script("ajax-script-file",get_template_directory_uri()."/js/ajax-scripts.js",array(),false,true);
//passing variables to the javascript file
wp_localize_script('ajax-script-file', 'frontEndAjax', array('ajaxurl' => 
    admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce('ajax_nonce')
     ));


    }
    add_action('wp_enqueue_scripts','shukr_scriptFiles');

这里是我的处理函数

    //now we can get the data we passed via $_POST[]. make sure it isn't empty first.
//need to get field input value using serialize form here
$_POST['form_field']

    if(! empty( $_POST['data_to_pass'] ) ){
               $my_paragraphs_text = esc_html($_POST['data_to_pass']['user_id']);
    }
        $ajax_response = array('data_from_backend' => $my_paragraphs_text);


     echo json_encode( $ajax_response );  //always echo an array encoded in json 
    wp_die();

    }

    add_action( 'wp_ajax_nopriv_my_ajax_function', 'my_ajax_function' );
    add_action( 'wp_ajax_my_ajax_function', 'my_ajax_function' );

0 个答案:

没有答案