Search code examples
javascripthttp-redirectgravity-forms-plugingravityforms

How to redirect URL via JavaScript based on a number (if 1, redirect to A; if 2, to B...)


I want to redirect a visitor based on a variable in their URL. Use case is a quiz with Gravity Forms where the user will be redirected to example.com/processing?quizresult={n}

Where n is a numerical value (0-50).

There are 3 possible outcomes (0-15, 16-30, 31-50).

I’ve found JavaScript to redirect based on if a URL contains a variable, but not a range of variables. Is there a better way than 50 “IF” statements?

<script>
if(document.location.href.indexOf('1') > -1) { 
    document.location.href = 'http://www.example.com/resultA';
}

if(document.location.href.indexOf('2') > -1) { 
    document.location.href = 'http://www.example.com/resultA';
}

if(document.location.href.indexOf('3') > -1) { 
    document.location.href = 'http://www.example.com/resultA';
}


Solution

  • Try this:

    • Extract {n} from your url string
    • Conditionally redirect according to the value of n

    Example:

    // extract {n} from example.com/processing?quizresult={n}
    const getParamValue = (url, parameterKey) => {
      const [urlWithoutParameters, parameters = ''] = url.split('?'); // ['example.com/processing', 'quizresult=1']
      const paramsArr = parameters.split('&'); // ['quizresult=1']
    
      for (let i = 0; i < paramsArr.length; i++) {
        const [k, v] = paramsArr[i].split('='); // k = 'quizresult', v = '1'
        if (k === parameterKey) {
          return v;
        }
      }
    };
    
    // conditionally redirect to the result urls.
    const conditionallyRedirect = (url) => {
      const quizResult = getParamValue(url, 'quizresult');
      if (quizResult >= 0 && quizResult < 16) {
        console.log('resultA');
        // document.location.href = 'http://www.example.com/resultA';
      } else if (quizResult >= 16 && quizResult < 31) {
        console.log('resultB');
        // document.location.href = 'http://www.example.com/resultB';
      } else if (quizResult >= 31 && quizResult <= 50) {
        console.log('resultC');
        // document.location.href = 'http://www.example.com/resultC';
      }
      // do not redirect otherwise
    };
    
    
    // Examples
    conditionallyRedirect('example.com/processing?quizresult=1'); // redirects to resultA
    conditionallyRedirect('example.com/processing?quizresult=17&someotherparam=whatever'); // redirects to resultB
    conditionallyRedirect('example.com/processing'); // does not redirect
    conditionallyRedirect('example.com/processing?quizresult=100'); // does not redirect
    

    So this would work for you:

    conditionallyRedirect(document.location.href);