Using variables sent from script into html - javascript

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 .

Related

How to get values from a URL using hash and split

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.

How to getet url query string in Angular2

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'];
}

Get ID from link on the page

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

Ajax - after "success" go to another page retrieve user id from the url there

var JSONonj = {"name": "James","age":"25"};
var data = "This data i would like to retrieve and print in the main.html page after success call in ajax.";
$.ajax({
url: "/user",
type: "POST",
data: JSONobj,
dataType: "json",
success: function() {
window.location.href = "main.html";
},
contentType: "application/json"
});
Here is the deal. After success i want to redirect to main.html and when I get there, I would like to retrieve and print data variable there.
The redirection works fine. But I can not receive the data there.
There are two main ways to achieve that :
somehow send the data to the server (see the other answers for possible ways to do that)
use the browser's localStorage :
success: function() {
localStorage.setItem('myMainKey', data);
window.location.href = "main.html";
}
// in main.html's javascript :
var data = localStorage.getItem('myMainKey');
if (data !== undefined) {
//do something
}
Note : if you want to store and retrieve a complete javascript object, you would have to use JSON.stringify() / JSON.parse() for storing / retrieving it.
you can also do this:-
window.location.href="main.html?data="+data;
In main.html
var user = decodeURI(getUrlVars()["src"]);
`//Now do some stuff with this data`
`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;
}`
Here's function that can be applied if you're using jQuery.
var redirect = 'http://www.example.com/';
$.redirectPost(redirect, {x: 'exemplo', y: '123'});
// jquery extend function
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
value = value.split('"').join('\"')
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
}
});
You would have to send that data in the querystring and reconstruct it with javascript. Or you would have to POST to a handler/controller (who knows what you are using..) with that json data and reconstruct it... either way you if you are going to change the location you will have to send the data.
If you are using HTML5 then local storage would be a good option as LeGEC advised.
Storing Objects in HTML5 localStorage

jQuery redirect to source url

I would like to redirect a user to a target URL on a button click. The target URL is variable and has to be read from the current page URL parameter 'source':
For instance, I have a url http://w/_l/R/C.aspx?source=http://www.google.com
When the user clicks on a button he's being redirect to http://www.google.com
How would I do that with jQuery?
first of all you need to get the url param : source
this can be done with a function like :
function GetParam(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
// you can use it like
var source = GetParam('source');
//then
window.location.href = source
On button click handler, just write window.location.href = http://www.google.com
You will need to parse the query string to get the value of the variable source.
You don't need jQuery for it.
A simple function like this will suffice:
function getFromQueryString(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
location.href = getFromQueryString("source");
Using the url parsing code from here use this to parse your url (this should be included once in your document):
var urlParams = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
})();
Then do this to redirect to the source parameter:
window.location.href = urlParams["source"];
Since you are using the jQuery framework, I'd make use of the jQuery URL Parser plugin, which safely parses and decodes URL parameters, fragment...
You can use it like this:
var source = $.url().param('source');
window.location.href = source;
get url params : (copied from another stackoverflow question) :
var params= {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
params[decode(arguments[1])] = decode(arguments[2]);
});
window.location = params['source'];
You can do like this,
<a id="linkId" href=" http://w/_l/R/C.aspx?source=http://www.google.com">Click me</a>
$('#linkId').click(function(e){
var href=$(this).attr('href');
var url=href.substr(href.indexof('?'))
window.location =url;
return false;
});

Categories

Resources