How can I process xml file on upload?

I need to process an XML-file after an admin uploads it in the wordpress backend.

1) I created the form:

function x_show_settings_page(){
?>

<form method="post">

<table class="form-table">
    <tr valign="top">
    <th scope="row">XML-Datei hochladen</th>
    <td><input type="file" name="thirdcolor" id="xmlfile" value="" /></td>
    </tr>
</table>

<?php submit_button('Hochladen'); ?>
</form>
<?php
}

2) I send the form via ajax to my function:

add_action( 'admin_footer', 'x_add_settings_js' );
function x_add_settings_js() { ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {

        var file_data = jQuery('#xmlfile').val();
        var form_data = new FormData();
        form_data.append('xmlfile', file_data);
        form_data.append('action', 'calculate_xml');

        $.ajax({
            url : ajaxurl,
            type: "POST",
            data : form_data,
            processData: false,
            contentType: false,
            success:function(response){
                alert('ok' + response);
            },
            error: function(response){
                alert('no' + response);  
            }
        });
    });
    </script> <?php
}

3) I want to output its content:

add_action( 'wp_ajax_calculate_xml', 'calculate_xml' );
function calculate_xml() {

    $xmlfile = $_POST['xmlfile'];
    print_r(simplexml_load_file($xmlfile));

    wp_die();
}

However it doesn’t seem to work. My response doesn’t return anything, except my teststring ‘ok’.

1 Answer
1

I solved my problem with lots and lots of testing things out.
Apparently my FormData Object was not correct.
Doing these changes to my code worked:

$('#xml').on('submit', function(e) {
        e.preventDefault();

        var form_data = new FormData(this);
        form_data.append('action', 'calculate_xml');

        $.ajax({
            url : ajaxurl,
            type: "POST",
            data : form_data,
            processData: false,
            cache: false,
            contentType: false,
            success:function(response){
                $('#response').html(response);
            },
            error: function(response){
                $('#response').text('error');
            }
        });
    });

Leave a Comment