Reputation: 258
I want to be able to load an xml file from my server. Edit a node in the xml with jQuery and then save this change with the rest of the xml file back to the server using php. Anyone know how to do this? I have code that changes the xml node and can see this in my console. But cannot get the code back to my server.
Thanks!
<?php
$xml = $_POST['xml'];
$file = fopen("data.xml","w");
fwrite($file, $xml);
fclose($file);
?>
$.post('saveXml.php', { xml: $(data)}, function(data){alert('data loaded');});
if I console.log(data) I get #document and all the xml nodes. I also get the data.xml file on my server but it's blank.
Upvotes: 1
Views: 9165
Reputation: 171690
Have never done this before but found some information here: Convert xml to string with jQuery
I have tested the following which will modify the original xml and send back to server as a string received by $_POST['xml']
$(function() {
$.get('test.xml', function(xml) {
var $xml = $(xml)
/* change all the author names in original xml*/
$xml.find('author').each(function() {
$(this).text('New Author Name');
})
var xmlString=jQ_xmlDocToString($xml)
/* send modified xml string to server*/
$.post('updatexml.php', {xml:xmlString },function (response){
console.log(response)
/* using text dataType to avoid serializing xml returned from `echo $_post['xml'];` in php*/
}'text')
}, 'xml')
});
function jQ_xmlDocToString($xml) {
/* unwrap xml document from jQuery*/
var doc = $xml[0];
var string;
/* for IE*/
if(window.ActiveXObject) {
string = doc.xml;
}
// code for Mozilla, Firefox, Opera, etc.
else {
string = (new XMLSerializer()).serializeToString(doc);
}
return string;
}
DEMO: http://jsfiddle.net/54L5g/
Upvotes: 4