我正在关注此tutorial以使用前端ajax从表单提交电子邮件,并在电子邮件中包含诸如当前帖子标题之类的信息。请注意我不是php或ajax的专家。任何建议或资源将不胜感激。
我尝试了以下内容 - 但我的隐藏输入字段值仅返回一个字符串,我认为这是因为它在页面加载后被包含。
Jquery的
function submit_me(){
jQuery.post(the_ajax_script.ajaxurl, jQuery("#theForm").serialize()
,
function(response_from_the_action_function){
jQuery("#response_area").html(response_from_the_action_function);
}
);
}
PHP
// enqueue and localise scripts
function plugin_enqueue_scripts() {
wp_enqueue_script( 'my-ajax-handle', plugin_dir_url( __FILE__ ) . 'ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'plugin_enqueue_scripts');
// THE AJAX ADD ACTIONS
add_action( 'wp_ajax_the_ajax_hook', 'the_action_function' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'the_action_function' ); // need this to serve non logged in users
// THE FUNCTION
function the_action_function(){
/* this area is very simple but being serverside it affords the possibility of retreiving data from the server and passing it back to the javascript function */
$name = $_POST['name'];
$title = $_POST['title'];
echo"Title: " . $title;// this is passed back to the javascript function
die();// wordpress may print out a spurious zero without this - can be particularly bad if using json
}
// ADD EG A FORM TO THE PAGE
function hello_world_ajax_frontend(){
$the_form = '
<form id="theForm">
<input id="name" name="name" value = "name" type="text" />
<input name="action" type="hidden" value="the_ajax_hook" /> <!-- this puts the action the_ajax_hook into the serialized form -->
<input id="submit_button" value = "Click This" type="button" onClick="submit_me();" />
<input name="title" type="hidden" value="<?php the_title(); ?>" />
</form>
<div id="response_area">
This is where we\'ll get the response
</div>';
return $the_form;
}
add_shortcode("hw_ajax_frontend", "hello_world_ajax_frontend");
?>
答案 0 :(得分:2)
更新:
而不是<?php the_title(); ?>
尝试' . get_the_title() . '
答案 1 :(得分:2)
试试这个:
function hello_world_ajax_frontend(){
$the_form = '
<form id="theForm">
<input id="name" name="name" value = "name" type="text" />
<input name="action" type="hidden" value="the_ajax_hook" /> <!-- this puts the action the_ajax_hook into the serialized form -->
<input id="submit_button" value = "Click This" type="button" onClick="submit_me();" />
<input name="title" type="hidden" value="'.get_the_title().'" />
</form>
<div id="response_area">
This is where we\'ll get the response
</div>';
return $the_form;
}
基本上,只需将get_the_title()
的结果与html输出结合起来。
如果你将php代码块留在字符串中,它将不会被执行,你的php代码将被输出到html doc。