Entries Tagged as 'Javascript'

WordPress AJAX response codes using status_header

As I’m relatively new to WordPress plugin development, I’m constantly searching around for the cleanest and most “WordPress way” to do things. One function that helps write cleaner AJAX call handlers is status_header(), to inform the caller when things go wrong:

add_action( 'wp_ajax_myajaxaction', 'my_ajax_handler' );

function my_ajax_handler() {
    if ( ! empty($_POST) and check_ajax_referer( 'mynonce', 'nonce' ) ) {

        if ( things_go_wrong ) {
            status_header( 500 );
            echo "some informative message or code";
        }

        // ...
    }
}

and in the javascript using success and failure functions rather than deconstructing response text:

var nonce = jQuery("input#nonce").val();

jQuery.ajax({
   type: "POST",
   url: ajaxurl,
   data: {
	   name: encodeURIComponent(tabName),
	   id: tabId,
	   mynonce: nonce,
	   action: 'myajaxaction'
         },
	 success: function(msg) {
               // Handle a successful call
	 },
	 error: function(v,msg) {
            // Handle the error, with the text in msg
         }
});

You could also output the headers manually, but this gives a nice clean way to do it.

jQuery Validator Plugin with a Custom Validation Function and Dependency Selectors

The jQuery validator plugin is a great way to add validation to forms in a clean way.  Error messages shown and hidden when they attempt to submit, and on the fly when they correct the input.

I recently added a new validation function to see if the field they entered was a valid twitter hashtag or username.  Though it could be improved (ie. looking for spaces), it does the job initially.  The problem was that the same field name was used for both depending on the value of another dropdown.

To handle enabling or disabling the validation function based on a certain condition, I initially thought you just pass in true or false, such as you do with required:

jQuery('#socialAdminForm').validate({
    rules: {
        component: { twitteruserrequired: true }
    }
    // ...

However the the 3rd parameter (which I’ve labelled, ‘isactive’) needs to be evaluated based on the condition, as the boolean value is passed in here. Here’s an example that determines whether or not to use the validation function based on the select element with id wx-select-social:

jQuery.validator.addMethod('twitteruserrequired', function(value, element, isactive) {
    return !isactive || (value.trim() != '@' && value.substr(0, 1) == '@');
}, "Please enter a valid value");

jQuery.validator.addMethod('twitterhashtagrequired', function(value, element, isactive) {
    return !isactive || (value.trim() != '#' && value.substr(0, 1) == '#');
}, "Please enter a valid value");

jQuery('#socialAdminForm').validate({
    rules: {
        component: { required: true },
        name: { required: true },
        "component_behaviour": { required: true, twitteruserrequired: function(element) {
                return (jQuery("select#wx-select-social").val() == 'twitteruser');
            }, twitterhashtagrequired: function(element) {
                return (jQuery("select#wx-select-social").val() == 'twitterhashtag');
            }
        } }
    }
    // ...

Without the third parameter of the function in addMethod being evaluated for true or false, the validation function will always execute.