Append form values to hidden XML string on post
I am posting a form to a remote server and have to send over an XML formatted string as a hidden field, containing the entered info. Im struggling to append the input values entered to the XML string, E.g.:
<input type="text" name="firstname" id="fname" />
<input type="text" name="lastname" id="sname" />
The XML is as such:
<input type="hidden" name="parameters" value="<request><first_name>Test User</first_name> <surname>XXXX</surname></request>"/>
How can I with PHP ideally, on POST, apply the values entered in the inputs to the XML string, so firstname and surname are posted as entered by the user?
I tried Jque开发者_如何学JAVAry but it broke the XML string.
Many Thanks in advance!
I think you need to use java script to manipulate parameters value.
Sample example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript">
function callme()
{
document.getElementById('parameters').value="<request><first_name>"+document.getElementById('fname').value+"</first_name> <surname>"+document.getElementById('sname').value+"</surname></request>";
document.getElementById('loginForm').submit();
}
</script>
</head>
<body>
<form id="loginForm">
<input type="text" name="firstname" id="fname" />
<input type="text" name="lastname" id="sname" />
<input type="hidden" id="parameters" name="parameters" value=""/>
<input type="button" onclick="javascript:callme()" />
</form>
</body>
</html>
html -
<input type="text" name="firstname" id="fname" />
<input type="text" name="lastname" id="sname" />
<input type="hidden" id="parameters" />
<input type="button" name="click" id="button" value="button" />
Script - Use a parameter and set before submit e.g.
$(document).ready(function() {
var parameters = "<request><first_name>YYYY</first_name> <surname>XXXX</surname></request>";
$('#button').click(function(){
parameters = parameters.replace('YYYY',$('#fname').val());
parameters = parameters.replace('XXXX',$('#sname').val())
$('#parameters').val(parameters);
alert($('#parameters').val());
});
});
I think you should do this server-side as malicious users could post anything. Having to escape your first and last name values is a lot easier than validating the correctness of your xml.
$first = htmlspecialchars($_GET['firstname']);
$last = htmlspecialchars($_GET['lastname']);
$xml = sprintf
( '<request>
<first_name>%s</first_name>
<last_name>%s</last_name>
</request>',
$first, $last
);
There is no reason to do this in javascript unless you need that xml to be sent of to a different url by ajax.
EDIT This solution also works for people having javascript turned off (e.g no-script users).
精彩评论