I am attempting to implement a get request via $.ajax
upon the user submitting a form.
I am not sure if what I am doing is the most efficient method (binding a click to the form button) so if there is a more efficient way (or standard way), please suggest it!
My result is that the content div is filled properly in FF/Chrome, but IE it is not. IE seems to be submitting the form and reloading the page entirely.
In addition, I really do think I need to "submit" the form, because I want to take advantage of jQuery validate();
which does not work with the below implementation (even in FF/Chrome).
Javascript:
$(document).ready(function(){
$("#theForm").submit(function(){
// build our data to send in our request
var mydata = {method: "search", color: $('#color').val()};
$.ajax({
url: 'foo.php',
data: mydata,
type: 'get',
dataType: 'json',
success: function(data){
$("#content").html(data);
}
error: function(e){
console.log(e.message);
}
});
return false;
});
});
HTML :
<form id="search">
<input type="submit" />
</form>
<div id="content"></div>
You should change your submit button to be of type button. Inputs of type submit automatically post the page and in your case this is not necessary.
<input type="button" id="search-button">
Otherwise you can prevent the default action of the button using event.preventDefault().
$("#search-button").click(function(event){
event.preventDefault();
$.ajax({
url: 'foo.php',
data: mydata,
type: 'get',
dataType: 'json',
contentType: 'application/json',
success: function(data){
$("#content").html(data);
}
});
});
Since you are expecting html back from the server, it is best to specify the dataType
that you are expecting is actually html. Note, you previously had json to be the dataType
. You can also specify the type of data you are passing to the server using contentType
which in your case is json so you should use application/json
.
Per your comments, your dataType should be json.
I just noticed that it seems your $(document).ready(function() {});
does not seem to be closed. You seemed to have forgot the );
. Is this a copy paste issue?
After your most recent code edit, you seem to be missing a comma between your success and error.
$.ajax({
url: 'foo.php',
data: mydata,
type: 'get',
dataType: 'json',
success: function(data){
$("#content").html(data);
}, // <---
error: function(e){
console.log(e.message);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With