In the past, whenever I needed to get the value of an html element, I would always submit a form to load a different page. Something like:
page1.php
<form name="form1" action="page2.php" method="post"> <input type="hidden" name="input1" value="value1" />
</form>page2.php
<?php $data = $_POST['input1'];
?>My question is, is it possible to get the value of 'input1' on the same page (page1.php) without requiring clicking a submit button?
2 Answers
With jQuery:
<?php if (isset($_POST['data'])) { $data = $_POST['data']; print( "data is: $data" ); return; }
?>
<html xmlns="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.6.3.js"></script>
</head>
<body>
<div>Response from server: <span></span></div>
<script type="text/javascript"> $.post('test.php',{'data': "value1"}, function (data) { $('#response').text(data); });
</script>
</body>
</html>Non-jQuery IE doesn't have the XMLHttpRequest object so here is a shim for IE:
Yes, using ajax / javascript:
var formData = new FormData();
formData.append("input1", "value1");
var xhr = new XMLHttpRequest();
xhr.open("POST", "page1.php");
xhr.send(formData);
if (typeof XMLHttpRequest == "undefined") XMLHttpRequest = function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} //Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant throw new Error("This browser does not support XMLHttpRequest.");
}; 11 What for? Do you want to submit it to another file without needing to actually "submit" the form?
You use JavaScript for that.
document.form1.input1.value 2