I'm trying to create a WordPress sample plugin based in AJAX. I read a tutorial and did a plugin, but it's not working. I am new to AJAX. Here is the code I tried:
<?php
class ajaxtest {
function ajaxcontact() {
?>
<div id="feedback"></div>
<form name="myform" id="myform">
<li>
<label for fname>First Name</label><input type="text" id="fname" name="fname" value=""/>
</li>
<li>
<label for lname>Last Name</label><input type="text" id="lname" name="lname" value=""/>
</li>
<input type="submit" value="Submit" id="submit" name="submit"/>
</form>
<script type="text/javascript">
jQuery('#submit').submit(ajaxSubmit);
function ajaxSubmit() {
var newcontact = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: newcontact,
success: function(data) {
jQuery("#feedback").html(data);
}
});
return false;
}
</script>
<?php
}
function addcontact() {
$fname = $_POST['fname'];
if ($fname != "") {
echo "Your Data is" . $fname;
} else {
echo "Data you Entered is wrong";
}
die();
}
}
function jquery_add_to_contact() {
wp_enqueue_script('jquery'); // Enqueue jQuery that's already built into WordPress
}
add_action('wp_enqueue_scripts', 'jquery_add_to_contact');
add_action('wp_ajax_addcontact', array('ajaxtest', 'addcontact'));
add_action('wp_ajax_nopriv_addcontact', array('ajaxtest', 'addcontact')); // not really needed
add_shortcode('cform', array('ajaxtest', 'ajaxcontact'));
I used this as a shortcode, but I didn't get an output. What's the mistake?
You need to add an 'action' to your AJAX call.
The value should be the same as the add_action hook to wp_ajax. e.g.
This allows WordPress to know which function to run when the AJAX call is made.
This Codex page has some useful info and this article describes how to better refine the code you have.
WordPress environment
First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. These operations will be hooked in
wp_enqueue_scripts
action hook. In the same hook you should putwp_localize_script
that it's used to include arbitrary JavaScript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle.Please take a look to:
In main plugin file, add these.
File: jquery.ajax.js
This file makes the AJAX call.
Also add below codes to plugin main file.
Finally, on your functions.php file, there should be the function triggered by your AJAX call. Remember the suffixes:
wp_ajax
( allow the function only for registered users or admin panel operations )wp_ajax_nopriv
( allow the function for no privilege users )These suffixes plus the action compose the name of your action:
wp_ajax_myaction
orwp_ajax_nopriv_myaction