I'm trying to get url query string that comes back from the security API, so my URL looks like this www.mysite.com/profile#code=xxxx&id_token=xxx I'd like to get the values of code and id_token.
I tried using activatedRoute in my ngOnInit() but params is undefined. Can someone shed a light if this is the right way? I have created a function but its not an angular way of getting the URL query string.
this.routeParam.queryParams
.subscribe(params => {
let code = params['id_token'];
console.log('code val >> ', code);
})
My attempt which works but I'd like to do it in angular way.
getURLVars(key) {
var vars = [], hash;
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[key];
}
Try this:
Using snapshot you can get the query string from URL.
ngOnInit() {
let code = this.router.snapshot.queryParams['id_token'];
}
Related
Obviously, if I send JSON data to php using an AJAX post or get request I will end up only receiving string data type in the php $_POST variable.
What is best practice for sending JSON fields but keeping their data types? My idea would be to send the whole JSON in one $_POST field, and then decoding it one more time.
So in JavaScript instead of:
$.post('test.php', {"stringparm":"a string","numparm": 66,"boolparm":true)}, function (result) ...
I would use:
params = '{"stringparm":"a string","numparm": 66,"boolparm":true)}';
$.post('test.php', {'params': params}, function (result) {
....
}
And in php I would:
$params = json.decode($_POST['params']);
or is there a better way?
My recommendation would be to send them as a query string using Fetch or Axios, you can use Ajax as well and it should send the various datatypes properly, and then parse the query string in PHP like this.
parse_str($_SERVER['QUERY_STRING'], $data);
$data = (object) $data;
I'm sure you know what your standard query string looks like
https://example.com/?user_id=value&someotherdata=value etc...
Once you have the $data object you can access the values with the arrow -> operator.
$user_id = $data->user_id
Here is a script I use to create a query string from a provided object.
prepareQuerystring(url, paramsObject, isParamsObjectUsed, phpMethod = '') {
if (url !== '') {
let postUrl = `${url}${phpMethod}`;
if (isParamsObjectUsed) {
postUrl += `?`;
let it = 0;
let len = Object.keys(paramsObject).length
for (let i in paramsObject) {
if (it === len - 1) {
postUrl = postUrl + [i] + '=' + paramsObject[i];
} else {
postUrl = postUrl + [i] + '=' + paramsObject[i] + '&';
}
it++;
}
return postUrl;
} else {
postUrl = `${url}${phpMethod}/`;
return postUrl;
}
} else {
let postUrl = `${window.location.href}${phpMethod}/`;
if (isParamsObjectUsed) {
postUrl += `?`;
let it = 0;
let len = Object.keys(paramsObject).length
for (let i in paramsObject) {
if (it === len - 1) {
postUrl = postUrl + [i] + '=' + paramsObject[i];
} else {
postUrl = postUrl + [i] + '=' + paramsObject[i] + '&';
}
it++;
}
return postUrl;
} else {
postUrl = `${window.location.href}${phpMethod}/`;
return postUrl;
}
}
}
The url argument is your base url (https://example.com)
The paramObject is your JSON object which is just an object in Javascript.
{
user_id: 1,
someotherdata: 'shoe'
}
The PHP method argument is there to call a specific method in php, it simply gets appended after the base url, my API lets me make calls this way, yours might not so you can just leave that as an empty string ''.
And the isParamsObjectUsed is a boolean, if you pass an object in the second argument then this will be true, I honestly can't recall ever setting it to false so may need to refactor and remove that eventually.
Heres an example of how to use it.
let url = prepareQuerystring(
https://example.com/,
{
user_id: 1,
someotherdata: 'shoe',
someBool: true
},
true
)
You will have reference to all the parameters as their data type in PHP using this method. I use Axios to send http requests but this also works with Ajax and Fetch, I'd recommend using Fetch or Axios. Mostly because I can't remember how I got it working with Ajax, I typically use Fetch or Axios.
Using Fetch
fetch(url, { method: "POST" })
Hope this helps point you in the right direction. Let me know if you have any questions.
Been trying for a while to send variables using url like this:
$.post("Controlador.php",{Ema:email_usuario, Cont:pass_usuario,Acc: acc},
function(datos){
json = JSON.parse(datos);
var Nombres = json.Nombres;
var Cedula = json.Cedula;
location.href = "Acerca.html proced="+Nombres+"&proce="+Cedula;
Now, it actually works sending the variables into the new page as shown here, but I can't seem to find a way to use these variables and I was wondering if anyone could help out. Thank you.
Edit: Alright, I managed to make it work... slightly (Still very new at this). I managed to use the variables (in this case the name "Martin") and display it almost as intended. This was the result. As you can see, it has a weird %20 which I don't know how it got there. Any ideas about how to remove it? Thanks a lot. Below I display what I used for this:
<script>
function getUrlVars(){
var vars = [], hash;
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;
}
//Calling function gerUrlVars to get value from url
function volar(){
var proce= getUrlVars()["proce"];
var proced= getUrlVars()["proced"];
document.getElementById("sirve").innerHTML = proced;
}
</script>
</head>
<body onload="volar();">
get value from URL
function getUrlVars()
{
var vars = [], hash;
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;
}
//Calling function gerUrlVars to get value from url
var proce= getUrlVars()["proce"];
var proced= getUrlVars()["proced"];
Now you can use proce and proced .
I have a url like this
http://localhost:9000/index.html#/acceptRequest?screen_name=kailash&rf=FIN1
Here I want to take FIN1 from the url and store it in another variable
I am using doing this in angularjs
I have made a function like this
function getUrlVars()
{
var vars = [], hash;
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];
console.log(hash[1]);
}
return vars;
}
Here the console line hash[1] prints kailash FIN1.I only need the FIN1 to be stored and just print it in the console.How to make that happen?...
Anyway thanks in advance...
If the URL is for a resource in your Angular app, you can simply inject the $location service and use
var anotherVariable = $location.search().rf
See https://docs.angularjs.org/api/ng/service/$location#search
Here is simple solution for you.In core Javascript.
var url = "http://localhost:9000/index.html#/acceptRequestscreen_name=kailash&rf=FIN1";
var test = url.lastIndexOf('=');
var r = url.slice(test+1);
alert(r);
This code will get the url parameter you need. You just have to call it and tell what value you need.
function getUrlParameter(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
};
Use it like
var yourVariable= getUrlParameter("rf");
It will return the value of rf.
Hope this helps.
After some research i got an answer
we just have to store the return value of that function to a variable like this
var urlParams = getUrlVars();
then all we need to do is to
console.log(urlParams['rf']);
thats it...
anyway you guys have been a great help... Thank you for responding.
I have two pages in my Moodle. The first is the enrolment page and the second is the course page. On each of them I have a button, which prints PDF. On the enrolment page there are breadcrumbs, which look like that:
Startpage->Course->Miscellaneous->Learning Course
1->Enrolment->Enrolment Options
Under Learning Course 1 there is a link, which is:
http://localhost/mymoodle/course/view.php?id=6
How to get the id from this link? I need the id in order to get the course information into PDF.
I build up the functionality to get the id on course level and the code works:
$('#page-enrol-index .printpdf').click(function() {
//jquery extend function
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="'+location+'" method="POST">'+form+'</form>').appendTo('body').submit();
}
});
var vars = [], hash;
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];
}
//create the pdf
$.redirectPost("http://localhost/mymoodle/local/getinfo/getinfocourse.php", {
id: vars['id']
});
When trying to get the id it from the enrolment url
http://localhost/mymoodle/enrol/index.php?id=6
It won't work.
The id is needed in order to get the information from the course for the pdf, where there is:
$courseid = required_param('id', PARAM_INT);
The enrolment page just loads and the PDF isn't being printed, so I guess the PDF doesn't get the id from the course? I am new to Moodle and Javascript, so any help will be appreciated.
You could use the Moodle single button function instead of Javascript.
$printpdfurl = new moodle_url('/local/getinfo/getinfocourse.php', array('id' => $id));
echo $OUTPUT->single_button($printpdfurl, get_string('printpdf', 'local_getinfo'));
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)", "i"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// query string: 'http://localhost/mymoodle/course/view.php?id=6'
var id = getParameterByName('id'); // 6
I'm struggling to retrieve some value on a json in this url:
http://go-gadget.googlecode.com/svn/trunk/test.json
the url data looks like this:
[
{
"key":{
"parentKey":{
"kind":"user",
"id":0,
"name":"test 1"
},
"kind":"smsgateway",
"id":5707702298738688
},
"propertyMap":{
"content":"test1 content",
"date":"Dec 12, 2013 2:58:57 PM",
"user":"test1"
}
}]
By ignoring the "key", I want to access the value of "propertyMap" object (content,date and user) using javascript code.
I have tried this code but it couldn't get the result:
var url = "http://go-gadget.googlecode.com/svn/trunk/test.json";
$.getJSON(url, function (json) {
for (var i = 0; i < json.length; i = i + 1) {
var content = json[i].propertyMap.content;
console.log('content : ', content);
var user = json[i].propertyMap.user;
console.log('user: ', user);
var date = json[i].propertyMap.date;
console.log('date : ', date);
}
});
(unsuccessful code here http://jsfiddle.net/KkWdN/)
considering this json can't be change, is there any mistake I've made from the code above or there's any other technique to get the result?
I just learn to use javascript and json for 1 month so response with an example is really appreciated.
--edited: I change [].length to json.length, now I'm looking for the answer to access the url
That would be something like :
$.getJSON("http://go-gadget.googlecode.com/svn/trunk/test.json", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.content;
var user = map.user;
var date = map.date;
$('#date').text(date);
$('#nohp').text(user);
$('#content').text(content);
}
});
But the request fails, as no 'Access-Control-Allow-Origin' header is present on the requested resource, so you're being stopped by the same origin policy
What do you think [].length; would evaluate to .
It is 0 , so it would never go inside the for loop.
Other than that you code looks ok.
Replace your for loop as below
$.getJSON(url, function (json) {
for (var i = 0; i < json.length; i = i + 1) {
Also you seem to be accessing a API as part of the different domain.
So you need to use CORS or JSONP to get this working if you want to retrieve data from a different domain.
Change:
for (var i = 0; i < [].length; i = i + 1) {
to
for (var i = 0; i < json.length; i = i + 1) {
DEMO here.
How about using something like the following
In your case, say the object is myObj, I would get the value like this
var content = fetchValue(myObj, [0, "propertyMap", "content"], "");
var date = fetchValue(myObj, [0, "propertyMap", "date"], new Date());
var user = fetchValue(myObj, [0, "propertyMap", "user"], "");
Just to make sure that we send a default value in case we do not get the desired ojbect. The beauty of this approach is that now you do not have to worry about array or objects nested in the structure. The fetchValue function could be something like below.
function fetchValue(object, propertyChain, defaultValue){
var returnValue;
try{
returnValue = object;
forEach(propertyChain, function(element){
returnValue = returnValue[element];
});
}catch(err){
return defaultValue;
}
if(returnValue == undefined) {
returnValue = defaultValue;
}
return returnValue;
}
Adding the forEach function
function forEach(array, action){
for(var x in array)
action(array[x]);
}