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
1 Answer
Reset to default 2You 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
}