I'm totally a newbie on frontend development and just learning about jQuery.
I'm confused about "submit a HTML form with jQuery ajax". Here is a simple example:
<form class="form" action="" method="post">
<input type="text" name="name" id="name" >
<textarea name="text" id="message" placeholder="Write something to us"> </textarea>
<input type="button" onclick="return formSubmit();" value="Send">
</form>
<script>
function formSubmit(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var dataString = 'name='+ name + '&message=' + message;
jQuery.ajax({
url: "submit.php",
data: dataString,
type: "PUT",
success: function(data){
$("#myForm").html(data);
},
error: function (){}
});
return true;
}
</script>
As you see, when we click the button Send
, the function formSubmit()
will be invoked and the jQuery.ajax will do its job. It will send a http request with the type PUT
.
But there is an attribute in the HTML form method="post"
, now I'm confused. When we click the button, what will actually happen? The jQuery.ajax will send a request in the js function but what will the method="post"
do? Or method="post"
can be ignored? If it does nothing, can we make the attribute method
empty: <form class="form" action="" method="">
?
Additional
Now I realise that the type of the buttion in this example is button
, instead of submit
. If I change the type into submit
and click it, what will happen? Will it send two http requests, a post request comes from the form and a put request comes from the jQuery.ajax?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…