最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Basic ajax call in WordPress

programmeradmin2浏览0评论

My aim is to create the most simple ajax call in WordPress, but I can't get my head around how it works.

JS File:

jQuery("#votepostform").submit(function() {

    var url = "file.php"; // php script to handle form

    jQuery.ajax({
           type: "POST",
           url: url,
           data: jQuery("#votepostform").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});

Form HTML:

<form action="" method="post" id="votepostform" />
    <input type="hidden" name="postid" value="333" />
    <button type="send" name="vote" class="vote_link"></button>
</form>

file.php:

echo '<script language=\'javascript\'>alert(\'It works! \');</script>';

How can I make this ajax code work in a WordPress site?

My aim is to create the most simple ajax call in WordPress, but I can't get my head around how it works.

JS File:

jQuery("#votepostform").submit(function() {

    var url = "file.php"; // php script to handle form

    jQuery.ajax({
           type: "POST",
           url: url,
           data: jQuery("#votepostform").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});

Form HTML:

<form action="" method="post" id="votepostform" />
    <input type="hidden" name="postid" value="333" />
    <button type="send" name="vote" class="vote_link"></button>
</form>

file.php:

echo '<script language=\'javascript\'>alert(\'It works! \');</script>';

How can I make this ajax code work in a WordPress site?

Share Improve this question asked Jan 9, 2015 at 19:57 ThanosThanos 231 gold badge2 silver badges4 bronze badges 1
  • 2 Did you check the Codex on Using Ajax in Plugins? – josh Commented Jan 9, 2015 at 20:25
Add a comment  | 

1 Answer 1

Reset to default 2

You have to use the admin-ajax handler to do the AJAX call.

Replace file.php in var url = "file.php"; with

yoursite/wp-admin/admin-ajax.php?action=simple_ajax

And in your plugin / functions.php file, add

add_action('wp_ajax_nopriv_simple_ajax','process_simple_ajax'); //for non logged in user
add_action('wp_ajax_simple_ajax','process_simple_ajax'); //for nlogged in user

function process_simple_ajax(){
    $data = $_REQUEST; // retrieve your submitted data
    wp_send_json($data); // return the processed data to the browser as json
}
发布评论

评论列表(0)

  1. 暂无评论