Support » Requests and Feedback » AJAX documentation (Plugin handbook) – Better code example needed

  • The docu page for server side AJAX handling in PHP is aimed at people both experienced and inexperienced in AJAX handling.

    The example is too simple to be really useful – the JS only passes one variable as the data object, rather than a serialized form, as plugin developers often need. And so, in the relevant PHP AJAX section, no mention is made of the need in a PHP handler function to parse a serialized data string if that is what has been passed by the JS (as is the case in almost every AJAX example on the web). Discovering this cost me two days of work time. The relevant terms are too widely used on stackexchange, etc. to yield the answer quickly and I went down many wrong paths.

    A slightly richer example in the Data section would solve the problem. Specifically here:

    $args = array(
        'tag' => $_POST['title'],
    );
    $the_query = new WP_Query( $args );

    In the example here, ‘title’ is sent as a parameter of the AJAX post.

    jQuery(document).ready(function($) {           //wrapper
        $(".pref").change(function() {             //event
            var this2 = this;                      //use in callback
            $.post(my_ajax_obj.ajax_url, {         //POST request
               _ajax_nonce: my_ajax_obj.nonce,     //nonce
                action: "my_tag_count",            //action
                title: this.value                  //data
            }, function(data) {                    //callback
                this2.nextSibling.remove();        //remove current title
                $(this2).after(data);              //insert server response
            });
        });
    });
    

    But if ‘title’ is passed as part of the AJAX data parameter in an array, like this:

    
    	$('#form_settings input[type="submit"]').click(function(e){
    		e.preventDefault();
    		var formSettings = $('#form_settings').serialize();
    		$.post( pluginSettings.ajax_url, {
    			_ajax_nonce: pluginSettings.nonce,
    			action: "plugin_settings_handler",
    			data: formSettings,
    			dataType:'json',
    			// title: this.value, 
                            // If 'title' is not sent as a parameter, PHP handler cannot access $_POST['title']
    		}, function(data){ //
    			$("#form_settings .feedback").html(data);
    		});
    	});
    

    In this case it is NOT available as $_POST[‘title’] on the PHP side! You have to parse the data object like this:

    		$fields = array();
    		parse_str($_POST['data'], $fields);
    

    Then you can access $fields[‘title’].

    Otherwise you get an “index does not exist” error for the “$_POST” variable.

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.