I make a request for a oAuth request token and I do that by visiting a special URL. The result of this request (content of page) is this, how can I get the auth_token form this?
oauth_token=TBFdNoytaizrfMAWNZ6feqssNz3BsozHk5AesIioX8u8Ec&oauth_token_secret=DtQ3jiUIe33VdRcBAKwVQJRWpgKtEHi3m1yl3k0nlsHCBj0&oauth_callback_confirmed=true
You could find it like this:
var string = 'oauth_token=TBFdNoytaizrfMAWNZ6feqssNz3BsozHk5AesIioX8u8Ec&oauth_token_secret=DtQ3jiUIe33VdRcBAKwVQJRWpgKtEHi3m1yl3k0nlsHCBj0&oauth_callback_confirmed=true';
var match = /oauth_token=([^&]*)/.exec(string);
if(match)
{
var oauth_token = match[1];
}
Also I don't think it's a good idea to show your oauth_token_secret here as I think that only you should know that secret, right?
var oAuth = /auth_token=(.*?)&/.exec( str )[1];
// token param + value
var tokenParam = ostr.split("&")[0];
// only token value
var tokenValue = tokenParam.split("=")[1];
The result of the request is in the same format as a query string. This can be parsed using common JS functions.
var str = "oauth_token=TBFdNoytaizrfMAWNZ6feqssNz3BsozHk5AesIioX8u8Ec&oauth_token_secret=DtQ3jiUIe33VdRcBAKwVQJRWpgKtEHi3m1yl3k0nlsHCBj0&oauth_callback_confirmed=true";
var auth_token = getQueryVariable("oauth_token", str);
console.log(auth_token);
function getQueryVariable(variable, query) {
if (!query) query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
Related
I have always used PHP for passing query strings into forms, but I am looking to move to a static site scenario and need the query data from a URL to populate the form fields.
I have the code with no console errors, but the data is not passing into the form fields. Does anyone know how this can be done that works across all modern and legacy browsers?
function getQueryString() {
var result = {};
if(!window.location.search.length) return result;
var qs = window.location.search.slice(1);
var parts = qs.split("&");
for(var i=0, len=parts.length; i<len; i++) {
var tokens = parts[i].split("=");
result[tokens[0]] = decodeURIComponent(tokens[1]);
}
return result;
}
$(document).ready(function() {
$("#theForm").submit(function(e) {
//var that = this;
var qs = getQueryString();
for(var key in qs) {
var field = $(document.createElement("input"));
field.attr("name", key).attr("type","hidden");
field.val(qs[key]);
$(this).append(field);
}
});
});
https://formpopulate.netlify.com/index.html?name=john&email=john#aol.com
https://formpopulate.netlify.com/
You should use URL seachParams:
var params = (new URL("https://example.com/?name=Jonathan&age=18&test=a%20long%20string")).searchParams;
var name = params.get("name"); console.log(name); // is the string "Jonathan"
var age = parseInt(params.get("age")); console.log(age);// is the number 18
var test = params.get("test"); console.log(test); // is a long string
I'm trying to parse user input from my webpage and store it in a JSON object using inline JavaScript, make a POST request to my Node.js server, and access the contents of the request.
In my example.html, I have a function which does the following:
var xhttp = new XMLHttpRequest();
dataToSubmit = [];
// find some inputs
for ( /* each row of input */ ) {
dataToSubmit.push({
'item': itemName,
'quantity': quantity,
'price': itemPrice
});
}
xhttp.open("POST", "http://localhost:8080/menu", true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(dataToSubmit));
EDIT :
After the POST request, I have a dispatcher.js file that processes the requests:
function(request, response) {
var qs = require('querystring');
var requestBody = '';
request.on('data', function(data) { requestBody += data; });
request.on('end', function() {
var qs = require('querystring');
var passed_data = qs.parse(requestBody);
if(request.url === "/menu") {
var menu_handler = require("./menu.js");
menu_handler.processOrder(passed_data);
}
}
I'm exporting processOrder() from my menu.js. The issue is that on the server-side, I have to do the following in order to access the object:
processOrder: function(data) {
for (var a in data) { <-------------- Having to do this seems incorrect
// a is a string, inputs is the expected object
var inputs = JSON.parse(a);
}
}
My question is: is the way I'm creating the JSON object incorrect, or is the way I'm accessing it on the server-side incorrect? My expectation is that, on the server-side, I should be able to do something like this:
processOrder: function(data) {
var inputs = JSON.parse(data);
for (var input in inputs) {
// access to input.item, input.quantity, input.price
}
}
Make dataToSubmit an object:
dataToSubmit = {};
For each input row, add a uniquely keyed property to your dataToSubmit, and assign it an object:
dataToSubmit['keyName' + index] = {}
Assign this new object properties like:
dataToSubmit['keyName' + index]['item'] = itemName;
dataToSubmit['keyName' + index]['quantity'] = quantity;
dataToSubmit['keyName' + index]['price'] = itemPrice;
The cause of me not being able to access the dataToSubmit variable as a JSON object was that I was doing parsing at a previous layer before the data reached the processOrder function. The solution was to make the following changes in my dispatcher.js file (which processes the requestBody before it makes its eventual way to menu.js):
function(request, response) {
var qs = require('querystring');
var requestBody = '';
request.on('data', function(data) { requestBody += data; });
request.on('end', function() {
var qs = require('querystring');
var passed_data;
if(request.headers['content-type'] === 'application/json') { <--- parse JSON data
passed_data = JSON.parse(requestBody);
else {
passed_data = qs.parse(requestBody);
}
if(request.url === "/menu") {
var menu_handler = require("./menu.js");
menu_handler.processOrder(passed_data);
}
}
Furthermore, when creating the JSON object, the following needed to be done in order to access the data as a JSON object rather than as an array:
dataToSubmit = {'content': []};
dataToSubmit['content'].push(
{
'item': itemName,
'quantity': quantity,
'price': itemPrice
}
);
I want to send json data through url to next html page. I checked it by emulator as I am working for mobile app, the url could not redirect to next page it is crashing at the moment what is the reason behind this. How can I parse it on next page .I am new to the jquery any idea? my json data contains result of two different sql queries in an array
$.ajax({
type : "POST",
datatype : "json",
url : "http://Localhost/phpBB3/check_pass.php?username="+ username + "&password="+ password+"&f=68",
success: function(data){
alert(data);
window.location.href="source/testmenu.html?varid=" + data +"&username=" + username +"&password=" + password;
}
});
This is the code on next page
$(document).ready(function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var arr = SearchString.split('&');
console.log(arr);
//Set session variables
var username = arr[1].split('=')[1];
var password = arr[2].split('=')[1];
document.getElementById('username').value = username;
document.getElementById('password').value = password;
)};
in your case in first page urlencode json
window.location.href="source/testmenu.html?varid=" + encodeURIComponent(data) +"&username=" + username +"&password=" + password;
and in next page
var data= arr[0].split('=')[1];
var recieved_json = $.parseJSON(data);
Then try this one:
var data = {
username: username,
password: password
};
$.ajax({
type: "POST",
url: "http://Localhost/phpBB3/check_pass.php",
params: $.param(data),
success: function(a) {
window.location.href = "source/testmenu.html?"
+ $.param(a) + "&" + $.param(data)
}
});
And this would be your code for the next page (the iterator is from Satpal's answer):
$(document).ready(function() {
var params = window.location.search;
var getURLParams = function(params) {
var hash;
var json = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
json[hash[0]] = hash[1];
}
return json;
}
params = getURLParams(params);
var username = params.username;
var password = params.password;
$('#username').val(username);
$('#password').val(password);
});
Though I agree with #Jai that sending username and password in url is not recommended.
Once you get the URL to load you'll need to run your data through some encoding and decoding. You might have the wrong path. If you want "http://Localhost/source/testmenu.html" make sure the first character is a "/".
Make sure your data object is encoded correctly.
// Encode data for querystring value.
var data = {
foo: "bar"
};
var data_str = JSON.stringify(data);
data_str = encodeURIComponent(data_str);
Decode and test your URL.
// Get data from querystring value.
// Get the query as an object with decoded values.
// Note that JSON values still need parsing.
function getQuery() {
var s=window.location.search;
var reg = /([^?&=]*)=([^&]*)/g;
var q = {};
var i = null;
while(i=reg.exec(s)) {
q[i[1]] = decodeURIComponent(i[2]);
}
return q;
}
var q = getQuery();
try {
var data = JSON.parse(q.data);
} catch (err) {
alert(err + "\nJSON=" + q.data);
}
Parameter should be html encode while navigating or requesting to the URL and decode at the receiving end. It may suspect potentially dangerous content which may leads to crash.
In my view, I have a javascript function to handle a select event on a pie chart. The function is shown below:
function selectHandler() {
var selectedItem = visualization.getSelection()[0];
if (selectedItem) {
var val = data.getFormattedValue(selectedItem.row, 0);
location.href = '/Tickets';
}
}
Currently I am on the Home Controller in the Groups View. I want to navigate to the Index View of the Tickets Controller while passing the selected value from the javascript variable "val". How would I go about doing this?
Are you intending to manually navigate the user?
If you're looking for a redirect JavaScript way, then you would do something as simple as...
location.href = '/Tickets?value=' + val;
Now this may not work for everything. For example, if location.href already contains a '?', and you need to maintain that context, then you need to use '&'. Maybe your app lives in a Virtual Directory.
You might do something like...
var newUrl = location.href;
if (newUrl.indexOf('?') > -1)
newUrl += '&';
else
newUrl += '?';
newUrl += val;
This allows you maintain any existing context as well.
If you expect the ticket to already be defined, you might need to remove that from the query string, if it already exists.
In that case then you might want to do something like...
var params = location.search.substring(1).split('&'),
paramToRemove, indexOfValue,
hasSearch = false,
param;
for (var i = 0, len = i; i < len; i++)
{
param = params[i];
indexOfValue = param.indexOf('value');
hasSearch = param.indexOf('?') === 0;
if (indexOfValue === 0 || (indexOfValue === 1 && hasSearch ))
{
paramToRemove = params[i];
break;
}
}
var newUrl = location.href;
// Remove old value
if (paramToRemove) newUrl = newUrl.replace(paramToRemove, hasSearch ? '?' : '');
// Add proper search char
if (newUrl.indexOf('?') > -1)
newUrl += '&';
else
newUrl += '?';
// Add new value
newUrl += val;
location.href = '/Tickets?val=' + val;
//On page load the server will generate the URL for you.
var ticketURL = '#Url.Action("Index", "Tickets")';
//Append the value to the URL
ticketURL = ticketURL + '?val=' + val;
//Do your stuff!
Since, you are calling Controller methods from javascript. You should make an POST ajax call to Ticket Controller and passing Action method name also.
Your code would be like this:
return $.post('/Ticket(ControllerName)/Index(method name)/',parameters here);
Inside API Controller, Index method will accept the same param which we are passing from our javascript.
ActionResult Index(parameter){...}
I have been trying to figure this out for the past week and everything that i try just doesn't seem to work.
I have to create a web service on my local box that responds to requests. The client (that i did not write) will ask my service one question at a time, to which my server should respond with an appropriate answer.
So the last thing i have to do is:
When a POST request is made at location '/sort' with parameter 'theArray', sort the array removing all non-string values and return the resulting value as JSON.
theArray parameter will be a stringified JSON Array
From going through trail and error i have found out that the parameters supplied is:
{"theArray":"[[],\"d\",\"B\",{},\"b\",12,\"A\",\"c\"]"}
I have tried many different thing to try to get this to work. But the closest thing i can get is it only returning the same thing or nothing at all. This is the code that i am using to get those results:
case '/sort':
if (req.method == 'POST') {
res.writeHead(200,{
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
var fullArr = "";
req.on('data', function(chunk) {
fullArr += chunk;
});
req.on('end', function() {
var query = qs.parse(fullArr);
var strin = qs.stringify(query.theArray)
var jArr = JSON.parse(fullArr);
console.log(jArr); // Returns undefided:1
var par = query.theArray;
console.log(par); // returns [[],"d","B",{},"b",12,"A","c"]
function censor(key) {
if (typeof key == "string") {
return key;
}
return undefined;
}
var jsonString = JSON.stringify(par, censor);
console.log(jsonString); // returns ""
});
res.end();
};
break;
Just to clarify what I need it to return is ["d","B","b","A","c"]
So if someone can please help me with this and if possible responded with some written code that is kinda set up in a way that would already work with the way i have my code set up that would be great! Thanks
Edit: Try this:
var query = {"theArray":"[[],\"d\",\"B\",{},\"b\",12,\"A\",\"c\"]"};
var par = JSON.parse(query.theArray);
var stringArray = [];
for ( var i = 0; i < par.length; i++ ) {
if ( typeof par[i] == "string" ) {
stringArray.push(par[i]);
}
}
var jsonString = JSON.stringify( stringArray );
console.log(jsonString);
P.S. I didnt't pay attention. Your array was actually a string. Andrey, thanks for the tip.
The replacer parameter of JSON.stringify doesn't work quite like you're using it; check out the documentation on MDN.
You could use Array.prototype.filter to filter out the elements you don't want:
var arr = [[],"d","B",{},"b",12,"A","c"];
arr = arr.filter(function(v) { return typeof v == 'string'; });
arr // => ["d", "B", "b", "A", "c"]
edit: one-liner (try it in repl!)
JSON.stringify(JSON.parse(require('querystring').parse('theArray=%5B%5B%5D%2C"d"%2C"B"%2C%7B%7D%2C"b"%2C12%2C"A"%2C"c"%5D').theArray).filter(function(el) {return typeof(el) == 'string'}));
code to paste to your server:
case '/sort':
if (req.method == 'POST') {
buff = '';
req.on('data', function(chunk) { buff += chunk.toString() });
res.on('end', function() {
var inputJsonAsString = qs.parse(fullArr).theArray;
// fullArr is x-www-form-urlencoded string and NOT a valid json (thus undefined returned from JSON.parse)
var inputJson = JSON.parse(inputJsonAsString);
var stringsArr = inputJson.filter(function(el) {return typeof(el) == 'string'});
res.writeHead(200,{
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(JSON.stringify(stringsArr));
};
break;