Test object has a value in it or not in javascript - javascript

I have one class in javascript :
function Quotation(){
if(typeof Quotation.instance === 'object'){
return Quotation.instance;
}
Quotation.instance = this;
var self = this;
this.getQuotation = function(customerID,numRow){
var result = "";
var urlDefault = "mysite.com/getDefaultQuote" + "?id="+ customerID +"&count=" + numRow;
var url = "mysite.com/getQuote" + "?id="+ customerID +"&count=" + numRow;
$.ajax({
url:url,
type:type,
dataType:datatype,
contentType: contenttype,
data : JSON.stringify(data),
success:function(res){
result = res;
},
error:function(res){
result="";
},
async : false
});
return result;
};
}
This is where my view call Quotation object :
var quotation = new Quotation();
var HomeView = Backbone.View.extend({
initialize: function() {
},
render: function(){
console.log(quotation.getQuotation(10,12));
}
});
I want to test in getQuotation :
if quotation.getQuotation(10,12) has value in it, then getQuotation will take url = "mysite.com/getQuote" as an ajax request URL.
Otherwise if quotation.getQuotation(10,12) no record, then getQuotation will take urlDefault = "mysite.com/getDefaultQuote";.
Here the result in the console :
Any help is much appreciated.

You should check res inside the success callback and perform an extra AJAX request to load the default quote when res is null.
I would probably implement this logic server-side so that you always perform a single request.

Related

using javascript to load json data from google maps

So, this is the code I have, console.log gives me the right value, but the function doesn't return the value, even if the return is inside the timeout. I must be doing something wrong.
function countyfinder(address){
var rr =$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + address.replace(" ", "%20")).done(function(data) {
var county = data.results[0].address_components[3].short_name;
//return county;//data is the JSON string
});return rr;};
function calculatetax(address, price){
var j = countyfinder(address);
setTimeout(function(){var k = j["responseJSON"]['results'][0]['address_components'][3]['short_name'];
console.log(k);//return k won't work in here either
}, 1000); return k
};
this is what I ended up with:
var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
function getCounty(address) {
var country;
var baseApiUrl = "https://maps.googleapis.com/maps/api/geocode/json";
var query = "?address=" + encodeURIComponent(address);
var queryUrl = baseApiUrl + query;
$.ajax({
url: queryUrl,
async: false,
dataType: 'json',
success: function(data) {
county = gmapsExtractByType(data, "administrative_area_level_2 political");
}
});
return countr.long_name;
}
function gmapsExtractByType(json, type) {
return json.results[0].address_components.filter(function(element) {
return element.types.join(" ") === type;
})[0];
}
console.log( getCounty("100 wacko lane ohio") );
I had to use a synchronous request by changing some settings in the ajax request. The drawback of this is that the browser will be locked up until you get a request response, which can be bad on a slow connection or a connection with an unreliable server. With google, most of the time, I don't think that will happen.

AJAX call within Javascript class (prototype function)

I am implementing a Javascript class which I am having trouble getting to work.
After I initialize an instance of the class, I then call a method of that class which makes an AJAX request. The data that is returned on 'success' of the AJAX function is then needed to be set to the a property of that instance. When I output the this.results variable later in my code, it is empty when it shouldn't be. Here is my code:
//Individual Member Class
function GetReports(options) {
this.options = options;
this.results = {};
}
GetReports.prototype.getResults = function() {
jQuery.ajax({
type : 'post',
dataType : 'json',
url : 'reporting/getStaffMemberReports',
async : false,
data : options,
success : function(data) {
this.results = data;
setResult(this.results);
}
});
}
GetReports.prototype.returnResults = function(type) {
if(type === "JSON") {
JSON.stringify(this.results);
} else if (type === "serialize") {
this.results.serialize();
}
return this.results;
};
GetReports.prototype.setResult = function(data) {
this.results = data;
};
And my code which creates an instance of the 'class':
var jsonString = <?php echo json_encode($JSONallocatedStaffMembers); ?>;
options = {
all : true,
members : JSON.parse(jsonString),
type : 'highperform'
};
var all = new GetReports(options);
all.getResults();
var results = all.returnResults("JSON");
console.log(results);
Now, as the AJAX call is asynchronous, I was thinking this may be the issue? I have tried putting 'async : false,' in but that doesn't help.
Can anyone see where I am going wrong?
There is one thing to be fixed here.
The this
inside ajax callback refers to ajax object, and not your
GetReport instance. You have to declare a var on getResults and point
it to this before make the ajax.
GetReports.prototype.getResults = function() {
var self = this;
jQuery.ajax({
type : 'post',
dataType : 'json',
url : 'reporting/getStaffMemberReports',
async : false,
data : options,
success : function(data) {
self.results = data;
setResult(self.results);
};
});
}

Class method in javascript is not a function

The answer must be obvious but I don't see it
here is my javascript class :
var Authentification = function() {
this.jeton = "",
this.componentAvailable = false,
Authentification.ACCESS_MASTER = "http://localhost:1923",
isComponentAvailable = function() {
var alea = 100000*(Math.random());
$.ajax({
url: Authentification.ACCESS_MASTER + "/testcomposant?" + alea,
type: "POST",
success: function(data) {
echo(data);
},
error: function(message, status, errorThrown) {
alert(status);
alert(errorThrown);
}
});
return true;
};
};
then I instanciate
var auth = new Authentification();
alert(Authentification.ACCESS_MASTER);
alert(auth.componentAvailable);
alert(auth.isComponentAvailable());
I can reach everything but the last method, it says in firebug :
auth.isComponentAvailable is not a function
.. but it is..
isComponentAvailable isn't attached to (ie is not a property of) your object, it is just enclosed by your function; which makes it private.
You could prefix it with this to make it pulbic
this.isComponentAvailable = function() {
isComponentAvailable is actually attached to the window object.
isComponentAvailable is a private function. You need to make it public by adding it to this like so:
var Authentification = function() {
this.jeton = "",
this.componentAvailable = false,
Authentification.ACCESS_MASTER = "http://localhost:1923";
this.isComponentAvailable = function() {
...
};
};
Another way to look at it is:
var Authentification = function() {
// class data
// ...
};
Authentification.prototype = { // json object containing methods
isComponentAvailable: function(){
// returns a value
}
};
var auth = new Authentification();
alert(auth.isComponentAvailable());

Javascript variable scope hindering me

I cant seem to get this for the life of me. I cant access the variable "json" after I calll the getJson2 function. I get my json dynamically through a php script, and that works. But then its gone. there is a sample that I use as a guide at The InfoVis examples where the json is embedded in the init function. i am trying to get it there dynamically.
<script language="javascript" type="text/javascript">
var labelType, useGradients, nativeTextSupport,animate,json;
function getJson2()
{
var cd = getParameterByName("code");
$.get("tasks.php?code="+cd, function(data){
return data;
})
};
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
(function() {
var ua = navigator.userAgent,
iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
typeOfCanvas = typeof HTMLCanvasElement,
nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
textSupport = nativeCanvasSupport
&& (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
//I'm setting this based on the fact that ExCanvas provides text support for IE
//and that as of today iPhone/iPad current text support is lame
labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
nativeTextSupport = labelType == 'Native';
useGradients = nativeCanvasSupport;
animate = !(iStuff || !nativeCanvasSupport);
})();
debugger;
var Log = {
elem: false,
write: function(text){
if (!this.elem)
this.elem = document.getElementById('log');
this.elem.innerHTML = text;
debugger;
this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
}
};
function init(){
json = getJson2();
//init data
var st = new $jit.ST({
//id of viz container element
injectInto: 'infovis',
//set duration for the animation
duration: 800,
//set animation transition type ..................
function getJson2()
{
var cd = getParameterByName("code");
$.get("tasks.php?code="+cd, function(data){
return data;
})
};
getJson2() doesn't return anything. The callback function to $.get() returns something, but nothing is listening for that return.
It sounds like you want synchronous loading instead. $.get() is just shorthand for this $.ajax() call: (See docs)
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
And $.ajax() supports more features, like setting async to false.
$.ajax({
url: "tasks.php?code="+cd,
async: false,
dataType: 'json',
success: function(data) {
// data !
}
});
Which means, getJson2 then becomes:
function getJson2()
{
var cd = getParameterByName("code");
var jsonData;
$.ajax({
url: "tasks.php?code="+cd,
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
return jsonData;
};
var myJsonData = getJson2();
Or still use $.get async style, and use callbacks instead.
function getJson2(callback)
{
var cd = getParameterByName("code");
$.get("tasks.php?code="+cd, function(data){
callback(data);
});
};
getJson2(function(data) {
// do stuff now that json data is loaded and ready
});
The $.get call is asynchronous. By the time you call return data;, the function has already long since returned. Create a variable outside of your function's scope, then in the $.get callback handler, assign data to that variable.
var json;
function getJson2(){
// ...
$.get(...., function(response){
json = response;
}
});
Alternatively, you could do a sychronous Ajax call, in which case returning your data would work (but of course would block script execution until the response was recieved). To accomplish this, see the asynch argument to jQuerys $.ajax function.
A jQuery $.get call is asynchronous and actually returns a promise, not the data itself.
An elegant way to deal with this is to use the then() method:
$.get(...).then(function(data){...});
Alternately, change your ajax settings to make the call synchronous.
$.get("tasks.php?code="+cd, function(data){
return data;
})
$.get is asynchroneous. So your value is never returned. You would have to create a callback.
The same question appears here:
Return $.get data in a function using jQuery

How to replace function params?

I'm using the following code to make ajax call where the form data is passed as params.
//ajax call
function restServiceCall(origin,destination,tripType,dateDepart,dateReturn){
dataString = 'origin='+ origin + '&destination=' + destination + '&tripType='+tripType;
$.jsonp({
"url": flightURL,
callbackParameter:jsonpCallBack,
data: dataString,
beforeSend:function(){$('#loadingdiv').show()},
"success": function(data) {
if(data.error != null){
$('#errtitle').html('<h2 class="pgtitle">Error !! '+data.error+'</h2>').show();
$("#displaydiv,loadingdiv").hide();
}else{
renderData (data,dateDepart,dateReturn);
}
},
"error": function(xOptions, textStatus) {
$('#errtitle').html('<h2 class="pgtitle">Sorry the service you are looking for is currently unavailable</h2>').show();
$("#displaydiv,loadingdiv").hide();
}
});
}
Besides making the call from form I also use it in the following function wherein I just need to pass either the dateDepart/dateReturn as params.
//for pagination
$('.pagenation a').bind('click',function(){
var numDays = 7;
var self = $(this);
var dateTemp = self.parents(':eq(1)').attr('id')=="onewaytripdiv"? parseDate(dateDepart):parseDate(dateReturn);
if(self.hasClass('left')){
var tempDepDate = removeNumOfDays(dateTemp,numDays);
}else{
var tempDepDate = addNumOfDays(dateTemp,numDays);
}
var changedDate = tempDepDate.getDate()+' '+cx.monthNamesShort[tempDepDate.getMonth()]+' '+tempDepDate.getFullYear();
if(self.parents(':eq(1)').attr('id')=="onewaytripdiv"){
dateDepart = changedDate;
}else{
dateReturn = changedDate;
}
restServiceCall(origin,destination,tripType,dateDepart,dateReturn);
});
I would like to remove the params in the function call, as the params may vary. Please suggest an alternative to pass the params.
How about passing an array of parameters instead? And then pass another value, such as an integer to indicate to the function what to expect in it's parameter array.
e.g
restServiceCall(myParams, 0);

Categories

Resources