I went through sb code and wants to implement similar code. he used:
htmlItems += '<li><a href="show-feed.html?url=' + items[i].url + '">' +
items[i].name + '</a></li>';
and used this javascript code to retrive the url and parse to a method
.on('pageinit', '#show-feed-page', function () {
var url = this.getAttribute('data-url').replace(/(.*?)url=/g, '');
Application.initShowFeedPage(url);
it works well and i want to parse three values to the method eg
<a href="showProduct.html?code='+ items[i].code +',name='+items[i].name+',price='+items[i].price+'">"and need code to retrive and parse to a method
initShowProductPage(code,name,price);
First of all, your html is wrong, you have to prepare proper query string format, the updated html mark up is:
<a href="showProduct.html?code='+ items[i].code +
'&name='+items[i].name+'&price='+items[i].price+'">"
You have to access window.location.href and parse it for the query string parameters.You can write a method which parses the url, like below:
function parseURL() {
var vars = [];
var hashes = window.location.href.slice( window.location.href.indexOf('?')+1 ).split("&");
for (var i=0;i<hashes.length;i++) {
hash = hashes[i].split("=");
vars.push( hash[0] );
vars[ hash[0] ] = hash[1];
}
return vars;
}
Then you can access them using code, name and price parameters like below:
.on('pageinit', '#show-feed-page', function () {
var hashObj = parseURL();
// To get code
var code = hashObj["code"];
// To get name
var name = hashObj["name"];
// To get price
var price = hashObj["price"];
// Now call the method
initShowProductPage(code,name,price);
});
Related
I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}
So I'm making a webpage with some code snippets loaded in from txt files. The information to paths and locations of the txt files are stored in a json file. First I'm loaing the json file looking like this
[
{"root":"name of package", "html":"htmlfile.txt", "c":"c#file.txt", "bridge":"bridgefile"},
{"root":"name of package", "html":"htmlfile.txt", "c":"c#file.txt", "bridge":"bridgefile"}
]
After loaded I'm using templates from my index.html file and then inserting the templates. My problem is that its happening asynch so that the page never looks the same because of the asynch nature of js.
Here is what my jquery code for loading and inserting looks like:
$(document).ready(function () {
var fullJson;
$.when(
$.get('/data/testHtml/data.json', function (json) {
fullJson=json;
})
).then(function(){
for(var i=0; i<fullJson.length; i++){
templefy(fullJson[i],i);
}
})
var templefy = function (data, number) {
//Fetches template from doc.
var tmpl = document.getElementById('schemeTemplate').content.cloneNode(true);
//Destination for template inserts
var place = document.getElementsByName('examples');
//Set name
tmpl.querySelector('.name').innerText = data.root;
//Next section makes sure that each tap pane has a unique name so that the system does not override eventlisteners
var htmlNav = tmpl.getElementById("html");
htmlNav.id += number;
var htmlLink = tmpl.getElementById('htmlToggle');
htmlLink.href += number;
var cNav = tmpl.getElementById('c');
cNav.id += number;
var cLink = tmpl.getElementById('cToggle');
cLink.href += number;
var bridgeNav = tmpl.getElementById('bridge');
bridgeNav.id += number;
var bridgeLink = tmpl.getElementById('bridgeToggle');
bridgeLink.href += number;
//Auto creates the sidebar with links using a link template from doc.
var elementLink = tmpl.getElementById('elementLink');
elementLink.name +=data.root;
var linkTemplate = document.getElementById('linkTemplate').content.cloneNode(true);
var linkPlacement = document.getElementById('linkListWVisuals');
var link = linkTemplate.getElementById('link');
link.href = "#"+data.root;
link.innerText = data.root;
linkPlacement.appendChild(linkTemplate);
//Fetches html, c# and bridge code. Then inserts it into template and finally inserts it to doc
$.get("/data/" + data.root + '/' + data.html, function (html) {
tmpl.querySelector('.preview').innerHTML = html;
tmpl.querySelector('.html-prev').innerHTML = html;
$.get('/data/' + data.root + '/' + data.c, function (c) {
tmpl.querySelector('.c-prev').innerHTML = c;
$.get('/data/' + data.root + '/' + data.bridge, function (bridge) {
console.log(bridge);
tmpl.querySelector('.bridge-prev').innerHTML = bridge;
place[0].appendChild(tmpl);
})
})
})
}
});
So yeah my problem is that it just fires in templates whenever they are ready and not in the order written in the json file.
I'll take whatever help I can get..Thank you :)
To my knowledge, there is no golden method and i usually apply one of the following options:
1) Preload the files separately e.g. create key "body" for each entry in your json and then set the value of it to the contents of the file.
2) Do not display items until they are not fully loaded in the DOM and before you show them, sort them in the DOM by e.g. their position in the json array.
Hope it helps.
My only way out has been to make the whole application in angular instead and using a filter to make sure that I get the right result.
I want to convert my all wordpress theme link to be ajax enable. So, I am using this code
siteUrl = "http://" + top.location.host.toString(),
url = '';
$(document).delegate("a[href^='" + siteUrl + "']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/])", "click", function() {
var pathname = this.pathname;
return false;
});
Now, I want if this var pathname is like /ebook/some-ebook then I want to call the post_load() function and if it is like /ebook then I want to call the post_archive() javascript function.
ebook is a post-type and some-ebook is %postname%.
Thank you
I don't understand half of what you're asking...but it sounds like you just want to split() the pathname into its relevant pieces.
In that case, you can do something like the following:
var pathPieces = pathname.split('/', 3),
archiveName = pathPieces[1],
postName = pathPieces[2];
At that point, you can do whatever you want with those path pieces. For example:
if ( archiveName === 'ebook' ) {
post_archive();
}
THE PROMPT: We have a search that connects to an JSON API url. The search query is inside the url, and the API generates a new JSON file for every search term. We also cannot rely on the browser to cache for us, and we can't use PHP or server side caching; we need to use HTML5 LocalStorage (and we don't care that IE7 can't use it)
We need to cache every new JSON file for every new search. We want to cut down on requests per minute, so we want to use a cached version of the JSON file for repeated search terms.
WHERE I'M STUCK: What has made this difficult is caching a JSON file for each new/different search term. I have been able to cache the first search, but then all subsequent searches use the same cached JSON.
We need help rewriting this so each time a new search is made, it checks to see if the term was searched for previously and if so, grabs the corresponding JSON file. Then of course if the search term is new then cache a new JSON file for that specific search term.
WHAT I'VE TRIED: In my research I've seen a lot of very complicated solutions and I can't seem to get my head completely around all of it, some of these solutions almost worked, I think I just need a better explanation for this specific case.
I think this is the answer but I don't know how to apply it to my situation: jQuery deferred ajax cache
This is crazy and it almost works, it writes into the console when it recognizes that I've searched the same thing again, and it does stop a new request, but unfortunately the cached JSON isn't there, it returns no results.
Caching a jquery ajax response in javascript/browser
WHAT I HAVE SO FAR:
MY PSUEDO CODE:
var searchTerm = WHATEVER IS TYPED INTO THE SEARCHBOX
// The JSON file
var url = 'https://api.example.com/fake/json/path/{'+searchTerm+'}';
// Local Storage Caching Promise
var cachedData = localStorage.getItem("cachedData"),
def = $.Deferred();
if (!cachedData) {
def = $.getJSON(url, function(data) {
cachedData = data;
localStorage.setItem("cachedData", JSON.stringify(cachedData));
});
}
else{
cachedData = JSON.parse(cachedData);
def.resolve();
}
def.done(function() {
var resultHTML = '';
for(var i = 0; i < Object.keys(cachedData.things).length; i++){
$.each(cachedData, function(index, node){
resultHTML += '<li>'
resultHTML += '<h1>' + node[i].name + '</h1>';
resultHTML += '</li>';
});
}
$('div#results').html(resultHTML);
});
EXAMPLE JSON:
{
"things": [
{
"type": "thing",
"username": "randoguy",
"name": "name001",
},
{
"type": "thing2",
"username": "randoguy2",
"name": "name002",
},
...
Thank you #Ian for providing the hints to my answer!
var searchTerm = WHATEVER IS TYPED INTO THE SEARCHBOX;
// The JSON file
var url = 'https://api.example.com/fake/json/path/{'+searchTerm+'}';
// BABAM! Right here, SearchTerm + "-cachedData" gets unique cached data
var cachedData = localStorage.getItem(searchTerm + "-cachedData"),
def = $.Deferred();
if (!cachedData) {
def = $.getJSON(url, function(data) {
cachedData = data;
// BABAM! And here is where the unique cachedData is set! SearchTerm + "-cachedData"
localStorage.setItem(searchTerm + "-cachedData", JSON.stringify(cachedData));
});
}
else{
cachedData = JSON.parse(cachedData);
def.resolve(cachedData);
}
def.done(function(data) {
var resultHTML = '';
for(var i = 0; i < Object.keys(data.repositories).length; i++){
$.each(data, function(index, node){
resultHTML += '<li>'
resultHTML += '<h1>' + node[i].name + '</h1>';
resultHTML += '<p>' + node[i].owner + '</p>';
resultHTML += '</li>';
});
}
$('div#results').html(resultHTML);
});
Where would I be without StackOverflow. Thank you all!
I found this script at Stack Overflow:
window.params = function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for(var i in param_array){
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
}();
This splits a URL into data, like PHP does with $_GET.
I have another function, which uses it and it refreshes the iframe. I want to get the data from the URL and add another with it if some of these data exist. Firebug shows me, that search is not defined, but why?
function RefreshIFrames(MyParameter) {
var cat = window.params.cat;
var category = window.params.category;
var search = window.params.search;
if (search.length>0 && category.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search="+search+"&category="+category+"&rendez="+MyParameter;
}
if (cat.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat="+cat+"&rendez="+MyParameter;
}
if (cat.length==0 && category.length==0 && search.length==0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez="+MyParameter;
}
alert(window.location);
}
If you want to add rendez OR change the existing rendez, do this - I am assuming the URL is actually beginning with http://siriusradio.hu/kiskunfelegyhaza/video/index.php so no need to create it. Let me know if you need a different URL than the one you come in with
The parameter snippet did not work proper (for in should not be used on a normal array)
Here is tested code
DEMO
DEMO WITH DROPDOWN
function getParams(passedloc){
var params = {}, loc = passedloc || document.URL;
loc = loc.split('?')[1];
if (loc) {
var param_array = loc.split('&');
for(var x,i=0,n=param_array.length;i<n; i++) {
x = param_array[i].split('=');
params[x[0]] = x[1];
}
}
return params;
};
function RefreshIFrames(MyParameter,passedloc) { // if second parm is specified it will take that
var loc = passedloc || document.URL; //
window.param = getParams(loc);
loc = loc.split("?")[0]+"?"; // will work with our without the ? in the URL
for (var parm in window.param) {
if (parm != "rendez") loc += parm +"="+ window.param[parm]+"&";
}
// here we have a URL without rendez but with all other parameters if there
// the URL will have a trailing ? or & depending on existence of parameters
loc += "rendez="+MyParameter;
window.console && console.log(loc)
// the next statement will change the URL
// change window.location to window.frames[0].location to change an iFrame
window.location = loc;
}
// the second parameter is only if you want to change the URL of the page you are in
RefreshIFrames("rendez1","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat=cat1&search=search1");
RefreshIFrames("rendez2","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search=search2");
RefreshIFrames("rendez3","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez=xxx&search=search2");
RefreshIFrames("rendez4","http://siriusradio.hu/kiskunfelegyhaza/video/index.php");
// here is how I expect you want to call it
RefreshIFrames("rendez5"); // will add or change rendez=... in the url of the current page