I want to get very specific string over my url to add as parameter in js:
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token=', usuario,
completado,
fallo);
}
URL
http://localhost:55728/Cliente/#/cambiarContrasena.html?Token=e12009cf-d48d-42e7-ba43-83b5082019bb
I want to get only Guid afrer Token= like:
e12009cf-d48d-42e7-ba43-83b5082019bb
I try using:
var url = (location.pathname + location.search).substr(1);
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
completado,
fallo);
}
But I get
http://localhost:55718/api/usuario/cambiarContrasena?token=Cliente/
I try too:
var guid = url.substr(url.indexOf('Token=') + 6);
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token='+guid, usuario,
completado,
fallo);
}
But I get
Uncaught ReferenceError: url is not defined
What I need to do to get only parameters after Token= ?
I try as this question:
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token='+getParameterByName, usuario,
completado,
fallo);
}
But I get an error:
POST
http://localhost:55718/api/usuario/cambiarContrasena?token=function%20getPa…%20%20var%20regex%20=%20new%20RegExp(%22[?&]%22%20+%20name%20+%20%22(=([^&
400 (Bad Request)
just try this :
var url = window.location.hash.split('?Token=')[1];
var guid = url || '';
Related
I have a complex string (URL) that is a link .
How to OPEN on click a specific URL from that URL/string... NOT the 'parent' URL?
Parent URL looks like this:
http://www.randomsite.com & randomtext & URL I need
.
Thank you.
On the assumption you mean get the url from the query string e.g. http://www.randomsite.com?foo=bar&url=http://www.url-i-want.com
You could do this:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var url = getParameterByName('url');
window.location.href = url;
ref: https://stackoverflow.com/a/901144/905653
Here is a simple solution
function getUrlVar(stringUrl, name) {
for (var value of stringUrl.split("?")[1].split("&")) {
var valueArr = value.split("=");
if (valueArr[0] === name) {
return valueArr[1];
}
}
return false;
}
var complexUrl = "http://www.whatever.com?lang=en&url=http://www.anyurlwhatsoever.com&test=loremipsum";
console.log(getUrlVar(complexUrl, "test"));
console.log(getUrlVar(complexUrl, "lang"));
console.log(getUrlVar(complexUrl, "url"));
console.log(getUrlVar(complexUrl, "asdasd"));
...Almost done... ! ;-)
But...I will be more 'specific':
ParentURL = URL1+random-text+URL-I-want
What I want to do is...on click on the link/ParentURL to open the link/URL-I-want, NOT the link/ParentURL (I think the best "suggestion" is...to 'specify' somehow a 'part' of the URL1...to be sure the URL of the opened window will be URL-I-want, NOT the URL1) !
Thank you .
function getUrlVar(stringUrl, name) {
for (var value of stringUrl.split("?")[1].split("&")) {
var valueArr = value.split("=");
if (valueArr[0] === name) {
return valueArr[1];
}
}
return false;
}
var complexUrl = "http://www.whatever.com?lang=en&url=http://www.anyurlwhatsoever.com&test=loremipsum";
console.log(getUrlVar(complexUrl, "test"));
console.log(getUrlVar(complexUrl, "lang"));
console.log(getUrlVar(complexUrl, "url"));
console.log(getUrlVar(complexUrl, "asdasd"));
I've been at this all day trying to figure out how to do an XMLHTTP request after authorization but just can't for the life of me figure it out.
So far I've got the code below which authorizes the user.
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?
access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile
https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = 'NOT SHOWING FOR SECURITY REASONS';
var REDIRECT = 'NOT SHOWING FOR SECURITY REASONS'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
The code works fine as far as the login goes. It's after logging in that I don't know what to do. I've tried multiple ideas and have gotten nowhere. Any ideas on how I can call tags from tag manager in "readonly" mode after this login?
Hi I just decided to try using the JavaScript web app method and was able to get this working. If you run into the same issue using the ajax version here is the documentation! Make sure to select the JavaScript tab or you can try the oAuth2.
https://developers.google.com/identity/protocols/OAuth2UserAgent
I have been getting an error when I try to post a message back.
messages.jsp
function success(data) {
$("#form" + data.target).toggle();
$("#alert" + data.target).text("Message sent.")
startTimer();
}
function error(data) {
alert("Error sending message");
}
function sendMessage(i, name, email){
var text = $("#textbox" + i).val();
$.ajax({
type: "POST",
url: '<c:url value="/sendmessage" />',
data: JSON.stringify({"target": i, "text": text, "name": name, "email": email}),
success: success,
error: error,
contentType: "application/json",
dataType: "json"
});
}
function showMessages(data){
$("div#messages").html("");
for(var i=0; i<data.messages.length; i++) {
var message = data.messages[i];
var messageDiv = document.createElement("div");
messageDiv.setAttribute("class", "message");
var subjectSpan = document.createElement("span");
subjectSpan.setAttribute("class", "subject");
subjectSpan.appendChild(document.createTextNode(message.subject));
var contentSpan = document.createElement("span");
contentSpan.setAttribute("class", "contentText");
contentSpan.appendChild(document.createTextNode(message.content));
var nameSpan = document.createElement("span");
nameSpan.setAttribute("class", "nameSpan");
nameSpan.appendChild(document.createTextNode("From: "+ message.name + '('));
var link = document.createElement("a");
link.setAttribute("class", "replylink");
link.setAttribute("href", "#");
link.setAttribute("onClick", "showReply(" + i + ")");
link.appendChild(document.createTextNode(message.email));
nameSpan.appendChild(link);
nameSpan.appendChild(document.createTextNode(")"));
var alertSpan = document.createElement("span");
alertSpan.setAttribute("class", "alert");
alertSpan.setAttribute("id", "alert" + i);
var replyForm = document.createElement("form");
replyForm.setAttribute("class", "replyForm");
replyForm.setAttribute("id", "form" + i);
var textarea = document.createElement("textarea");
textarea.setAttribute("class", "replyArea");
textarea.setAttribute("id", "textbox" + i);
var replyButton = document.createElement("input");
replyButton.setAttribute("class", "replyButton");
replyButton.setAttribute("type", "button");
replyButton.setAttribute("value", "reply");
replyButton.onclick = function(j, name, email) {
return function() {
sendMessage(j, name, email);
}
}(i, message.name, message.email);
replyForm.appendChild(textarea);
replyForm.appendChild(replyButton);
messageDiv.appendChild(subjectSpan);
messageDiv.appendChild(contentSpan);
messageDiv.appendChild(nameSpan);
messageDiv.appendChild(alertSpan);
messageDiv.appendChild(replyForm);
$("div#messages").append(messageDiv);
}
}
controller.java
#RequestMapping(value="/sendmessage", method=RequestMethod.POST, produces="application/json")
#ResponseBody
public Map<String, Object> sendMessages(Principal principal, #RequestBody Map<String, Object> data)
{
String text = (String)data.get("text");
String name = (String)data.get("name");
String email = (String)data.get("email");
Integer target = (Integer)data.get("target");
System.out.println(name + " , " + email + " , " + text);
Map<String, Object> returnVal = new HashMap<String, Object>();
returnVal.put("success", true);
returnVal.put("target", target);
return returnVal;
}
I can't post the message.
Any help or reason why I keep getting this error?
jquery.js:4 POST http://localhost:8080/spring/sendmessage 403 (Forbidden) send # jquery.js:4 ajax # jquery.js:4 sendMessage # messagesView:32 (anonymous function) # messagesView:90
I know that I should disable CSRF protection. But I don't know how to connect this function and ajax request. I've tried many ways to do that but none of them don't work.
$(function () {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
});
I need to call a c# function in my code behind using a javascript where i set two variables that i need to call my function with these variables, following my codes:
C# code behind:
public string CallWebMethod(string url, Dictionary<string, string> dicParameters)
{
try
{
byte[] requestData = this.CreateHttpRequestData(dicParameters);
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.KeepAlive = false;
httpRequest.ContentType = "application/json; charset=utf-8";
httpRequest.ContentLength = requestData.Length;
httpRequest.Timeout = 30000;
HttpWebResponse httpResponse = null;
String response = String.Empty;
httpRequest.GetRequestStream().Write(requestData, 0, requestData.Length);
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream baseStream = httpResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(baseStream);
response = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
return response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private byte[] CreateHttpRequestData(Dictionary<string, string> dic)
{
StringBuilder sbParameters = new StringBuilder();
foreach (string param in dic.Keys)
{
sbParameters.Append(param);//key => parameter name
sbParameters.Append('=');
sbParameters.Append(dic[param]);//key value
sbParameters.Append('&');
}
sbParameters.Remove(sbParameters.Length - 1, 1);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(sbParameters.ToString());
}
and this is my javascript :
<script>
function SendNeedHelpLinkTrace() {
var keysToSend = ['pCatchLinkVirement', 'pCatchLinkCarteBancaire', 'pCatchLinkRechargePaiementFactureTelecom', 'pCatchLinkPaiementVignetteImpotTaxe', 'pCatchLinkPaiementFactureEauElectricite', 'pCatchLinkServiceFatourati', 'pCatchLinkCihExpress', 'pCatchLinkEdocuments']
var lChannelId = document.getElementById('<%= HiddenChannelId.ClientID%>').value;
var lServiceId = "900149";
var lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value;
//alert(lClientId);
var lData = keysToSend.reduce(function(p,c){
var _t = sessionStorage.getItem(c);
return isEmpty(_t) ? p : p + ' | ' + _t;
}, '')
function isEmpty(val){
return val === undefined || val === null;
}
var lCollect;
console.log(lClientId);
console.log(lData);
alert(lData);
// this is the dictionnary:
lDataCollected = lClientId + ";" + lChannelId + ";" + lServiceId + ";" + lData;
console.log(lDataCollected);
//this is the url:
var url="http://10.5.230.21:4156/CatchEvent.asmx/CollectData";
sessionStorage.clear();
}
How should i proceed ?
I have that script:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var dynamicContent = getParameterByName('utm_term');
$(document).ready(function() {
if (dynamicContent.match(/buy/i)) {
$('#buy').show();
}
else {
$('#default-content').show();
}
});
When in url there is any parametr it's working fine and else working, #deafult-content showing.
Problem that when i have clean url without parametr #default-content don't showing because "Cannot read property 'match' of null".
Any idea how to fix this?
you are returning null for !results, which you can then not match against.
try combining your two checks and return an empty string:-
function getParameterByName(name, url) {
if (!url)
url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results || !results[2])
return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var dynamicContent = getParameterByName('utm_term');
$(document).ready(function() {
if (dynamicContent.match(/buy/i)) {
$('#buy').show();
} else {
$('#default-content').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="default-content" style="display:none;">test</p>