Reputation: 3819
I have a JSON page the content would be {"success":1} or {"success": 0}
depending on the success value, I have to show error message or a success message. If the page is unavailable then I should give a error message too. I have a spinner in the loading div: Here is my code.
url = "add.jsp";
$("#loading").show();
$.getJSON(url, dataToBeSent, function(data) {
$.each(data, function(key, val) {
if (val == 0) {
$("#loading").hide();
$("#add_response").show();
$("#add_response #error_message").show();
$("#add_response #success_message").hide();
} else {
$("#loading").hide();
$("#add_response").show();
$("#add_response #error_message").hide();
$("#add_response #success_message").show();
}
})
.fail(function(){
$("#loading").hide();
$("#add_response").show();
$("#add_response #error_message").hide();
$("#add_response #success_message").show();
});
});
There are no error message in my console. I don't have file add.jsp. Hence getJSON
should fail. What am I doing wrong? Please help me finding out. Why the fail is not called at all ?
Follow Up: This is the code following answer suggested by Hardik
<script type="text/javascript">
var url = "add.jsp";
$("document").ready(function() {
$('input[name=submit]').click(function(e) {
var dataToBeSent = $("form").serialize();
var url = 'db.jsp';
$.ajax({
url : url,
data : dataToBeSent,
dataType : 'json',
success : function(response) {
$('#response').text(response.success);
},
error : function(request, textStatus, errorThrown) {
alert(request.status + ', Error: ' + request.statusText);
// perform tasks for error
}
});
e.preventDefault();
});
});
</script>
Upvotes: 1
Views: 992
Reputation: 14877
<script type="text/javascript" src="js/jquery.min.js"></script>
// I have jquery.js under js directory in my webapp
<script type="text/javascript">
var url = "add.jsp";
$(function(){
$.ajax({
url : url, // Pass you Servlet/ JSP Url
data : {
empId : 0
}, // data can be passed from outside
dataType : 'json',
success : function(response) {
alert('Success');
// perform tasks for success
},
error : function(request, textStatus, errorThrown) {
alert(request.status + ', Error: ' + request.statusText);
// perform tasks for error
}
});
});
</script>
EDIT-- Example:
<script type="text/javascript">
$(function(){
function getData(url, dataToBeSent) {
console.log(dataToBeSent);
$.ajax({
url : url,
data :dataToBeSent,
dataType : 'json',
success : function(response) {
alert(response.success);
},
error : function(request, textStatus, errorThrown) {
alert(request.status + ', Error: ' + request.statusText);
}
});
}
getData('getData.jsp', '{name:Hardik}'); // You should use Servlet to get Data. This is just an example
});
getData.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
response.setContentType("application/json");
out.println("{\"success\":1}"); // Write values using JSONObject
%>
Upvotes: 1