Reputation: 397
My HTML page is a form where I type in the upper bound for the random number generator and on submit, use AJAX to submit the form parameter as a HTTP request to a PHP script and then it writes the random number generated by the php to an empty div but when I hit submit, the number is there for only a split second until it goes away.
How can I edit my JQuery to get the random number to stay in the div until I either resubmit or leave the page?
In the code: The #x ID is the general form, the #y ID is the input where the upper bound is put and the #random ID is the div where the random number goes.
$('#x').on('submit', function() {
$('#random').load('random.php', $('#y').serialize());
});
Upvotes: 0
Views: 137
Reputation: 4484
when I hit submit, the number is there for only a split second until it goes away.
It's not exactly what happens: it does NOT go away. At the opposite, it is overwritten (in fact, like the whole page), because when you submit... then you submit!
(so because you didn't set a different action
attribute to your <form>
, the current page is loaded again)
In other words the important thing is that you don't want the form to be submitted, but only the submit
event to be catched to do your job.
So the solution is simply to make the submit
event to be stopped as soon you did the load()
:
$('#x').on('submit', function() {
$('#random').load('random.php', $('#y').serialize());
return false; // <-- prevent to execute the real submit action
});
Upvotes: 1
Reputation: 81
$('#x').on('submit', function(e) {
e.preventDefault();
$('#random').load('random.php', $('#y').serialize());
// or use:
// return false;
});
Upvotes: 1