Reputation: 411
I'm using jquery to modify html elements from http response from jquery. The element in html was indeed modified but immediately returned to original content - looks like the page was refreshed. Please give some suggestions. Here is my code.
<form action="" method="get" id="test_form">
<div class="form-group">
<input type="text" class="form-control input-sm" >
<input type="submit" class="btn btn-primary" id="submit-btn" onclick="submit_jquery()" value="">
</div>
</form>
<p id="p_test">123</p>
//// js code
function submit_jquery() {
var i =0;
$.ajax({
type:"GET",
async: false,
url:"http://127.0.0.1:80",
data:{source: i},
dataType:"json",
success:function(data){
j = JSON.stringify(data);
$("#p_test").replaceWith(j);
},
error: function(){
}
});
}
Upvotes: 0
Views: 151
Reputation: 24638
When dealing with forms always listen for the form
's submit event rather than for the submit
button's click event. Both events do fire but when you focus on the button's click event you're not able to stop the form's default action when it's submit
button is clicked. I would therefore take the following approach:
$(function() {
$('#test_form').on('submit', function(e) {
//stop form from submitting (defaut action)
e.preventDefault();
var i =0;
$.ajax({
type:"GET",
async: false,
url:"http://127.0.0.1:80",
data:{source: i},
dataType:"json",
success:function(data){
j = JSON.stringify(data);
$("#p_test").replaceWith(j);
},
error: function(){
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="get" id="test_form">
<div class="form-group">
<input type="text" class="form-control input-sm" >
<input type="submit" class="btn btn-primary" id="submit-btn" value="SUBMIT">
</div>
</form>
<p id="p_test">123</p>
Upvotes: 0
Reputation: 34127
As you are handling the submission via jQuery/Ajax, you need to handle the form onSubmit
event and return false so that the normal form submission(which reloads the page) is cancelled.
Try this
<form action="" method="get" id="test_form" onSubmit="return false">
Upvotes: 1
Reputation: 696
Try to return false
after the ajax. It prevents the page from redirecting.
function submit_jquery(){
// your code here
return false;
}
Upvotes: 0
Reputation: 42
The page must be reloading because the type of button is submit
You can change it to
<input type="button">
which will stop it from refreshing page
Upvotes: 1