Parsing variable into .get() function - javascript

:-)
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);

Related

Recursive promise not returning expected value

With a slight modification, I am attempting to use the code provided by Bergi in jQuery Recursive AJAX Call Promise. In my case I make an AJAX call to test if a username is already used. If it is already in use then compose a new username and test that one. Once we have a username that is not in use then we are done and return that unused username. However, I am not getting the expected return value. The return value I get is undefined. The console log statement:
console.log("Return => " + username);
just before the return from the requestUsername function shows that I am returning a good value, but it is not making it to the:
requestUnused().done(function(unused_uname)
statement. Here is my code:
$(document).ready(function() {
function request(query_val) {
// return the AJAX promise
return $.ajax({
url: "/php/is_dup_ad_json.php",
method: 'GET',
dataType: 'json',
data: {
query: query_val, sid: Math.random()
},
});
}
function requestUsername(username) {
console.log("Initial => " + username);
return request(username).then(function(ajax_json){
$.each(ajax_json, function(key, value) {
$.each(value, function(k, v) {
if ((k == "duplicate") && (v > 0)) {
// try again with a different username
var first_initial = fname.substr(0,1);
var surname = lname.substr(0,6);
var idx = v + 1;
var tmpUname = surname + first_initial + idx;
console.log("Temp => " + tmpUname);
return requestUsername(tmpUname);
}
else {
console.log("Return => " + username);
return username;
}
});
});
});
}
function requestUnused(){
var fname = "bugs";
var lname = "bunny";
var first_initial = fname.substr(0,1);
var surname = lname.substr(0,7);
var init_uname = surname + first_initial;
return requestUsername(init_uname);
}
$("#test").on('click', function() {
requestUnused().done(function(unused_uname) {
console.log("Done => " + unused_uname);
});
});
});
Without debugging tools at hand, I would guess that the return value from "requestUnused()," which is a ".then" returned from "requestUsername" is competing with the ".done". I believe ".done" and ".then" serve a similar purpose. If you want to keep a modular approach, separating the functions as it were, you could define the function in the ".then" externally and remove "requestUsername" entirely. Then (no pun intended) call "request" directly in "requestUnused," applying the ".then" functionality extracted previously in the ".click" function instead of ".done."
Alternatively, you could simply call "requestUnused()" in the click function without a ".done".

JQuery $.getJSON asynchronous workaround - caching ajax results

I am caching the JSON returned from ajax calls and then displaying the results from the cache. My issue is if there is no cache for that Ajax call already, the results only display on refresh. This is down to the fact that ajax is asynchronous but how do I get around that? Ajax async:false has been deprecated so that's not an option. Would the $.getJSON .done() function suffice or is there a better way?
Here is my code so far:
if ((online === true)) {
//get JSON
$.getJSON(baseurl + '/wp-json/app/v2/files?filter[category]' + cat + '&per_page=100', function(jd) {
//cache JSON
var cache = {
date: new Date(),
data: JSON.stringify(jd)
};
localStorage.setItem('cat-' + cat, JSON.stringify(cache));
});
//if not online and no cached file
} else if ((online === false) && (!cache['cat-' + cat])) {
alert('There are no cached files. You need to be online.');
}
//get cached JSON
cache['cat-' + cat] = JSON.parse(localStorage.getItem('cat-' + cat));
var objCache = cache['cat-' + cat].data;
objCache = JSON.parse(objCache); //Parse string to json
//display JSON results from cache
$.each(objCache, function(i, jd) {
var thumb = jd.file_thumbnail.sizes.medium;
//.....etc...
)
}}
A simple rewrite of your code yields the following:
function cacheAsCacheCan(cat, callback) {
if (online === true) {
//get JSON
$.getJSON(baseurl + '/wp-json/app/v2/files?filter[category]' + cat + '&per_page=100', function(jd) {
//cache JSON
var cache = {
date: new Date(),
data: JSON.stringify(jd)
};
localStorage.setItem('cat--' + cat, JSON.stringify(cache));
});
//if not online and no cached file
} else if ((online === false) && (!cache['cat-' + cat])) {
callback('There are no cached files. You need to be online.');
return;
}
//get cached JSON
callback(null, cache['cat-' + cat] = JSON.parse(localStorage.getItem('cat-' + cat)));
}
cacheAsCacheCan('someCat', function(error, cachedata) {
if(error) {
alert(error);
} else {
var objCache = cachedata.data;
objCache = JSON.parse(objCache); //Parse string to json
//display JSON results from cache
$.each(objCache, function(i, jd) {
var thumb = jd.file_thumbnail.sizes.medium;
//.....etc...
)
}
}
);

Array value becomes null while passing from Ajax

I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.

how to access json data globaly

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 :)

If an ID is in the list already, don't allow to add product

I'm making a simple shopping cart type thing in javascript and basically I only want one of each item to be allowed to be added. I have the following code, my plan was to split out the myIDs and then loop through to see if that number already existed but it falls over on the split and i'm not sure if that's the best way of doing it really.
Heres what I have, any help will really be appreciated. Thanks
var myIDs;
jQuery(".selectItem").click(function () {
if (myIDs) {
var split = myIDs.split(",");
alert(split[0]);
}
addToCart(jQuery(this).data('id'));
});
function addToCart(id) {
jQuery.ajax({
type: "GET",
url: "feeds/prodxml.aspx?id=" + id,
dataType: "xml",
success: function (xml) {
jQuery(xml).find('Product').each(function () {
var sTitle = jQuery(this).find('Name').text();
var sPublisher = jQuery(this).find('Description').text();
jQuery("<li></li>").html(sTitle + ", " + sPublisher).appendTo("#addedItem ul");
jQuery('.hide-on-click').remove();
addItem(id);
});
},
error: function () {
alert("An error occurred while processing XML file.");
}
});
}
function addItem(itemID) {
if (!myIDs) {
myIDs = itemID;
} else {
myIDs = myIDs + "," + itemID;
}
alert(myIDs);
}
You could make myIDs an array instead of a string.
var myIDs = [];
Then you can modify the check to be
jQuery(".selectItem").click(function () {
if(jQuery.inArray(jQuery(this).data('id'), myIDs){
var split = myIDs.split(",");
alert(split[0]);
}
addToCart(jQuery(this).data('id'));
});
function addItem(itemID) {
myIds.push(itemID);
}
jQuery's inArray function can do this for you.
See: Jquery, checking if a value exists in array or not

Categories