String comparison in javascript fails - javascript

Hi i have a problem when comparing two strings. the problem is that when i compare the equality of status variable with "success" string literal it returns False, However when I check the value of the success via alert or console.log I get "success".
when I use status.valueOf() == "success" I get an error which says Can not call method 'valueOf' of undefined but when checking
// this is a callback function used in jQuery.post(url, data, callback)
this.callback = function(data, status, jqXHR) {
alert(status); // shows that status is equal to "success"
console.log("STATUS: " + status);
console.log("STATUS CONSTRUCTOR: " + status.constructor);
console.log("STATUS TYPE: " + (typeof status));
if(status.valueOf() === "success") {
var data = JSON.parse(data);
if(data.errors) {
this.success(data.message);
} else {
this.failure(data.message, data.errors);
}
} else {
alert("WTF");
}
};
UPDATE 2:
This is what i get after logging some attributes of the status:
>>>console.log("STATUS: " + status);
STATUS: success add_poll.js:34
>>>console.log("STATUS CONSTRUCTOR: " + status.constructor);
STATUS CONSTRUCTOR: function String() { [native code] } add_poll.js:35
>>>console.log("STATUS TYPE: " + (typeof status));
STATUS TYPE: string add_poll.js:36
STATUS: undefined add_poll.js:34
Uncaught TypeError: Cannot read property 'constructor' of undefined add_poll.js:35
(callback add_poll.js:35)
(callback add_poll.js:41)
(fire jquery.js:1037)

Can not call method 'valueOf' of undefined
The error message says, valueOf is called on undefined. It means that the status is undefined. So, you might want to drop the valueOf and simply do
if (status === "success") {

A better way of checking might be,
if(status.toLowerCase() === "success")

First check what you server code is returning, if it is ok, try this
if (status === "success")
or you can do this
if (data=== "success")

The method you are using for jQuery ajax is almost deprecated.
As already mentioned in comment, there is no need of using valueOf method with status
So, this should do
$.ajax({
url: 'url2ajax.php',
dataType: 'datatype returned by the url ajaxed maybe json',
data: {//list of key-value pairs to be send },
success: function( oData ) {
//call back to perform on a successful ajax.
//Data returned from ajaxed url available as argument, oData
},
error: function( ojQXhr, strStat, strErr ) {
//callback to perform on a failed ajax request
//jQuery XHR object, status string and error message available as argument
}
});
Refer to jQuery.ajax for details

I finally found the problem. The problem is that I defined the callback function as a property of an object this.callback = function(){...}; I changed it and defined a normal javascript function and it worked. Actually I don't know why? Anyone knows why I can't use an object method as a callback function for $.post(url, data, callback)?

Related

How to detect a response which does not have an object

Complete newbie question :
When I query to database using API, I sometimes get a response which contains no objects.
With the code below no alerts are raised at all.
I need a method to detect this type of empty response - jQuery.isEmptyObject does not work.
$.get("http://api.lmiforall.org.uk/api/v1/ashe/estimatePay",
{ soc: soc, coarse: "false", filters:"region:12"},
function(datani) {
alert(datani);
if(jQuery.isEmptyObject(datani)) {
alert("empty");
}
use done event to identify.
<script>
$.get( "test.php", { name: "John", time: "2pm" } )
.done(function( data ) {
alert( "Data Loaded: " + data );
});
</script>
It sounds like you are confusing no response as being an empty object.
Something like:
var myObj = {};
would be considered an empty object that isEmptyObject() would return true for but an empty string (no response) would not
Try changing:
if(jQuery.isEmptyObject(datani)) {
To
if(!datani) {
With the code above no alert box appears at all.
The first alert() should be called; whether response is object or not.
You can add error handling to ajax request using .fail() to alert textStatus, errorThrown or property of jqxhr object.
Note, also js at Question is missing closing }) at $.get() .
$.get("http://api.lmiforall.org.uk/api/v1/ashe/estimatePay",
{ soc: soc, coarse: "false", filters:"region:12"},
function(datani) {
alert(datani);
}).fail(function(jqxhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown)
})

jQuery how to read this JSON string from responseText

I have tried almost everyway here on stack overflow, but somehow I cannot read JSON string data returned from a success function call in jquery ajax. my success function receives following JSON string:
Object {
readyState = 4, responseText = "{"
Response ":200,"
Data ":"
6 ","
Message ":"
6 "}", status = 200, statusText: "OK"
}
This is my success callback:
success: function(response, msg, responseText) {
if (response.Response == 200) {
console.log("Data was submitted");
var obj = responseText;
console.log(typeof obj);
} else if (response.Response == 400) {
console.log("there was some error");
}
}
When success function is fired and checks for status code, it executes console.log("Data was submitted"); statement successfully, however, I am not able to access the "Data":"6" key/value pair.
So far I have tried doing this:
var obj = responseText;
console.log(obj.Data);
and
console.log(obj.data[1]);
and numerous other ways, but either it says "undefined" or gives and error. However, when I console.log(obj), in console it shows 'obj'. which means I am getting a JSON object.
Please note that I have also tried:
obj = jQuery.parseJSON(responseText);
which gives me an error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
What to do in this situation? I want to be able to extract the value of a key name "Data": and and assign its value ="6" to a variable.
The first parameter of the success callback is what you need, not the third. The first parameter will represent the body of the response as returned from the server. Also you don't need to be checking for anything different than 200 status code in a success callback. That's what the error callback is designed for because the success callback will never be fired if your server returns 400 status code.
So:
dataType: 'json',
success: function (response) {
console.log("Data was submitted");
console.log(response.Data);
},
error: function() {
console.log("there was some error");
}
The success callback is success: function(data, textStatus, jqXHR )
So the 1st, data will contain the data returned to the success function.

Uncaught TypeError: Cannot read property 'results' of undefined

I'm a complete newby to JS. Trying to use SharePoint REST API to display a link list in a footer. Keep getting this error no matter what I do. It is for this line LoadFooterLinks(results.d.results);
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/lists/getbytitle('Footer Links')/items/?$orderby=Display_x0020_on_x0020_Homepage";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (results) {
LoadFooterLinks(results.d.results);
},
error: function (error) {
console.log("Error in getting List: " + listName);
}
});
}
A few things:
How do you know you have an "error"?
Is is a Javascript Exception?
WHAT IS the error or Exception?
How do you know the error isn't with your LoadFooterLinks() function?
Most likely your results are NOT what you are expecting. You're obviously:
Successfully making a connection and request
But, you can't be sure what's coming back. It could be:
empty string
null
malformed
Hitting F12 in most browsers will bring up that browser's Developer mode/built-in JS console
My code changes below should help you debug by outputting to the console for you.
Things to NOTE about the code changes:
The difference between:
catching a JavaScript runtime exception/error using try-catch vs.
outputting the string variable arbitrarily named "error" in the failure callback method of the $.ajax object
Print an exception to to the console doesn't require console.err()
If you want to show a string as an error in the console use console.err(), not console.log.
Null is an object, not a datatype or primitive like the other ones in JavaScript. For Example,
boolean
string
undefined
number
New Code
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl +
"/_api/lists/getbytitle('Footer Links')/items/?
$orderby=Display_x0020_on_x0020_Homepage"
;
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (results) {
if (!results) { // should handle null and empty strings
try{
LoadFooterLinks(results.d.results);
}
catch (e){ // catch any JavaScript runtime exception (error)
console.log(e); // print the error to the console
// (hit F12 in most browsers to see
// the console BEFORE you refresh
// the page to run your code)
}
}
else {
var msg = "The 'results' variable is ";
var varType = typeof(results);
if (varType == "object") {
msg += "NULL";
}
else {
msg += varType;
}
}
},
error: function (error) {
// this 'error' variable can be named
// anything you'd like and is a string
// description of the AJAX error.
// This description comes from $.ajax -
// which is part of jQuery (a JS library).
// This "error" is not a native JS
// exception; therefore, you wouldn't
// use a TRY-CATCH. Also, since it's
// only a string, if you want to show it
// as an error in the console, you should
// use `console.err`, not `console.log`.
console.err("Error in getting List: (0)", error);
}
});
}
What you are basically doing is making a request to the "/_api/lists/getbytitle" method.
When that method returns a response, it will do so as an object named "results", as you can see under the "success" callback.
What you are doing afterwards is reading a property called "d" and within "d" you are trying to obtain the value of property called "results".
What the error is saying is that "d" is undefined therefore it cannot retrieve the value of "results" from "d".
I suggest you check what is inside the object "results" of the success callback.
For SharePoint API result, you would need to parse the JSON response to convert it to Javascript object. I've modified your code a bit to make it work in this case.
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/lists/getbytitle('Footer Links')/items/?$orderby=Display_x0020_on_x0020_Homepage";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (response) {
var svcData = JSON.parse(response.data).d.results;
LoadFooterLinks(svcData);
},
error: function (error) {
console.log("Error in getting List: " + listName);
}
});
}

JSON or Jquery error: Uncaught TypeError: Cannot read property 'error' of null

I am trying to make an ajax call using the below jQuery.
But I can see in Chrome, i'm getting uncaught typeerror cannot read property 'error' of null. So this stops the preloader from going away. Any idea why it's doing this?
function appendTeam(){
$.ajax({
url : _path + "/core/ajax.php",
type : 'POST',
data : { f: 'getTeam'},
dataType : 'json',
success : function(data) {
if(data.error){
errorMessage('Error: ' + data.error, data.error, data.error);
return false;
}else{
var count = 0;
$.each(data.team, function(i, c){
// check
if(!$('#'+c)) return true;
var element = $('#'+c);
$('input[name="s'+i+'"]').val(element.attr('id'));
$('.slot.'+(i+1)+'.ui-droppable').append(element);
element.data('prevParent', $('.slot.'+(i+1)+'.ui-droppable'));
count ++;
});
appendStatus(count);
setTimeout(function(){
$('#preloader').fadeOut('fast',function(){
$('#preloader').remove();
popUp('match');
});
}, 2000);
}
}
});
}
There is a mistake in your if operator:
if(data.error)...
You should check it like if(data && data.error)... so if the server returned you null instead of JSON object you won't try to access object's property error.
Also maybe you need to handle this case separately:
if(!data) {
// handle empty response
} else if(data.error) {
// handle error
} else {
// process results
}
Test if data is not null before trying acces his error property
Probably the data object does not contains the property error or it is null;
so instead of this
if(data.error) {
you can check for it in a different way :
if(data && data.hasOwnProperty('error')) {
which is more fail-safe.
i think response is null try to see response in using firebug

Issues with handling http errors with jQuery AJAX webservice calls

I'm developing an jQuery application in where I've a requirement to capture HTTP errors as and when it occurs. Below is my snippet.
// Function to validate URL
function validateURL(url)
{
var pattern = new RegExp();
pattern.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
if (!pattern.test(url))
{
return false;
}
return true;
}
// Generic error handler for handling the webservice requests.
function initWebService(wstype, wsurl,jsonData)
{
// If the method parameter is not either "GET" or "POST" display an error message to the developer.
var msgValidateArgument;
var wsCallStatus;
var callbackData;
if ((arguments[0] != 'GET') && (arguments[0] != 'POST'))
{
//alert("Invalid");
//alert("You must provide a valid http method in your webservice call.");
msgValidateArgument = "You must provide a valid http method in your webservice call.";
return msgValidateArgument;
}
// Making sure whether the developer is passing the required number of parameters.
if(arguments.length < 3)
{
//alert("Some required arguments seems to be missing. Please check your webservice invocation.");
msgValidateArgument = "Some required arguments seems to be missing. Please check your webservice invocation.";
return msgValidateArgument;
}
if (!validateURL(arguments[1]))
{
msgValidateArgument = "You must provide a valid URL in your webservice call.";
return msgValidateArgument;
}
if(arguments[2] != ''){
var response=jQuery.parseJSON(arguments[2]);
if(typeof response =='object'){
//It is JSON
alert(response.toSource());
}
else{
msgValidateArgument = "The JSON data being passed is not in valid JSON format.";
return msgValidateArgument;
}
}
// Making the AJAX call with the parameters being passed. The error handler handles some of the possble http error codes as of now.
$.ajax({
type: arguments[0],
url: arguments[1],
data: arguments[2],
dataType: 'json',
async:false,
statusCode:{
404: function(){
alert('Page not found');
},
500: function(){
alert('Page not found');
},
504: function(){
alert('Unknown host');
}
},
success: function(data){
//alert('Data being returned from server: ' +data.toSource());
//alert('Data being returned from server: ' +data.toSource());
//alert(data);
callbackData = data;
}
});
return callbackData;
}
But, when I programatically change the webservice url to hold a wrong value, and upon calling the html page, I'm able to see an error message in the firebug console, but my snippet doesn't seem to be catching the error at all.
For e.g, While calling the GEONames API, I'm encountering an stating "407 Authorization required" in firebug's console.but even if I handle that status code in my error block, it is not firing.. What could be the reason?.
Don't we have any comprehensive solution for handling these HTTP errors effectively?.
I think there are a few problems with your code ... firstly how is handleError called ? because you call a method called handleError but pass nothing ... im assuming your using .ajax()
You should do it like this :
$.ajax({
statusCode: {
404: function() {
alert('page not found');
},
500: function() {
alert('server error');
}
},
success : {
alert('it working');
},
complete : {
alert('im complete');
});

Categories