For example I have the URL:http://www.website.com/example?something=abc&a=b
How can I get the something's content, "abc" and the content of a as strings?
Thanks in advance,
Mateiaru
var path = window.location.href;
var index = path.indexOf('?');
var paramstr = path.substring(index + 1);
var paramstrs = paramstr.split('&');
paramstrs.forEach(function(str, index){
var parts = str.split('=');
alert('value of ' + parts[0] + ' is ' + parts[1])
});
//var url = window.location.href;
var url = "http://www.website.com/example?something=abc&a=b";
var attributes = url.split("?")[1].split("&");
var keyValue = {};
for(i in attributes)
{
var pair = attributes[i].split("=");
keyValue[pair[0]] = pair[1];
}
alert(keyValue["something"]);
alert(keyValue["a"]);
Use a function helper:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
Then call it like:
var aValue = getURLParameter(a);
Related
I want to remove the query string from my URL before I add my URL parameters. Say my site is https://www.abcd.com/test I am appending some parameters to my URL like /def?key=value through javascript. But the page is built as https://www.abcd.com/test?/def?key=value. I want it to be https://www.abcd.com/test/def?key=value Below is my code. Any input is greatly appreciated.
redirectURL: function() {
var currentURL = window.location.href;
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
if (currentURL.indexOf("def") == -1){
document.location.search = '/def'+ '?' + 'key' + '=' + 'value';
}else{
document.location.search = '?' + 'key' + '=' + 'value';
}
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
document.location.search = kvp.join('&');
}
}
You are appending your URL parameters to the location.search property which is the querystring:
document.location.search = '/def'+ '?' + 'key' + '=' + 'value';
I believe what you want to do is append your URL parameters to the location.href property, but first you will need to separate the existing search string (querystring) from it:
var urlBase = window.location.href.split('?')[0];
window.location.href = urlBase + '/def'+ '?' + 'key' + '=' + 'value';
I have an if statement that when I print the result in the console, I can see sometimes its true, and sometimes its false.
However, whats inside the IF, its never executed and the resulting array is always empty.
var createQuery = function(viewFields,clientCode) {
return '<View Scope="RecursiveAll">' + viewFields +
'<Query>' +
'<Where>' +
'<And>' +
'<Eq>' +
'<FieldRef Name="ClientCode" />' +
'<Value Type="Text">'+ clientCode + '</Value>' +
'</Eq>' +
'<Neq>' +
'<FieldRef Name="ContentType" />' +
'<Value Type="Computed">Bill Cycle</Value>' +
'</Neq>' +
'</And>' +
'</Where>' +
'</Query>' +
'</View>';
};
var createListItemValues = function(filter) {
return function(listItems,selectProperties) {
var listItemsWithValues = [];
if (listItems) {
var enumerator = listItems.getEnumerator();
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
var listItemValues = [];
selectProperties
.forEach(function (propertyName) {
var value = listItem.get_item(propertyName);
if (propertyName === "JobCodesMulti") {
jobvalue = "";
value.forEach(function (jobvalues) {
jobvalue += jobvalues.get_lookupValue() + ";";
})
listItemValues[propertyName] = jobvalue;
} else {
listItemValues[propertyName] = value;
}
});
if(filter(listItemValues)){//only push if filter returns true
listItemsWithValues.push(listItemValues);
}
}
}
return listItemsWithValues;
};
};
var processListItemWithValue = function(listItemsWithValues) {
return function(listItem) {
var fileDirRef = listItem["FileRef"];
var id = listItem["ID"];
var title = listItem["Title"];
var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl, "");
var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id=" + fileDirRef;
var parentLink = listItem["FileRef"];
//!!!PLEASE NOTE: made arrayofstrings a local variable
var arrayofstrings = parentLink.split("/");
var billCycleFolderName = arrayofstrings[arrayofstrings.length - 2];
arrayofstrings.pop();
var hyperLink = '' + billCycleFolderName + '';
listItem["Bill Cycle"] = hyperLink;
listItemsWithValues["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString());
}
};
function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
//pass filter function to createListItemValues to get a new function that
// creates filtered list item values
var createFilteredListItemsWithValues = createListItemValues(
function(listItemValues) {
var x1=listItemValues && typeof listItemValues.FileRef === "string" && listItemValues.FileRef.split("/")[4];
var x2= currentBillCyclePath.split("/")[8]
console.log(x1===x2);
return !(//pass filter function to createListItemValues
listItemValues &&
typeof listItemValues.FileRef === "string" &&
listItemValues.FileRef.split("/")[4]
) === currentBillCyclePath.split("/")[8];
}
);
var webUrl = _spPageContextInfo.webAbsoluteUrl;
selectProperties = selectProperties.concat("ContentTypeId");
var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
// query must return the documents for the same client but in other bill cycles not the current one
var camlQuery = createQuery(viewFields,clientCode);
var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
//return a promise like here so the caller knows if something went wrong
return spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
.then(
function(listItems){
console.log("currentBillCyclePath:",currentBillCyclePath);
var listItemsValues = createFilteredListItemsWithValues
(listItems,selectProperties);
return $q.all(listItemsValues.map(addContentType))
.then(function(){ return listItemsValues; })//finished asynchronously mutating array of listItems
}
).then(
function(listItemsWithValues) {
listItemsWithValues.forEach(processListItemWithValue(listItemsWithValues));
return $q.all(
spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions)
)
}
)
}
the important lines are: var createFilteredListItemsWithValues and if(filter(listItemValues))
You filter function will always return false because you're checking if a String value equals a boolean value.
!(
listItemValues &&
typeof listItemValues.FileRef === "string" &&
listItemValues.FileRef.split("/")[4]
)
Is a boolean, while
currentBillCyclePath.split("/")[8];
is a string.
I've coding pagination with JS
out like this
<a id="prev">Previous Page</a>
<a id="next">Next Pages</a>
and JS Code like this
$('#next').click(function(){
var url = window.location.href;
var urllen = url.length;
var cur = parseInt((url.substr(urllen-1)).substr(0,1));
var nurl = url.substr(0,(urllen-1))+(cur+1);
if(cur=="NaN") { window.location = (url); }
else { window.location = (nurl); }
});
$('#prev').click(function(){
var url = window.location.href;
var urllen = url.length;
var cur = (url.substr(urllen-1)).substr(0,1);
if(cur==1||cur=="NaN") { window.location = (url); }
else { var nurl = url.substr(0,(urllen-1))+(cur-1); window.location = (nurl); }
});
and my url like
http://localtest/rftpages/record.html?s=1&l=1&bike_id=1
let's me explain the reason that i'm using a JavaScript method is i don't want to change my URL that containing page variable that i use in my whole page
so what i'm doing is get all the URL and change bike_id value to next/prev
and the problem is when it count to 19 or URL like
http://localtest/rftpages/record.html?s=1&l=1&bike_id=19
then i goes next again the URL will become
http://localtest/rftpages/record.html?s=1&l=1&bike_id=110
any idea/suggestion to fix this ?
Thanks
What you should do is grab the page from the query string and the either increment or decrements it based on what is clicked.
all you need is this function to get the parameters:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
So if I assume your example:
http://localtest/rftpages/record.html?s=1&l=1&bike_id=19
Then you can change your function to be:
$('#next').on("click", function() {
var currentPageParameter = getParameterByName("bike_id");
var s = getParameterByName("s");
var l = getParameterByName("l");
var myPage = parseInt(currentPageParameter);
if (! isNaN(myPage )) {
myPage = myPage + 1;
window.location = location.protocol + '//' + location.host + location.pathname + "?s=" + s + "&l=" + l + "&bike_id=" + myPage;
}
});
$('#prev').on("click", function() {
var currentPageParameter = getParameterByName("bike_id");
var s = getParameterByName("s");
var l = getParameterByName("l");
var myPage = parseInt(currentPageParameter);
if (! isNaN(myPage )) {
myPage = myPage - 1;
window.location = location.protocol + '//' + location.host + location.pathname + "?s=" + s + "&l=" + l + "&bike_id=" + myPage;
}
});
Hi I have a string that contains the URL as in below
http://www.myurl.com/abc/asdd/asd/rwewe/saaa/all-makes?expanded=no&s=true&searchLimit=12&searchOffset=24
I am storing the URL in a js string as below
var backToSearch = $(location).attr('href');
//typeof(backToSearch);
I want to add 12 to searchOffset and then set it to cookie myCookie.
$.cookie('myCookie', backToSearch , { path: '/' });
When 12 is added it will be like
http://www.myurl.com/abc/asdd/asd/rwewe/saaa/all-makes?expanded=no&s=true&searchLimit=12&searchOffset=36
How to add 12 to the string?
How about;
url = url.replace(/searchOffset=(\d+)/, function(a, b) {
return "searchOffset=" + (parseInt(b, 10) + 12);
})
Try
function getURLParameter(name) { //get getURLParameter value
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}
var searchOffset = getURLParameter(searchOffset), //get Current value
newSearchOffset = +searchOffset + 12; // set new value
var backToSearch = $(location).attr('href')
.replace('searchOffset=' + searchOffset, 'searchOffset=' + newSearchOffset);
//replace old value with new one
String.replace()
decodeURIComponent()
Mine was a little bit more long winded than the rest I believe:
<script type="text/javascript">
var backToSearch = $(location).attr('href');
var split = backToSearch.split("searchOffset=");
var number = parseInt(split[1]);
number += 12;
var url = split[0] + "searchOffset=" + number.toString();
</script>
If you have the searchOffset=24 parameter,
just get the value, parse it as number then add 12
parseInt(searchOffset)+12
The solution I used at the end is as below
var backToSearch = $(location).attr('href');
backToSearch = backToSearch .replace(/searchOffset=(\d+)/, function(a, b) {
return "searchOffset=" + (parseInt(b, 10) + 12);
})
I have this function which returns some XML datas from a foreign website :
function sendData()
{
var dev_statut = jQuery("select[name='statut']").val();
var dev_fdpaysid = jQuery("select[name='pays']").val();
var dev_fddeffet = jQuery("input[name='date_effet']").val();
var dev_fdnbadu = jQuery('select[name="nb_adultes"]').val();
var dev_fdnbenf = jQuery('select[name="nb_enfants"]').val();
var date_naiss_a_val = jQuery("input[name^=date_naissance_a]").map(function() {
var dev_date_naiss_a = 'dev_fadnaiss_';
return dev_date_naiss_a + this.id + '=' + this.value;
}).get().join('&');
var date_naiss_e_val = jQuery("input[name^=date_naissance_e]").map(function() {
var dev_date_naiss_e = 'dev_fadnaiss_';
return dev_date_naiss_e + this.id + '=' + this.value;
}).get().join('&');
var xdr = getXDomainRequest();
xdr.onload = function()
{
alert(xdr.responseXML);
var xml = xdr.responseXML;
var prod = xml.documentElement.getElementsByTagName("produit");
var proddata = [];
proddata.push('<ul>');
var len = prod.length;
for (var i = 0; i < len; i++) {
var nomprod = xml.getElementsByTagName('nomprod')[i].firstChild.nodeValue;
var url = xml.getElementsByTagName('url')[i].firstChild.nodeValue;
var desc = xml.getElementsByTagName('desc')[i].firstChild.nodeValue;
var texte = xml.getElementsByTagName('texte')[i].firstChild.nodeValue;
proddata.push("<li><div class='resultat_produit'>" + "<h1>" + nomprod + "</h1>" + "<p class='from_devis_desc'>" + desc + "</p>" + "<p class='form_devis_texte'>" + texte + "</p>" + "<a href='" + url + "'class='btn_url'>Faire un devis</a>" + "</div></li>");
}
proddata.push('</ul>');
jQuery('#mydiv2').append(proddata.join("\n"));
jQuery('.resultat_produit a').click(function(e)
{
e.preventDefault();
var href = jQuery(this).attr('href');
jQuery('#myDiv').empty();
jQuery('#myDiv').append('<iframe src="'+ href +'" scrolling="auto" width="960" height="100%"></iframe>');
});
}
xdr.open("GET", "http://www.MYURL.fr/page.php?dev_statut="+ dev_statut +"&dev_fdpaysid="+ dev_fdpaysid +"&dev_fddeffet="+ dev_fddeffet +"&dev_fdnbadu="+ dev_fdnbadu +"&dev_fdnbenf="+ dev_fdnbenf +"&"+ date_naiss_a_val +"&"+ date_naiss_e_val +"");
xdr.send();
}
It works fine on any major browsers (Chrome, FF, etc) but not on ... IE ! I've opened the console and it says : "DocumentElement is undefined ..."
I'm tired and can't fix that, any help will be very very appreciated !!