When any user logs in, I just want to send 2 parameters to PHP and then want to update related DB table. Is it possible in javascript? If possible any sample code or links appreciated.
-
you are better off using PHP call itself to update Database entries than using JavaScript, Ajax is your friend if you really need to implement this in JS only.Jasdeep Singh– Jasdeep Singh2011-04-29 05:07:06 +00:00Commented Apr 29, 2011 at 5:07
-
@drachenstern: I assume you didn't read the question carefully, the OP wants to update two values, WHEN THE USER LOGS IN (let's take sign in count for example - just assuming - lets say the OP wants to update the sign_in count for the user). This can be easily achieved by adding an afterLogin() function in PHP which would update these values after every login - SEE MOM NO AJAX! :) And again, i think you didnt read my comment carefully either - I mentioned Ajax there - which is same as what Delan talked about. The scenario might be different for sure..Jasdeep Singh– Jasdeep Singh2011-04-30 00:29:19 +00:00Commented Apr 30, 2011 at 0:29
3 Answers
You can use JavaScript to request a PHP script using XMLHttpRequest, and include some database interaction with MySQL in the PHP script.
1 Comment
AJAX is the key you're looking for.
A javascript framework such jQuery could help you a lot. There's several built in AJAX methods related in the documentation, specially this method.
Comments
It is really pretty simple using JQuery, as pedrorezende said. The easiest way would be something like
$.post('sample/path?var1=value&var2=otherValue');
Edit: here is the full code, I believe this would accomplish what you want (untested):
<script type="tex/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js">
</script>
<script type="text/javascript">
$("#login_form").submit(function() {
$.post("login_handler.php", $("#login_form").serialize());
}
</script>
<body>
<form id="login_form">
<input type="text" name="username"></input>
<input type="text" name="password"></input>
<input type="submit" value="login">
</form>
</body>
The first script will load JQuery.
The second script creates the handler and sends the form data to an external PHP file.
Then in login_handler.php you would send your query to MySQL using the $_POST values.