Hello I have the next code into my website:
<input type="text" id="name" name="name" width="25px"/>
<a href="#" id="newUser">Add User</a>
I need that when I click "newUser" the value of the name is saved into my mysql database without refreshing the page.
Any exemple of how to do this?
This can be done on the client side with jquery's ajax libraries to create the refreshless submit.
Here's an example of some html and javascript
<html>
<head>
<script type="text/javascript" src="jq/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
function adduser()
{
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "adduser.php",
data: data,
dataType: "html",
});
}
</script>
</head>
<body>
<form id="adduserform" name="adduserform">
<fieldset>
<input type="text" id="name" name="name" width="25px"/>
</fieldset>
</form>
<a href="javascript:adduser();" id="newUser">Add User</a>
</body>
</html>
On the php side just code like you would if you were submitting a form via post.
I haven't had time to try it, but I hope it works :)
Like the others have suggested, look on the jquery site for more info.
If you don't want to use a <form>
and a submit
button which would be the absolutely correct way to do this, you will need to use javascript and AJAX:
- Subscribe for the onclick event of the anchor
- Send an AJAX request to the server passing the value of the name entered in the textbox
Cancel the default action of the link
Add User
and the insert
function could be defined in a separate javascript file:
function insert() {
var name = document.getElementById('name').value;
// TODO: send an AJAX request to the server
return false;
}
http://api.jquery.com/jQuery.ajax/
$('#newUser').click(function(ev){
$.ajax(...);
ev.preventDefault();
});
You can do an Ajax
call with JQuery that will send the name to the server. In your PHP code you will be able to create the Insert Query
in your user table.
You can use JavaScript for that. Take a look at jQuery
ajax: http://api.jquery.com/jQuery.ajax/
note: next time try googling, or at least provide what you have tried