Passing URL query strings into HTML form fields using Javascript - javascript

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

Related

JSON parsed object and wild card

I have a function that is supposed to check old data against data. I am parsing data and oldData to get a JSON object respectively as dbData and formData are simply strings containing ID's and values for the HTMML form. The purpuse of the function is to check if the user has made any textchanges some textareas in the HTML form. I want to do this by checking the ID for each textarea and then check if the value in formData and Data are the same. In that case no change has been made and the function will return true.
The data string im parsing looks something like this:
"[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\Apple \",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]"
So for example, i have to check the ID for "textarea1" in dbData and formData and then check if the value is the same. Can this be done using wildcard or is there a better way to archive this?
function CheckValues() {
var isChanged = false;
var formData = $.parseJSON(data);
var dbData = $.parseJSON(oldData);
if(formData !== dbData) {
var isChanged = true;
}
return isChanged;
}
The code shown below works in IE9+, Chrome, FireFox but other
browsers yet to test. The example shows two different values, data and
OldData - data contains "Tea" where as OldData contains "OldTea" so
isChanged flag is true.
function CheckValues() {
var data = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"Tea\"}";
var oldData = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"OldTea\"}";
var formData = JSON.parse(data);
var dbData = JSON.parse(oldData);
var oFormData = Object.keys(formData);
var oDbData = Object.keys(dbData);
var isChanged = false;
if (oFormData.length === oDbData.length)
{
for (var i = 0; i < oFormData.length; i++) {
var propName = oFormData[i];
if (typeof (dbData[propName]) === "undefined") {
isChanged = true;
break;
}
else {
if (formData[propName] !== dbData[propName]) {
isChanged = true;
break;
}
}
}
}
}

Put XMLHttprequest results into one string

I'm trying to get my array of URL's to run through a JQuery .get function to get the site's source code into one string outside of the function. My code is below.
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var get = $.get(fetch, function(sourcecode) {
sourcecode = fetch;
}
I need the sourcecode variable to be the combination of source code on all of the URLs in the array.
You need to put a variable outside of the function, something like this data variable below and append to it with +=:
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var data = null;
var get = $.get(fetch, function(sourcecode) {
data += fetch;
}
}
Try this like,
var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
var data='';
$.ajax({
url:fetch,
async:false,
success : function(d){
data=d;
}
});
return data;
}).get();
Since you're using jQuery, I suppose that jQuery.each() may be a better way to iterate over the array.
var URL = ["http://website.org", "http://anothersite.com"];
var str = [];
$.each(URL, function(index, fetch) {
$.get(fetch, function(sourcecode) {
str.push(sourcecode); // if you want an array
})
});
str.join(''); // if you want a string
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to send json and parse it on next html page through url in jquery?

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.

How do I loop through a json collection of strings with Mustache?

The MVC that creates the array of strings is
public JsonResult GetInvalidFilesAJAX(JQueryDataTableParamModel param)
{
string[] invalidFiles = new string[] { "one.xls", "two.xls", "three.xls" };
return Json(new
{
Status = "OK",
InvalidFiles = invalidFiles
});
}
And the javascript that should loop through and print out each string is
$.ajax(
{
type: 'POST',
url: 'http://localhost:7000/ManualProcess/GetInvalidFilesAJAX',
success: function (response) {
if (response.Status == 'OK') {
//Use template to populate dialog with text of Tasks to validate
var results = {
invalidFiles: response.InvalidFiles,
};
var template = "<b>Invalid Files:</b> {{#invalidFiles}} Filename: {{invalidFiles.value}} <br />{{/invalidFiles}}";
var html = Mustache.to_html(template, results);
$('#divDialogModalErrors').html('ERROR: The following files have been deleted:');
$('#divDialogModalErrorFiles').html(html);
How do I refer to the string in the array? The way above is not correct. All the example I find seem to be for when the Jason collection has property names.. in my case it is just a key value pair (I guess?)
There is no built in way. You must convert the JSON into an array or loop through the data yourself, e.g,
var data = JSON.parse(jsonString); // Assuming JSON.parse is available
var arr = [];
for (var i = 0, value; (value = data[i]); ++i) {
arr.push(value);
}
Alternatively:
var arr = [];
for (var prop in data){
if (data.hasOwnProperty(prop)){
arr.push({
'key' : prop,
'value' : data[prop]
});
}
}
And then to display it:
var template = "{{#arr}}<p>{{value}}</p>{{/arr}}";
var html = Mustache.to_html(template, {arr: arr});
This is assuming your JSON Object is one level deep.

How to get part of string?

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);
}​

Categories