I am stuck on trying to fetch data using AjAX. Below is the code for a HTML form that has an input value. The data value gets pushed to a python handler via a submit button. On the server side, the python handler stores the data in the database.
Now I need to fetch the data from the database first via AJAX and display if there is an existing value. The data consists of a "yes or no" status, so pretty simple. But I don't know how to fetch the data using ajax, and properly set the input value based on data fetched. The question, how would I call a handler via Ajax to return a value?
<html>
<script language="javascript" src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
send_data = function(status) {
$.ajax({
url: "/Subscription",
dataType: "json",
data: {'status' : status},
type: "POST",
cache: false
}).done(function(data, status, xml) {
var obj = jQuery.parseJSON(data);
alert(obj.success);
}).fail(function(jqXHR, textStatus, errorThrown) {
}).always(function() {
});
}
$(document).ready(function() {
$("#subscription").submit(function() {
send_data($("#switch-1").prop('checked') ? 'yes' : 'no');
return false;
});
});
</script>
</head>
<body>
<form id="subscription" action="" method="post">
<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
<input type="checkbox" id="switch-1" class="mdl-switch__input" id="status" name="status" />
<span class="mdl-switch__label">blemtorp@google.com subscription status is: << subscription >> </span>
<input type="submit" value="Submit" /></label>
</form>
</body>
</html>
Thanks so much. Any hints will be so helpful.
</div>
To perform an asynchronous call based on user input, you have to make the request and then explicitly specify which actions you want to perform in the request is successful, fails, etc.
For example:
function send_data(shouldRequest, successCallback) {
// if ...prop('checked'), run ajax request
if (shouldRequest) {
$.ajax({
url: "/Subscription",
dataType: "json",
data: {'status' : status},
type: "POST",
cache: false
}).done(function(data, status, xml) {
// when request completes, run callback function
successCallback(data);
});
}
}
$("#subscription").submit(function() {
var checked = $("#switch-1").prop('checked');
var successCallback = function(data) {
// perform success actions on data here
}
send_data(checked, successCallback);
});
If you pass successCallback
to the send_data
function, you can run the function only when the asynchronous call has successfully completed. You can also pass in other functions to handle errors, etc.
You can additionally pass in other functions to handle different results from your ajax request, like a function to handle errors.
By setting dataType:"json"
in ajax there is no need to use JSON.parse()
on done()
callback.
Use data.success
or data.status
depending on your json.
Example json response {'success':'yes'}
or {'status':'yes'}