Created
October 16, 2014 12:36
-
-
Save chrisblakley/f0b2365357d970ad0130 to your computer and use it in GitHub Desktop.
Use your functions file to perform AJAX calls through Wordpress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form class="ajax-example-form"> | |
<input type="text" class="message" /> | |
<input type="submit" /> | |
</form> | |
<div class="example-response"></div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Add this to functions.php | |
add_action('wp_ajax_nebula_example_ajax', 'nebula_example_ajax_function'); | |
add_action('wp_ajax_nopriv_nebula_example_ajax', 'nebula_example_ajax_function'); | |
function nebula_example_ajax_function() { | |
echo 'Success! Your message was: "' . $_POST['data'][0]['message'] . '"'; | |
exit(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(document).on('submit', '.ajax-example-form', function(e){ | |
var messageData = [{ | |
'message': jQuery(".ajax-example-form input.message").val() | |
}]; | |
jQuery.ajax({ | |
type: "POST", | |
url: bloginfo["admin-ajax"], //bloginfo["admin-ajax"] is localized from functions.php | |
data: { | |
action: 'nebula_example_ajax', | |
data: messageData, | |
}, | |
success: function(response){ | |
jQuery('.example-response').css('border', '1px solid green').text(response); | |
}, | |
error: function(MLHttpRequest, textStatus, errorThrown){ | |
jQuery('.example-response').css('border', '1px solid red').text('Error: ' + MLHttpRequest + ', ' + textStatus + ', ' + errorThrown); | |
}, | |
timeout: 60000 | |
}); | |
e.preventDefault(); | |
return false; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment