Accessing URL parameters - PHP & Angular JS
Ad
So my website is PHP for the backend and AngularJS for the frontend. Weird that I'm finding that I have to use PHP on the frontend to achieve some things like getting URL paramters. Explanation below;
Given the following URLs for example
http://www.test.co.uk/search-menu/1/cinamon-soho
http://www.test.co.uk/search-restaurant?location=asokoro&day=today&time=1100
My Angular code in the same page requires the parameters location, day etc. Right now I'm having to use the line below to pass them to angular
$scope.l = <?php echo json_encode($_GET['location']); ?>;
My questions are;
- Is there a way to access these variables using just Angular so I can take PHP out of the equation?
- If question 1 is possible, how can I do the same if I then decide to move my Angular code away from that page to a dedicated
.js
page that I reference using
<script src="http://www.test.co.uk/js/main.js"></script>
FYI
The website was not built from the ground up using AngularJS. Angular was later introduced to the frontend heavy lifting PHP was doing so the website is not a SPA. There's no angular routing in place.
Thanks.
Ad
Answer
Ad
I would use a function like below
function fetchGetVariables() {
var loc = "http://www.test.co.uk/search-restaurant?location=asokoro&day=today&time=1100";
// var loc = window.location.href; // Use this in actual use
var result = {};
var parts = loc.split("?");
if (parts.length > 0) {
var params = parts[1].split("&");
for (var i = 0; i < params.length; i++) {
var keyValuePair = params[i].split("=");
var key = keyValuePair[0];
var value = "";
if (keyValuePair.length > 0) {
value = keyValuePair[1];
}
result[key] = value;
}
}
return result;
}
console.log(fetchGetVariables());
This gives the output:
Object {location: "asokoro", day: "today", time: "1100"}
See it at this fiddle.
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad