I want to check if json data is empty or not.
if json its empty, i want to alert orders Not Found.
If its not empty, i want to alert orders found.
if user not logged in, there won't be any token in his localstorage. so he will get a 500 error when browser requests the API URL. then I want to alert failed along with the failed status reason
my dev is sick, so tried my self. its not going too well.
Tried the below code, not at all working.
<script>
$http.get("http://localhost.com/activeorders/?format=json",{
headers: {'Authorization': 'Token '+ localStorage.getItem("token")}})
.success(function(response) {
if(response=="[]")
{
alert(" orders NOT found");
}
else
{
alert("orders found");
}
.error(function(response,status) {
alert("failed");
alert(status);
}
return ;
});
</script>
Any help will be thankfull.
if you are trying to do in Angular js, then you can try the code below using callbacks:
$http({
method: 'GET',
url: 'http://localhost.com/activeorders/?format=json',
headers: {
'Authorization': 'Token '+ localStorage.getItem('token')
}
}).then(function successCallback(response){ // this callback will be called asynchronously when the response is available
if (response.data.length == 0){
console.log("orders NOT found")
}
// or if you just return an array json by php for example
//if (response.length == 0) {
//console.log("orders NOT found")
//}
}, function errorCallback(response){ // called asynchronously if an error occurs or server returns response with an error status.
if (response){
alert("failed");
}
});
If you are using an external file .json type, you can try :
menuApp.controller("dynamicMenuController", function($scope, $http) {
$http.get('config/menu.json').success(function(data) {
console.log("success!");
if(data.length == 0){
alert('empty');
}
else {alert('some here!')}
});
If your json is in another domain, an external domain . In this case , I suggest you look at JSONP instead, here's an example http://fdietz.github.io/recipes-with-angular-js//consuming-external-services/consuming-jsonp-apis.html:
$http.jsonp('http://teckstack.com/api/get_recent_posts/?callback=JSON_CALLBACK').success(function (data) {
console.log("success callback");
if(data.length == 0){
alert('empty');
} // response data
}).error(function (data) {
console.log("failed callback");
});
If you want to check if a JS object or JSON is empty ({}), for example, your object is response:
Object.keys(response).length === 0 && response.constructor === Object
Try
if( Object.keys(JSON.parse(response)).length == 0 ){
alert("err")
}
Related
I'm using angularjs to call my Rest web services but I have a problem with error handle.
This is one of my http calls:
$http({
method: 'POST',
url: "tr"+licenseSelected,//angular need string in url
headers: {'Content-Type': 'application/json'},
data : updatedLicense,
beforeSend: function() {
waitingModal.showPleaseWait();
},
complete: function() {
setTimeout(function(){
waitingModal.hidePleaseWait();
}, 1000);
}
}).then(function successCallback(response) {
if (response.data.success==true){
licenseTable.ajax.reload();
$('#updateLicenseModal').modal("hide");
notifyMessage(response.data.result, 'success');
} else {
notifyMessage(response.data.result, 'error');
}
}, function errorCallback(response) {
window.location.href = "/ATS/500";
});
I would like to show 500 page if an error occurred during http request (for example server down or wrong url), but errorCallback is never called.
Is there an error in my code? where is my fault?Thanks
This is an example of response that I can't handle in error code:
{
"status":422,
"exception":"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
"message":"Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"tr71\"",
"stacktrace":"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"tr71\"
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:115)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:78)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
......"
}
Web service example
#Override
#RequestMapping(value = { "/license"}, method = RequestMethod.POST)
public #ResponseBody Response createLicense(#RequestBody ClientLicenseForm clientLicenseForm) {
try{
administrationService.createLicense(clientLicenseForm);
return new Response(true, true, "Your license has been created!", null);
}catch(Exception e){
ErrorResponse errorResponse= ErrorResponseBuilder.buildErrorResponse(e);
LOG.error("Threw exception in AdministrationControllerImpl::createLicense :" + errorResponse.getStacktrace());
return new Response(false,false,"Error! Your license hasn't been created!",errorResponse);
}
}
This may be the problem(it wrap json response inside another object), but how can I fix it?
UPDATE
I have fixed with this code, I'll test it
}).then(function successCallback(response) {
if (typeof response.data.success == 'undefined'){
window.location.href = "/ATS/500";
}else if (response.data.success==true){
licenseTable.ajax.reload();
$('#updateLicenseModal').modal("hide");
notifyMessage(response.data.result, 'success');
} else if(response.data.success==false) {
notifyMessage(response.data.result, 'error');
}
}, function errorCallback(response) {
window.location.href = "/ATS/500";
});
Redarding you comments you get a json response (i think with 200 header)
The error callback will not fire while in the header response was 200 code.
You can manage it in two ways:
Rewrite backend side to return proper status header code
Check if response valid in successCallback
if (response.data.exception) {
window.location.href = "/ATS/500";
}
NOTE: but basically it's wrong that server return this type or error with stacktrace.
Exceptions handling examples
I'm getting status as 200 but it's printing message present inside error message alert("error...");. Why so?
function makeSelect() {
var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value;
var url = "http://dukano.co/sakhidev/retailon/productoption/values";
alert(url);
var jsondata = $j('#customoption').serialize();
alert("jsondata: " + JSON.stringify(jsondata));
$j.ajax({
type : 'POST',
url : url,
data : jsondata,
dataType : 'json',
success : function(response) {
console.log("calling");
console.log(response);
alert("call success");
alert("response data:" + JSON.stringify(response));
if (response.status == 200) {
console.log("yes");
} else if (response.status == "error") {
console.log("no");
}
},
error : function(response) {
alert("error...");
alert("response:" + JSON.stringify(response));
console.log(response);
}
});
}
Magento's controller function returning json value
public function valuesAction(){
$blouseoption = $this->getRequest()->getParam('blouseoption');
$sareefinishing = $this->getRequest()->getParam('sareefinishing');
$data = array( 'sfinishing' => $sareefinishing, 'layout' => $this->getLayout());
Mage::dispatchEvent('product_custom_option', $data);
$jsonData = json_encode(array($blouseoption, $sareefinishing));
$this->getResponse()->clearHeaders()
->setHeader('Content-type','application/json',true);
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($jsonData));
$this->getResponse()->sendResponse();
}
As you are using
dataType: "json"
this evaluates the response as JSON and returns a JavaScript object.any malformed JSON is rejected and a parse error is thrown.
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".
Make sure that the server returns valid JSON. empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.
try to check the textStatus in the error.
error : function(jqXHR,textStatus,errorThrown)
{console.log(textStatus)}
if this prints "parsererror" then of course you have problem with your returning json. please check that.
More Info
Alternative answer
Instead of returning status 200 with empty response, you can return status 204 and not return any response. Status 204 is for No Content. JQuery should not throw any error in this case.
Tried all jquery methods and js to check for file exist but all doesn't work all give me that any file that exist or doesn't on my server / with my domain that it does exist although some dont... idk why it say that all does although they dont?!!! maybe something wrong with my server? idk :( i need help tried all of that
$.get('http://MyUrl/file.wav')
.done(function() {
alert('exists');
}).fail(function() {
alert('does not exist');
})
&
$.ajax({
url: 'http://MyUrl/file.wav', //or your url
type: 'GET',
success: function(data){
alert('exists');
},
error: function(data){
alert('does not exist');
},
})
&
function doesFileExist(urlToFile)
{
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://MyUrl/file.wav', false);
xhr.send();
if (xhr.status == "404") {
//return false;
console.log('not exist');
} else {
//return true;
console.log('file with that name exists exists');
}}
&
$.ajax({
url:'http://MyUrl/file.wav',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
console.log('file with that name exists exists');
}
});
idk what else i do really but it frustrate me that it always give me exists or true no matter file exists or not.....
I guess you are using rewrite rules on your server? If yes, most likely your server is rewriting your requests for non-existing files and you are getting response from some script which handles requests. Did you check response from your server? For example, open developer tools in chrome browser and then open the url of non-existing file in chrome, what do you see in network tab of developer tools? If you are always getting 200 http response, you will need to change your rewrite conditions or modify your script to check for file existence and send back 404 if file does not exist.
$.get("/path/to/file/")
.always(function(data, textStatus, errorThrown) {
// if file does not exist, or `error` , log `textStatus`, `errorThrown`
if (textStatus !== "success") console.log(textStatus, errorThrown);
// else, log response `data`
else console.log(data);
});
Create a new route for ajax
Server side:
echo json_encode(new Array(exists => file_exists(filePath + $_POST['filename]));
Client side:
$.ajax({
url:'http://MyUrl/fileexists.php', // new route
type:'POST', // post data
data: { filename: 'new.wav' }, // data to post
dataType: 'json', // returned data type
error: function()
{
//file not exists
},
success: function(resp) {
//file exists?
console.log('file with that name exists exists?' + resp.exists);
}
});
This is a very small application for a prototype/experiment. A device is going into sleep every so often to save battery life and a user will access a local webpage and press a button to change something with the device--this sends a POST to the device using the javascript code below.
Since the device can be sleeping when the user presses a button it will miss the POST. I know this is bad practice but I basically need the webpage to keep POST-ing (don't even know if I'm using the terminology correctly) or sending data until it receives the response. I tried a while loop but it only sent it once, maybe I put it in the wrong place.
function execPOST(url, postData, callback) {
var postRequest = newAjaxRequest();
postRequest.onreadystatechange = function() {
if (postRequest.readyState == 4) {
if (postRequest.error) {
callback(1, "Request had an error.");
alert('postRequest Error');
} else {
var status;
try {
status = postRequest.status;
} catch (err) {
callback(1, "Failed to get HTTP status from server.");
return;
}
if (status == 200 || status == 0) {
callback(0, postRequest.responseText);
} else {
callback(1, "POST: Unexpected HTTP Status: "
+ postRequest.status);
alert('POST: Unexpected HTTP Status: '
+ postRequest.status);
}
}
}
}
if (postRequest.overrideMimeType){
postRequest.overrideMimeType("text/xml");
}
postRequest.open("POST", url, false);
//I tried adding this while loop hoping it would keep sending but it only sent once
while (postRequest.readystate != 4)
{
setTimeout('',2000);
postRequest.send(postData);
}
return postRequest;
}
I suggest looking at socket.io to "ping" the device in a loop until it wakes up, THEN send the POST request.
have you considered to use jquery?
function ping () {
$.ajax (
<url>
, {
error: function ( jqXHR, textStatus, errorThrown ) {
}
, timeout: 5000 // in ms
, type: 'POST'
}
}).done(function ( data, textStatus, jqxhr ) {
// whatever
}).fail(function ( jqxhr, textStatus, data ) {
// note that the order of arguments is different from that of the success handler ('done') !
if (textStatus === 'timeout') {
ping();
}
else {
// ... more error handling
}
});
for more info, consult the docs.
Below is an existing jquery code in our code base.
$("#download_").click( function() {
$("#error").html('');
$.ajax({
type : "GET",
cache : false,
async : false,
url : "/download",
success : function(data) {
var json_obj = $.parseJSON(data);
if(json_obj !== undefined && json_obj != null){
if(json_obj.download=="success"){
location=json_obj.url;
}
}
},
error : function(data) {
// TODO
$("#error").html(failed);
}
});
});
Here, In case of error (marked as TODO), I want to check if the http status is 404, then I need to redirect user to different url.
Can any one tell me how do I get the http status in this error: function(data) method?
Thanks!
Did you even look at the docs?
$.ajax({
...
statusCode: {
404: function() {
alert('page not found');
}
}
});
try: statusCode
from documentation:
$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
http://api.jquery.com/jQuery.ajax/
EDIT:
Now that I think about it, do you only want to redirect if it's a 404? What about other error codes?