I am trying to have my ajax load the data once the page loads and be able to click on a button to update the data when need it. Right now it only works on the button click. Here is a sample of what I have.
<a id="update" href="#" class="button">Update Data</a>
<div id="container">
<div id="mydata"></div>
</div>
$(document).ready(function() {
$("#update").click(function(e) {
e.preventDefault();
$.ajax({
url: "mycode",
dataType: "json",
data: {
//id: $(this).val(),
},
success: function(result) {
alert(JSON.stringify(result));
},
error: function(result) {
console.log(result);
}
});
});
});
Thanks for looking!
To achieve this you can either leave your code as is and just raise a click event on load:
$("#update").click(function(e) {
e.preventDefault();
// ajax logic here...
}).click(); // < raise event on load
Alternatively you can extract the AJAX logic to a function which is called in both places:
function makeAjaxCall() {
// ajax logic here...
}
$('#update').click(function(e) {
e.preventDefault();
makeAjaxCall();
}); // on click
makeAjaxCall(); // on load
You need to put your AJAX call in your .ready scope, it's currently blocked by the click function.
$(document).ready(function() {
updatePage();
$("#update").click(function(e) {
e.preventDefault();
updatePage();
});
});
function updatePage(){
$.ajax({
url: "mycode",
dataType: "json",
data: {
//id: $(this).val(),
},
success: function(result) {
alert(JSON.stringify(result));
},
error: function(result) {
console.log(result);
}
});
}
Here you go:
$(document).ready(function() {
$("#update").click(function(e) {
e.preventDefault();
loadData();
}
loadData();
});
function loadData() {
$.ajax({
url: "mycode",
dataType: "json",
data: {
//id: $(this).val(),
},
success: function(result) {
alert(JSON.stringify(result));
},
error: function(result) {
console.log(result);
});
});
}
<a id="update" href="#" class="button">Update Data</a>
<div id="container">
<div id="mydata"></div>
</div>