0

I'm getting the following XML response back from a Wordpress AJAX request and having trouble extracting the data. I think it's because it's being parsed as CDATA, but I can't see why.

<?xml version="1.0" encoding="UTF-8"?>
<wp_ajax>
   <response action="mz_mindbody_ajax_add_to_class_0">
      <object id="0" position="1">
     <response_data><![CDATA[error]]></response_data>
     <supplemental>
        <classID><![CDATA[2237]]></classID>
        <message><![CDATA[Error in add to class (2237)]]></message>
     </supplemental>
      </object>
   </response>
</wp_ajax>

This is the php to handle the AJAX call:

<script type='text/javascript'>
/* <![CDATA[ */
var my_parameters = {"ajaxurl":"http:\/\/localhost:8888\/wp-admin\/admin-ajax.php"};
/* ]]> */
</script>
<?php

// Ajax Handler
add_action( 'wp_ajax_my_ajax_handler', 'my_ajax_handler' );
function my_ajax_handler() {
    // Get the Post ID from the URL
    $classID = $_REQUEST['classID'];

    // Instantiate WP_Ajax_Response
    $response = new WP_Ajax_Response;

    if( wp_verify_nonce( $_REQUEST['nonce'], 'nonce-name' . $classID )){
    //Do something here

    $response->add( array(
        'data'  => 'success',
        'supplemental' => array(
        'classID' => 'did it',
        'message' => 'Class ID goes here', // ideally want to show $classID
        ),
     ) );
    } else {
    // Build the response if an error occurred
    $response->add( array(
        'data'  => 'error',
        'supplemental' => array(
        'classID' => 'nothing to see here',
        'message' => 'Error in add to class',
        ),
    ) );
    }
    // Whatever the outcome, send the Response back
    $response->send();

    // Always exit when doing Ajax
    exit();
}
//End Ajax

This is the jQuery code:

(function($){
$(document).ready(function($) {
    $( '.my_class' ).click( function( e ) {
        var link = this;
        var id   = $( link ).attr( 'data-id' );
        var nonce = $( link ).attr( 'data-nonce' );

        // This is what we are sending the server
        var data = {
            action: 'my_function',
            classID: id,
            nonce: nonce
        }
        // Change text of link
        $( link ).text( 'DOING IT' );

        // Post to the server
        $.post( my_parameters.ajaxurl, data, function( data ) {
            // Parse the XML response with jQuery
            // Get the Status
            console.log(data); //the XML data posted above
            var status = $( data ).find( 'response_data' ).text();
            // Get the Message
            var message = $( data ).find( 'supplemental message' ).text();
            // If we are successful, add the success message and remove the link
            console.log(status); // empty string
            if( status == 'success' ) {
            $( link ).parent().after( '<p><strong>' + message + '</strong></p>').remove();
            } else {
            // An error occurred, alert an error message
            alert( message );
            }
        });
        // Prevent the default behavior for the link
        e.preventDefault();
        });
    }); 
})(jQuery);

In the tutorial I'm following the $response->add() calls are within a function. Is the fact that mine aren't what's causing the problem here?

Wait - I have misrepresented the data "object", which may be part of (or all of) the problem. The entire data "object" is actually a string, which in the console looks like:

<script type='text/javascript'>
/* <![CDATA[ */
var mz_mbo_params = {"ajaxurl":"http:\/\/localhost:8888\/wp-admin\/admin-ajax.php"};
/* ]]> */
</script>
<?xml version='1.0' encoding='UTF-8' standalone='yes'?><wp_ajax><response action='mz_mindbody_ajax_add_to_class_0'><object id='0' position='1'><response_data><![CDATA[error]]></response_data><supplemental><classID><![CDATA[nothing to see here]]></classID><message><![CDATA[Error in add to class]]></message></supplemental></object></response></wp_ajax>
1
  • yea. i think so. the XML I posted is the result of the console.log(data); in the $.post callback you can see above. That anonymous function is the $.post callback, right? Commented Mar 28, 2015 at 0:27

2 Answers 2

1

Update

Given response data string ; Note, not certain about quotations of actual raw string returned at data

var data = "<script type='text/javascript'>/* <![CDATA[ */var mz_mbo_params = {\"ajaxurl\":\"http:\/\/localhost:8888\/wp-admin\/admin-ajax.php\"};/* ]]> */</script><?xml version='1.0' encoding='UTF-8' standalone='yes'?><wp_ajax><response action='mz_mindbody_ajax_add_to_class_0'><object id='0' position='1'><response_data><![CDATA[error]]></response_data><supplemental<classID><![CDATA[nothing to see here]]></classID><message><![CDATA[Error in add to class]]></message></supplemental></object></response></wp_ajax>";

try utilizing jQuery.parseHTML()

var xml = $.parseHTML(data, document, false)[1]; // remove `script` element
// do stuff
$(xml).find("message");

Try utilizing $.parseXML() with data argument , calling jQuery() with documentElement of parsed xml document argument

// response `data` from `$.post()` callback
var xmlDocument = $.parseXML(data); 
// `documentElememt` `<wp_ajax></wp_ajax>` of response `xml` `data`
var xml = $(xmlDocument.documentElement); 
var status = xml.find("response_data").text();
var message = xml.find("supplemental message").text();
console.log(status); // empty string
if ( status == "success" ) {
   $( link )
   .parent()
   .after("<p><strong>" + message + "</strong></p>").remove();
} else {
   // An error occurred, alert an error message
   alert( message );
}

var data = '<wp_ajax><response action="mz_mindbody_ajax_add_to_class_0"><object id="0" position="1"><response_data><![CDATA[error]]></response_data><supplemental><classID><![CDATA[2237]]></classID><message><![CDATA[Error in add to class (2237)]]></message></supplemental></object></response></wp_ajax>'
var xmlDocument = $.parseXML(data);
var xml = $(xmlDocument.documentElement);
var status = xml.find("response_data").text();
var message = xml.find("supplemental message").text();
console.log(status); // empty string
if ( status == "success" ) {
   $( link )
   .parent()
   .after("<p><strong>" + message + "</strong></p>").remove();
} else {
   // An error occurred, alert an error message
   alert( message );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

12 Comments

Ah. This is illuminating. I have misrepresented my data object. When I run your code with the hard-coded data it works, but the data I'm actually returning contains more details at the top - which I'm added to the question: <script type='... + /* <![CDATA[ */...+var mz_mbo_params = {"ajaxurl"+<?xml version='1.0' and THEN the wp_ajax stuff!
@MikeiLL Is data returned as html string , xml string , or object "data object" ?
Can include returned raw text string at post, including quotation marks, without formatting ? , how returned at console.log(data) - before any processing ? If possible, can add textStatus, jqxhr to $.post() callback, console.log(jqxhr.responseText) ?
Yes. Can include actual raw string at original post, without formatting as html ? , instead of <script type='text/javascript'> and remainder of string wrapped in code block ? including ', or "" around jqxhr.responseText ? An alternative approach would be to utilize $.parseHTML(data, document, false)[1] to extract xml from returned data; though, requires string to try at stacksnippets . See api.jquery.com/jQuery.parseHTML
Yes, "keys" appear to be jQuery "array-like" object ? Can post returned string "data" at original post ? Are keys retrieved utilizing $.parseXML or $.parseHTML ?
|
1

This is a problem you've got with your wordpress configuration. Fix the configuration that results in pre-pending XML-RPC responses with the ajax script tag. It breaks the response.

Most likely you've registered that on some hook that is too generic or your hooked function doesn't filter out AJAX calls.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.