Reputation: 156
I have a button that links to a php file that tracks user's email when clicked, but I don't want the user to leave the page when button is clicked, I just want to change button's value. This is the html of the form.
<form action="mysql-query.php" method="post">
<input type="text" name="email" style="display:none;">
<input type="submit" value="Press here" id="test" onclick="Press()">
</form>
And this is the script that handles the form:
<script>
function Press() {
var test= document.getElementById("test");
test.value="Thank you";
localStorage.value=("ok");
}
</script>
I put the display:none; because I don't want to display anything but the button and have a way to connect with my php file.
Any ideas?
Upvotes: 1
Views: 2543
Reputation: 89
Use:
<form action="javascript:void()">
Ok, this thing prevents the form from sending the data anywhere, unless you use "onclick" event on the submit button.
Upvotes: 1
Reputation: 66560
You need to use ajax:
html:
<form action="mysql-query.php" method="post" onsubmit="return Press(this)">
<input type="text" name="email" style="display:none;">
<input type="submit" value="Press here" id="test">
</form>
js:
function Press(form) {
$.post($(form).attr('action'), function() {
var test= document.getElementById("test");
test.value="Thank you";
localStorage.value=("ok");
});
return false; // prevent submitting the form
}
or better bind submit event using jQuery:
$('form').submit(function() {
$.post($(this).attr('action'), function() {
var test= document.getElementById("test");
test.value="Thank you";
localStorage.value=("ok");
});
return false; // prevent submitting the form
});
Upvotes: 1
Reputation: 1830
What you can do is remove the type="submit" on the button and replace it with type="button". Next you can do an ajax call to your php and do your magic.
Upvotes: -1