This is my code (im using codeigniter as my framework and this is the view). This code should write the div named contain's content to the file called newfile.php after the submit button is clicked. But I need to click the button 2 times before it writes the data into the newfile.php. Help please. I don't know what's wrong with my code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Online Lodging Locator</title>
</head>
<script>
function test(){
var x = document.getElementById('contain').innerHTML;
alert(document.my_form.my_var.value=x);
<?php
$content = $_POST["my_var"];
$myfile = fopen("newfile.php", "w") or die("Unable to open file!");
fwrite($myfile, $content);
fclose($myfile);
?>
}
</script>
<body>
<form name="my_form" method="post">
<input type="hidden" name="my_var">
<div id="contain">
<h1>Online Lodging Locator</h1>
<table cellspacing="0" cellpadding="1" border="1">
<tr>
<td>COL 1 - ROW 1222<br />COLSPAN 3</td>
<td>COL 2 - ROW 1</td>
<td>COL 3 - ROW 1</td>
</tr>
<tr>
<td rowspan="2">COL 2 - ROW 2 - COLSPAN 2<br /></td>
<td>COL 3 - ROW 2</td>
</tr>
<tr>
<td>COL 3 - ROW 3</td>
</tr>
</table>
</div>
<button type="submit" class="btn btn-default" name="SEARCH" id="SEARCH" onclick="test()">WRITE</button>
</form>
</body>
</html>