I'm trying to get ajax working so when a user enters a postcode and clicks submit an alert appears saying what postcode they entered.
I'm really new to AJAX so forgive me if the following if the code below is horrible!
When clicking submit an alert box appears but shows me the source code of the whole page and not the message in postcode_ajax2
.
Can anyone help please?
function ajax_postcode_form_init() {
wp_register_script('ajax-login-script', get_bloginfo('stylesheet_directory'). '/ajax-postcode-script.js', array('jquery') );
wp_enqueue_script('ajax-login-script');
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxlogin', 'postcode_ajax2' );
}
add_action('init', 'ajax_postcode_form_init');
function postcode_ajax2() {
$postcode = false;
if(isset($_POST['postcode'])){
$postcode = $_POST['postcode'];
}
echo 'Received postcode was: ' . $postcode;
die();
}
var $ = jQuery.noConflict();
$(document).ready(function(){
$('#postcode_checker').on('submit', function(e){
//Stop the form from submitting itself to the server.
e.preventDefault();
var postcode = $('#postcode').val();
console.log(postcode);
$.ajax({
type: "POST",
url: ajax_login_object.ajaxurl,
data: {
action: "postcode_ajax2",
postcode: postcode
},
success: function(data) {
alert(data);
},
error : function(error){
console.log(error)
}
});
});
});
// JavaScript Document