how to access json data globaly - javascript

In code below I am trying to retrieve clients machine IP. The problem is in TestIP variable this one shows null when I debug script. How I could assign this value to show clear string with IP after exiting from $.getJSON() function.
<script>
var test1 = null;
$(document).ready(function () {
var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
//getting IP correctly
test1 = data.host;
$('#' + '<%=hdnDeliServerGIP.ClientID%>').val(data.host);
})
if (inDesignMode != "1") {
//should show IP - is Null
var TestIP = test1;
//Not getting the value from hidden asp object
var GIP = $('#' + '<%=hiddenElementIP.ClientID%>').val() != '' ? $('#' + '<%=hdnDeliServerGIP.ClientID%>').val() : 'not set';
}
});
Thanks in advance

The problem is that getJSON is an asynchronous call, so your subsequent if block is actually called before getJSON returns. You should move the if block inside the getJSON callback:
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
//getting IP correctly
test1 = data.host;
$('#' + '<%=hdnDeliServerGIP.ClientID%>').val(data.host);
if (inDesignMode != "1") {
//should show IP
var TestIP = test1;
//Getting value from hidden asp object
var GIP = $('#' + '<%=hiddenElementIP.ClientID%>').val() != '' ? $('#' + '<%=hdnDeliServerGIP.ClientID%>').val() : 'not set';
}
})

Use your code in the getJSON callback like,
var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
//getting IP correctly
test1 = data.host;
$('#' + '<%=hdnDeliServerGIP.ClientID%>').val(data.host);
// use you code here in callback function
if (inDesignMode != "1") {
//should show IP
var TestIP = test1;
//Getting value from hidden asp object
var GIP = $('#' + '<%=hiddenElementIP.ClientID%>').val() != '' ? $('#' + '<%=hdnDeliServerGIP.ClientID%>').val() : 'not set';
}
})

Put the if statement inside the $.getJSON call at the end of the lines you currently have in it. The problem is that $.getJSON is asynchronous and so its not necessarily done by the time you are trying to access test1
So what you want is:
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
//getting IP correctly
test1 = data.host;
$('#' + '<%=hdnDeliServerGIP.ClientID%>').val(data.host);
if (inDesignMode != "1") {
//should show IP - is Null
var TestIP = test1;
//Not getting the value from hidden asp object
var GIP = $('#' + '<%=hiddenElementIP.ClientID%>').val() != '' ? $('#' + '<%=hdnDeliServerGIP.ClientID%>').val() : 'not set';
}
})

In order to make a global variable in javascript, we need to declare variable without using "var" keyword.
try using "test1 = null;"

in order to make a js variable globally you need to first declare a variable and then assign you json data onto that, and then you can access that variable globally.
eg:
$(document).ready(function () {
var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
$.ajax({
url :'http://smart-ip.net/geoip-json?callback=?',
async:false,
dataType:"json",
success: function (data) {
//getting IP correctly
test = data.host;
}});
if (inDesignMode != "1") {
//should show IP - is Null
var TestIP = test1;
//Not getting the value from hidden asp object
var GIP = $('#' + '<%=hiddenElementIP.ClientID%>').val() != '' ? $('#' + '<%=hdnDeliServerGIP.ClientID%>').val() : 'not set';
}
});
Note:- Please define test variable once outside this call in the begining of page
hope this will help you :)

Related

Parsing variable into .get() function

:-)
I cannot get this to work!
The variable "textpageId" won't work inside the .get() function?
How do i parse an id in to the function then??
var textpageId = $(this).attr("textPageID");
if (isOpen != true) {
console.log("Clicked");
$.get("#Url.Action("Index", "Upload", new { textId = textpageId })", function (data) {
console.log(data);
You have to concatenate the variable inside url using plus ( + ) signs, see below code -
NOTE - are Index and Upload variables? If yes, then concatenate them in same way as did for textpageId.
var textpageId = $(this).attr("textPageID");
if (isOpen != true) {
console.log("Clicked");
$.get("#Url.Action("Index", "Upload", new { textId = " + textpageId + "})", function (data) {
console.log(data);

Create Cookie in Controller, read cookie from Javascript

using MVC.
In one of my controllers I am creating a cookie like the following:
Function Login(ByVal access_token As String) As ActionResult
Response.Cookies.Add(New HttpCookie("access_token", access_token))
End Function
I want to check the value of the cookie called "access_token" client-side, in order to know the next step to take in javascript.
How can I do that?
Any help would be appreciated
UPDATE
I found the solution:
I just add this function in Javascript :
function ReadCookie(cookieName) {
var theCookie = "" + document.cookie;
var ind = theCookie.indexOf(cookieName);
if (ind == -1 || cookieName == "") return "";
var ind1 = theCookie.indexOf(';', ind);
if (ind1 == -1) ind1 = theCookie.length;
return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}
and I call it on Document.ready() with the name of the cookie that I want to retrieve like that:
if (ReadCookie("access_token") != '')
{ }

Using javascript to check true/false condition on viewmodel

I am using local storage variable to hold the location of a users current progress. I have ran into a problem whereby if the last section that the user was on has been since deleted I am getting a target invocation must be set error. This is my code:
if (localStorage["Course" + '#Model.Course.CourseID'] != null && localStorage["Course" + '#Model.Course.CourseID'] != "") {
var id = localStorage["Course" + '#Model.Course.CourseID'];
}
else {
var id = '#Model.CourseSections.First().CourseSectionID';
}
I need to check using javascript that the localStorage course section is still existing in the database so I created the following ViewModel method:
public bool CourseSectionLaunchStillExistCheck(int courseSectionID)
{
this.TargetCourseSection = courseSectionRepository.Get(cs => cs.CourseSectionID == courseSectionID).FirstOrDefault();
if (this.TargetCourseSection != null)
{
return true;
}
else
{
return false;
}
}
But when I try to use the following javascript:
if (localStorage["Course" + '#Model.Course.CourseID'] != null && localStorage["Course" + '#Model.Course.CourseID'] != "") {
var id = localStorage["Course" + '#Model.Course.CourseID'];
if ('#Model.CourseSectionLaunchStillExistCheck(id)' != true) {
var id = '#Model.CourseSections.First().CourseSectionID';
}
}
else {
var id = '#Model.CourseSections.First().CourseSectionID';
}
It is failing to recognise the id parameter saying it does not exist in the current context. How can I ensure that the course section exists using javascript before setting the variable?
Could I use a post such as:
var postData = { 'courseSectionID': id };
$.post('/Course/CourseSectionLaunchStillExistCheck/', postData, function (data) {
});
and then how could i check if the result of this post data would be true or false?

"Cannot find function replace" errror when trying to replace part of a string

I need a way to replace part of a string with another string using Google Apps Script. I tested the following and it worked:
function test(){
var value = 'https://plus.google.com/117520727894266469000';
var googleimageURL = googlePlus(value);
Logger.log('Returned Result: ' + googleimageURL);
}
function googlePlus(value){
var apiKey = ScriptProperties.getProperty('apiKey');
var re = 'http://'
var theURL = value;
Logger.log('Google+ is called: ' + value);
var replacingItem = 'https://';
var theURL = theURL.replace(re, replacingItem);
Logger.log('Google+ Values 2: ' + value + ' : ' + theURL + ' after ' + replacingItem);
return imageURL;
}
But, when I embedded into the following code, it did not work. Any idea?
//If a Google+ column was not specified,put a flag.
if (googleColumn && column == googleColumn) {
if (value == ""){
columns.push(nogoogleColumn);
values.push(flag);
var googleimageURL="";
} else {
var googleimageURL = googlePlus(value);
Logger.log('Returned Result: ' + googleimageURL);
}
}
The script did not work as I wish. It seems to stop at line:
var theURL = theURL.replace(re, replacingItem);
Additional information: Google notified me with the following message
onFormSubmit
TypeError: Cannot find function replace in object https://plus.google.com/117520727894266469000. (line 536) formSubmit
I found the mistake. It is Type Error. value in the second block is not a "string", while the first block is a "string". Hence to fix the second block, I need to use:
var value = value.toString();
before passing to googlePlus(value)

Variable without value inside callback function

Im having a strange problem with the following code:
function getTrxData(trx,inputPar,outputPar,callback) {
var retorno = {};
var URL = '/XMII/Runner?Transaction=' + trx;
var params = "";
for(key in inputPar)
params = params + "&" + key + "=" + inputPar[key];
if(!outputPar)
outputPar = "*";
if(params)
URL = URL + params;
URL = URL + '&OutputParameter=' + outputPar;
$.ajax({
type: "GET",
url: URL,
async: true,
success: function(data){
retorno.datos = $.xml2json(data);
retorno.tipo = 'S'; // Success
retorno.mensaje = "Datos obtenidos correctamente";
callback(retorno);
},
error: function(jqXHR, textStatus, errorThrown){
retorno.tipo = 'E'; // Error
retorno.mensaje = "Error: " + textStatus;
callback(retorno);
}
});
}
function crearSelect(trx,inputPar,outputPar,selectID,campoTextoXX,campoValor,valorDefault,callback2) {
// At this point campoTextoXX exists and has a value
getTrxData(trx,inputPar,outputPar,function(retorno2) {
// At this point campoTextoXX is an object equal to callback2
if(retorno2.tipo == 'E') {
callback2(retorno2);
return false;
}
var options = "";
var selected = "";
$.each(retorno2.datos.Rowset.Row, function(k,v) {
if(valorDefault == v[campoValor]) {
selected = " selected='selected'";
} else {
selected = "";
}
options = options + "<option value='" + v[campoValor] + selected "'>";
options = options + v[campoTextoXX];
options = options + "</option>";
});
$("#" + selectID + " > option").remove();
$("#" + selectID).append(options);
callback2(retorno2);
});
}
And the call is like this:
crearSelect("Default/pruebas_frarv01/trxTest",{letra: 'V'},"*",'selectID',"CustomerID",'OrderID','',function(retorno) {
alert(retorno.tipo + ": " + retorno.mensaje);
});
The problem is that campoTextoXX and campoValor dont get any value inside the callback function. Also, debugging in Chrome shows me that campoTextoXX has the value of the callers callback function:
alert(retorno.tipo + ": " + retorno.mensaje);
I dont know what to do next.
Any ideas?
Thx
You might find it easier to mange the callback chain by exploiting $.ajax's ability to behave as a jQuery Deferred.
This allows us very simply to specify the "success" and "error" behaviour in the guise of request.done(...) and request.fail(...) at the point where getTrxData is called rather than inside getTrxData - hence the callback chain is (ostensibly) one level less deep.
function getTrxData(trx, inputPar, outputPar) {
inputPar.Transaction = trx;
inputPar.OutputParameter = (outputPar || '*');
return $.ajax({
url: '/XMII/Runner?' + $.param(inputPar)
});
}
function makeOptions(obj, selectID, campoTextoXX, campoValor, valorDefault) {
var $option, selected, $select = $("#" + selectID);
$("#" + selectID + " > option").remove();
$.each(obj.datos.Rowset.Row, function(k, v) {
selected = (valorDefault == v[campoValor]) ? ' selected="selected"' : '';
$option = $('<option value="' + v[campoValor] + selected + '">' + v[campoTextoXX] + "</option>");
$select.append($option);
});
return obj;
}
function crearSelect(trx, inputPar, outputPar, selectID, campoTextoXX, campoValor, valorDefault, callback) {
var request = getTrxData(trx, inputPar, outputPar);
request.done(function(data) {
var obj = {
datos: $.xml2json(data),
tipo: 'S',// Success
mensaje: "Datos obtenidos correctamente"
};
callback(makeOptions(obj, selectID, campoTextoXX, campoValor, valorDefault));
});
request.fail(function(jqXHR, textStatus, errorThrown) {
var obj = {
tipo: 'E',// Error
mensaje: "Error: " + textStatus
};
callback(obj);
});
}
crearSelect("Default/pruebas_frarv01/trxTest", {letra:'V'}, "*", 'selectID', "CustomerID", 'OrderID', '', function(retorno) {
alert(retorno.tipo + ": " + retorno.mensaje);
});
You will see that this is essentially a refactored version of your original code, with significant simplification of the string handling in getTrxData, which appears to work correctly.
The options code has been pulled out as a separate function, makeOptions, to make the new structure of crearSelect clearer. This is not strictly necessary and the code could be re-combined without penalty.
Tested here insomuch as to make sure it loads and runs through to the "Error" alert, which it does successfully. Without access to the server-side script, I can't test/debug the full ajax functionality so you may need to do some debugging.
The problem appears to be that you are overwriting the variable "pepe" somewhere in your code.
Also, check how you are assigning your callback function and parameter object. A quick look appears that it is not being supplied the correct parameters.
You should be careful not to use global variables within your success and error functions. so instead of:
success: function(data){
retorno.datos = $.xml2json(data);
retorno.tipo = 'S'; // Success
retorno.mensaje = "Datos obtenidos correctamente";
callback(retorno);
}
I think you should do something like:
success: function(data){
var retorno = {};
retorno.datos = $.xml2json(data);
retorno.tipo = 'S'; // Success
retorno.mensaje = "Datos obtenidos correctamente";
callback(retorno);
}
furthermore you should use Firebug for Firefox to step through your code and watch your variables to ensure that the data is coming in correctly, and not getting overwritten at any point
Your control flow is a bit confusing, and another thing you can do is check to make sure your callbacks and variables are correct using some typeof conditionals to make sure they are functions, etc. try doing things like this:
success: function(data){
var retorno = {};
retorno.datos = $.xml2json(data);
retorno.tipo = 'S'; // Success
retorno.mensaje = "Datos obtenidos correctamente";
if (typeof callback !== "function" || typeof data !== "object"){
console.log('error');
throw "callback or data is not correct type";
}
callback(retorno);
}
and make sure you aren't getting an error in the console.

Categories