2

Is there a way I could process an XML file and display it

<?xml version="1.0"?>
<phonebooks>
<contacts group_name="Sample" editable="1" id="0">
<contact first_name="Extension" last_name="1000" contact_type="sip" subscribe_t$
        <numbers>
                <number dial="1620" dial_prefix="" label="Extension" primary="1$
        </numbers>
</contact>
. . . 
</phonebooks>

that's what file I need it to display, just in the text area, nothing special. I'm open to most solutions. Here is what I tried so far

var textarea = $("#xml"); 

$.ajax({
    type: "GET",
    url: "http://localhost/contacts.xml",
    cache: false,
    dataType: "xml",
    success: function(xml) {
        var xmlText = new XMLSerializer().serializeToString(xml);
        textarea.text(xmlText);
    }

});

I get no display in my textarea nor any errors in the console.

Naveen Kumar Alone
  • 7,536
  • 5
  • 36
  • 57
Seth Earby
  • 149
  • 3
  • 4
  • 12
  • You want all of it in 1 textarea? And yes there is a way.. it just depends on how you want it to be displayed – putvande Aug 13 '13 at 21:00
  • Yeah in one text area, to take all these contents and put it in an editable textarea is what I need. I would just need that function to be able to read multiple names. Contacts1.xml, Contacts2.xml etc. – Seth Earby Aug 13 '13 at 21:03
  • So what have you tried? – putvande Aug 13 '13 at 21:05
  • So really, what you want is to allow users to edit the text file, and then re-save the edited file back into the server's file system? – cssyphus Aug 13 '13 at 21:07
  • @gibberish yes, that is what I would need. I'm thinking Ajax is the only way so far. – Seth Earby Aug 13 '13 at 21:09
  • Had PHP on an earlier question that I posted and they deemed it irrelevant. But yes, PHP accesses the directory, and I was told ajax was where I needed to go and it stopped there. – Seth Earby Aug 13 '13 at 21:23
  • AJAX is just a simple construct for sending data **FROM** the DOM (client's browser) via Javascript **TO** a PHP file on the server for processing, **AND OPTIONALLY** receiving back a response which can be re-introduced into the DOM. In your case above, it is not strictly necessary to use AJAX because you can use PHP to read the XML file and build an HTML document that contains a `
    ` with fields for all the data. Upon submission of the form, the data is sent to another PHP file for parsing, reconstruction of the XML document, and saving back to the server's file system.
    – cssyphus Aug 13 '13 at 21:27
  • Nice explanation, I don't need to organize into forms. I just need to slap it into a textarea, edit, and save on completion. – Seth Earby Aug 13 '13 at 21:29
  • Ah... that's what's going on... the right side of your XML is cut off in the OP. I'm not very conversant with XML so... – cssyphus Aug 13 '13 at 21:50
  • Sorry, I've run out of time. I gave it a shot but haven't previously loaded text from server into a textarea control before. Here are some possible links that might steer you in the right direction: [save textarea into file using php](http://stackoverflow.com/questions/15183417/cant-save-textarea-to-file-using-php) || [save txt files from HTML textarea using PHP](http://stackoverflow.com/questions/12773838/how-can-i-save-txt-files-from-a-html-textarea-using-php) || [use jQuery to load xml file](http://forum.jquery.com/topic/using-jquery-to-load-an-xml-file) – cssyphus Aug 13 '13 at 21:51

2 Answers2

5

Here is a fully working example. Just copy paste into three files named:

whateveryouwant.php
another_php_file.php (to change name, you must also change in ajax code (2 places)
contacts.xml

How It Works:

The first ajax code block runs as soon as the DOM is ready (note: no event triggers it, it just runs. The 2nd code block is triggered by a click event). The ajax sends this POST over to the PHP file called another_php_file.php: req=load. This is a key=>value associative array: "req" is the var name, and "load" is its value.

Now, look what happens inside another_php_file.php. Upon launch, the file checks what POST variables it received. If $_POST['req'] == 'load' then it reads the file from disk and ECHOes it back out. That's how AJAX works: whatever is echoed from the specified PHP processor file is received inside that AJAX code block's success: function.

And how does the xml text get inside the textarea control? Look again at that first AJAX code block. Remember that data echoed from the PHP processor file is received inside the success function? Here's the magic:

success: function(result) {
    $('textarea').val(result);
}

result is a variable (could name it anything) containing what was echoed by the PHP file. Then we use jQuery to stick result into the textarea control.

Note that I did not specify an ID for that textarea control. This code assumes there is only one on your page. If you had more than one, then you would reference the desired textarea control by its ID:

    $('#myText').val(result);

The HTML:

<head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function() {

                $.ajax({
                    type: 'POST',
                    url: 'another_php_file.php',
                    data: 'req=load',
                    success: function(result) {
                        //alert(result);
                        $('textarea').val(result);
                    }
                });

                $('#mybutt').click(function() {
                    var stuff = $('textarea').val();
                    alert(stuff);
                    $.ajax({
                        type: 'POST',
                        url: 'another_php_file.php',
                        data: 'req=save&changes=' +stuff,
                        success: function(result) {
                            alert(result);
                            //$('textarea').val(result);
                        }
                    });
                });

            }); //END $(document).ready()

        </script>
    </head>
<html>
    <body>
        <input type="button" value="Save Changes" id="mybutt" />
        <textarea id='myText'  rows="30" cols="120" value='<?php echo $xml; ?>' />
    </body>
</html>

another_php_file.php

<?php

//This necessary to prevent AJAX from automatically ESCAPING all values (e.g. "Bob" is turned into \"Bob\" )
//See http://stackoverflow.com/questions/4550036/jquery-is-automatically-escaping-ajax
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}

if ($_POST['req'] == 'load') {
    $xml = file_get_contents("contacts.xml");
    echo $xml;

}else if ($_POST['req'] == 'save') {
    $d = $_POST['changes'];
    //echo $d;
    $size = file_put_contents('contacts.xml', $d);
    echo 'Wrote ' .$size. ' bytes to file. Refresh page with [Ctrl]+[F5] to see your changes.';
}

contacts.xml

<?xml version="1.0"?>
<phonebooks>
<contacts group_name="Dimple" editable="1" id="0">
<contact first_name="Extension" last_name="1000" contact_type="sip">
        <numbers>
            <number dial="1620" dial_prefix="" label="Extension" primary="1">
        </numbers>
</contact>
<contact first_name="George" last_name="Smith" contact_type="sip">
        <numbers>
            <number dial="1700" dial_prefix="" label="Extension" primary="1">
        </numbers>
</contact>
</phonebooks>
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • Sweet, looks like a start I appreciate it greatly. – Seth Earby Aug 13 '13 at 22:03
  • What else is left on this gibberish? The //End part? – Seth Earby Aug 14 '13 at 16:04
  • Man, that's amazing. I hate that you coded all that to show me, but honestly, I'm really glad you did. For me and for anyone else who stumbles upon it. What actually appends it to the textarea? Again, well done. – Seth Earby Aug 14 '13 at 16:55
  • Man, kudos to you. Have a great week! – Seth Earby Aug 14 '13 at 17:19
  • Could you also transform that first ajax function to triggered by click event as well? – Seth Earby Aug 15 '13 at 17:27
  • 1
    Sure. Exactly the same way as the second one: surround it with the `$('#mubutt').click(function() {` //AJAX code block here `}`. Or, say you want to create another button with ID="bonkers": `$('#bonkers').click(function() {` //AJAX code block here `}`. [Here are some more ajax examples](http://stackoverflow.com/questions/17973386/ajax-request-callback-using-jquery/17974843#17974843) to check out (pls upvote any you find useful). – cssyphus Aug 15 '13 at 17:42
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/35538/discussion-between-seth-earby-and-gibberish) – Seth Earby Aug 15 '13 at 18:23
  • I won't be able to monitor chat effectively until we connect, so please create a new question and leave a link to the new question here as a comment. I'd be happy to help. Did you check out the other ajax examples I linked to above - [Here are some more ajax examples](http://stackoverflow.com/questions/17973386/ajax-request-callback-using-jquery/17974843#17974843)? – cssyphus Aug 16 '13 at 15:47
  • Yes, I've got it working and just have one final step that I'm going over. Thanks. – Seth Earby Aug 16 '13 at 17:17
  • Glad to hear it. Post any other questions you get stuck on. – cssyphus Aug 16 '13 at 17:30
  • [Here is my new one](http://stackoverflow.com/questions/18279010/store-javascript-select-option-into-php-variable) Thanks again gibberish. – Seth Earby Aug 16 '13 at 17:32
0

You should set dataType to "text" and contentType to "text/plain" in your ajax request because you are treating the result as a text. Your ajax request code would like below:

var textarea = $("#xml"); 

$.ajax({
    type: "GET",
    url: "http://localhost/contacts.xml",
    cache: false,
    contextType: "text/plain",
    dataType: "text",
    success: function(xml) {
        textarea.text(xml);
    }

});
meebee
  • 116
  • 1
  • 3