I want use jquery to sent form data to server, and I follow this page↓
how do i submit a form using get method in jquery .
But is not working, has no any window alert. I don't know why....
I already import the jquery script in head(version 1.11.3).
<script src="./static/jquery-1.11.3.js" type="text/javascript"></script>
this is my script.
<script>
function test(){
document.getElementById("form_test").submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( response ) {
alert( response );
},
error:function(){
alert("error");
}
});
return false;
});
}
</script>
this is my form code.
<form id="form_test" class="appnitro" method="post" action="">
<div class="form_description">
<p>test.</p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="info">info</label>
<div>
<input id="info" name="info" class="setInfo" type="text" maxlength="16" value=""/>
<label id="infoMsg" class="Message"></label><br/>
</div>
</li>
<li class="buttons">
<button type="button" class="mbutton" onclick="test()">submit</button>
</li>
</ul>
</form>
You need to have a form submit event handler registered in the dom ready handler
$(function () {
$("#form_test").submit(function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
});
})
In your code, you are calling the test
method on click of the button, which calls the form
elements submit function with a callback
Remove the submit handler from test()
document.getElementById("form_test").submit(function () {
This is not required as the function test
is being called when user clicks on the button.
function test() {
var $form = $('#form_test');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
}
I would also suggest you to use jQuery on()
to bind event
$('#form_test').on('submit', function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
});
As you used inline js in submit button, no need for submit event handle for this. See code below :
<script>
function test(){
var myForm = document.getElementById("form_test");
$.ajax({
url : $(myForm).attr('action'),
type : $(myForm).attr('method'),
data : $(myForm).serialize(),
success : function( response ) {
alert( response );
},
error:function(){
alert("error");
}
});
return false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.