0

I've got a pretty basic form, that has a couple fields that are saving data via SharePoint API post. My ultimate goal is to pass in a parameter in the URL, and save that parameter in the field named "SiteURL". How do I grab the url and insert it as part of my API Post. I've currently just saving "Hello World" for the SiteURL (I wanted to make sure it was saving). Here's my code so far:

function addEntry() {

        var item = {
            "__metadata": { "type": "SP.Data.EntryListItem" },
            "SiteURL": "Hello World",
            "Title": $('#inputTitle').val(),
            "Entry": $('#inputEntry').val()
        };


        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/lists/getbytitle('" + listName + "')/Items",
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
        });
        return false;
    }
1

Below function can be used to get the query string parameters from URL:

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

You can use it like:

var mytext = getUrlVars()["siteUrl"];

Okay but when the parameter is missing from the URL the value will be undefined. Here’s how to set a default value to the variable:

function getUrlParam(parameter, defaultvalue){
    var urlparameter = defaultvalue;
    if(window.location.href.indexOf(parameter) > -1){
        urlparameter = getUrlVars()[parameter];
        }
    return urlparameter;
}

Use it like this:

var mytext = getUrlParam('siteUrl', _spPageContextInfo.webAbsoluteUrl);

Note: Here I am passing current site URL as default. But, you can pass any other site URL you want by default if the query string parameter is missing from URL

Solution for you:

  1. Add getUrlVars() and getUrlParam() functions in your code.
  2. Construct a URL to your form page with siteUrl as query string parameter like: https://tenant.sharepoint.com/sites/siteName/SitePages/PageName.aspx?siteUrl=<enter the site URL here>
  3. On form page Use your code like below:
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

function getUrlParam(parameter, defaultvalue){
    var urlparameter = defaultvalue;
    if(window.location.href.indexOf(parameter) > -1){
        urlparameter = getUrlVars()[parameter];
        }
    return urlparameter;
}

function addEntry() {
    var siteUrlFromURLParameter = getUrlParam('siteUrl', _spPageContextInfo.webAbsoluteUrl);

    var item = {
        "__metadata": { "type": "SP.Data.EntryListItem" },
        "SiteURL": siteUrlFromURLParameter,
        "Title": $('#inputTitle').val(),
        "Entry": $('#inputEntry').val()
    };


    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/lists/getbytitle('" + listName + "')/Items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
    });
    return false;
}

Reference: Get URL Parameters With JavaScript.

| improve this answer | |
  • Have you tried this? Is it working for you? let me know if you face any issue while using it. – Ganesh Sanap Mar 5 at 13:34
  • Success! This works great. I appreciate the reference links and step by step instructions. I just got it to work on my site. Thank you!!! – Susan T. Mar 5 at 14:00
  • Welcome. Glad it worked for you. Please Upvote(^) and accept as an Answer as it helped you. – Ganesh Sanap Mar 5 at 14:01
0

Per this community post, you can use URLSearchParams which is simple and has decent (but not complete) browser support.

Assuming the value was passed to this page like https://fullpageurl.aspx?SiteUrl, then the following should get you what you need:



    function addEntry() {

        const urlParams = new URLSearchParams(window.location.search);

        var item = {
            "__metadata": { "type": "SP.Data.EntryListItem" },
            "SiteURL": urlParams.get('SiteUrl'),
            "Title": $('#inputTitle').val(),
            "Entry": $('#inputEntry').val()
        };


        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/lists/getbytitle('" + listName + "')/Items",
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
        });
        return false;
    }
| improve this answer | |
  • The URLSearchParams interface is very easy to use. But, unfortunately it is not supported in IE browser. – Ganesh Sanap Mar 5 at 5:54
0

We can use the method below to get the parameter from the url.

function getUrlParameter(name){
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}

Modify your code as below.

function addEntry() {
    var siteUrl=getUrlParameter("SiteUrl");
    var item = {
        "__metadata": { "type": "SP.Data.EntryListItem" },
        "SiteURL": siteUrl,
        "Title": $('#inputTitle').val(),
        "Entry": $('#inputEntry').val()
    };


    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/lists/getbytitle('" + listName + "')/Items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
    });
    return false;
}
function getUrlParameter(name){
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.