I am busy writing a web page for a company. I need to accomplish the following: If the output is nothing, alert "Rookswitch is turned off"
. If the output is "Hookswitch-Playlist"
, alert "Rookswitch is turned on"
. The data is grabbed from a REST API.
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://192.168.0.15:8080/Cnario/REST/GetDevice?deviceName=Rook-Switch",
dataType: "json",
processdata: true,
success: function(response) {
alert("De Rookswitch staat al aan");
if (response.GetDeviceResult.DevicePins.PinValue == 'Playlist-Roken')
handleSuccess(response);
else
handleError(response);
},
error: function(message) {
alert("Rookswitch is uit");
}
});
});
For some reason, the message is always on. even if it is off. How can i fix this?
In your success function, you're doing an alert for "switched on" in all cases. No matter whether the response is blank, or contains a value.
You've put the alert for "It's switched off" in the error function. This function will only be called if the AJAX request actually fails (i.e. there is a HTTP error).
I think what you probably want to do is put an if/else block in your success function to check the value of the appropriate field in the response object to see if it contains the string "Hookswitch-Playlist" or not.
If you are able to control the http://192.168.0.15:8080/Cnario/REST/GetDevice?deviceName=Rook-Switch response, I strongly recommend to use sth like
/* --------------------------------------- */
/* Response will be generated according to which
/* prog lang you are using but as a result we should have sth like this
/* --------------------------------------- */
var response = {
code: 200, // on
message: 'Rookswitch is turned on'
}
/* OR */
var response = {
code: 300, // off
message: 'Rookswitch is turned off'
}
/* --------------------------------------- */
/* Response
/* --------------------------------------- */
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://192.168.0.15:8080/Cnario/REST/GetDevice?deviceName=Rook-Switch",
dataType: "json",
processdata: true,
success: function(response) {
alert(response.message);
/* --------------------------------------- */
/* doing sth according to server response
/* --------------------------------------- */
if(response.code == 200){
/* On function goes here */
}else if(response.code == 300){
/* Off function goes here */
}
},
error: function(message) {
alert("Rookswitch is uit");
}
});
});