Set hidden field value using Javascript; use PHP p

2019-08-29 22:59发布

I need to get the user's screen resolution and save it my database.

What I'm doing is this: I have a Javascript function called with that gets the info and passes the value to a hidden form field. This is the function:

<script type="text/javascript">

function getUserData(){

var s_width=screen.width
var s_height=screen.height
document.getElementById('screen_width').value=s_width
document.getElementById('screen_height').value=s_height

}

</script>

And the form:

<form name="login" id="login" action="memberlogin.php" method="post">
<input type="hidden" id="screen_width" name="screen_width">
<input type="hidden" id="screen_height" name="screen_height">
<table style="margin-top:9px;">
<tr><td width="200px"><input type="text" name="username" style="width:100%"/></td></tr>
<tr><td width="200px"><input type="password" name="password" style="width:100%"/></td></tr>
<tr><td><input type="submit" name="submit" value="Log In" /></td></tr>
</table>
</form>

The form submits to the same page. When I click 'submit' and try to echo the value of $_POST['screen_width'] and $_POST['screen_height'], nothing happens. But when I re-submit it, the values are there. Can someone tell me what am I doing wrong? If you have an alternative solution, it would be equally appreciated.

2条回答
干净又极端
2楼-- · 2019-08-29 23:24

have you checked firebug's output? maybe there are some errors? try alert sth in your function, maybe it isn't called after initial page load? try putting function call in submit button's onClick or form's onSubmit event.

查看更多
Viruses.
3楼-- · 2019-08-29 23:29

Solved it myself, it was just a matter of calling the function after loading the element.

查看更多
登录 后发表回答