I'm new here and I need help.
I need to build a system of students who log in through a JSON file.
After connecting, the user is redirected to his personal page with all his details. When the user is redirected, a blank page is loaded, and I can't figure out how i pause the running script until the page loaded complete. I would appreciate it if you could help me.
this is my js code:
ocument.querySelector('form').addEventListener('submit', (evt) = >{
evt.preventDefault();
let usernameContent = document.querySelector('#input-login').value;
let pwContent = document.querySelector('#input-pw').value;
tryusername(usernameContent, pwContent);
})
function tryusername(username, password) {
let usernameFound = false;
fetch('db.json').then(response = >response.json()).then(data = >{
data.forEach(element = >{
if (username === element.username) {
usernameFound = true;
if (password === element.password) {
//alert('access granted');
//console.log(data);
clearInputs();
var res = Object.entries(element);
console.log(res);
for (let i = 0; i < res.length; i++) {
window.open("/test.html");
let FirstName = res[0];
let LastName = res[1];
let ID = res[2];
let Mobile = res[3];
let Email = res[4];
let Uname = res[5];
let Type = res[7];
let department = res[8];
let Year = res[9];
document.getElementById("User").innerHTML = Uname;
document.getElementById("FirstNamee").innerHTML = FirstName;
document.getElementById("Email").innerHTML = Email;
document.getElementById("LastName").innerHTML = LastName;
document.getElementById("ID").innerHTML = ID;
document.getElementById("Mobile").innerHTML = Mobile;
document.getElementById("Type").innerHTML = Type;
document.getElementById("department").innerHTML = department;
document.getElementById("Year").innerHTML = Year;
}
}
else {
alert('password incorrect. access denied');
clearInputs();
}
}
});
if (!usernameFound) {
alert('login not registered');
}
})
}
function clearInputs() {
document.querySelector('#input-login').value = '';
document.querySelector('#input-pw').value = '';
}
</head>
<body >
<form action="#" method="post">
<label for="login">
<p>Login:</p>
<input id="input-login" type="text" name="login" id="login" placeholder="Insert your login" required>
</label>
<label for="pw">
<p>Password:</p>
<input id="input-pw" type="password" name="password" id="pw" placeholder="Insert your password" required>
</label>
<input id="button-submit" type="submit" value="Submit">
</form>
<script src="fetch.js"></script>
</body>
</html>
Related
Long story short:
<form action="example.com/" method="get">
<input type="hidden" name="q" value="one,two,">
<input type="text" name="q">
</form>
The goal is that, when the user inputs e.g. "three", the website
example.com/?q=one,two,three
is called, instead of example.com/?q=one,two,&q=three.
A solution without JavaScript would be ideal, but I suspect that's not possible.
Thank you so much!
If you don't mind using an array then you can try using this solution
<form action="example.com/" method="GET">
<input type="hidden" name="q[]" value="one">
<input type="hidden" name="q[]" value="two">
<input type="text" name="q[]">
<input type="submit" name="submit">
</form>
this way you will get an array of values on submit then you can handle it on server side. But if you just still want to use your method then Javascript is required. With javascript you can get formdata then append the user input to the form then send it using ajax.
Yes, it's not possible without using Javascript as far I know.
it's better if you handle this at the backend.
But, if you really want to do at the front-end, you can do as follows (With vanilla Javascript).
document.addEventListener("DOMContentLoaded", function(){
let form = document.getElementById('form');
let query = '';
let valueObj = {};
if(form){
form.addEventListener('submit', (e) => {
e.preventDefault();
let exceptinput = ['submit','reset','button','file','image'];
let allElem = e.srcElement;
if(allElem.length > 0){
createValueObj(allElem, valueObj, exceptinput).then(data => {
console.log(data);
query = serialize(data);
window.location = 'http://www.example.com/?' + query;
}).catch(err => {
console.log(err);
})
}
});
}
let serialize = (obj) => {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
let insertValueToObj = (key, value, obj) => {
if(obj[key]){
obj[key] = obj[key]+','+ value;
}else{
obj[key] = value;
}
return obj;
}
let createValueObj = (arr, obj, exceptinput) => {
return new Promise((resolve, reject)=>{
for (let index = 0; index < arr.length; index++) {
let isProperInput = exceptinput.includes(arr[index].type);
if(!isProperInput) {
let key = arr[index].name;
let value = arr[index].value.trim();
obj = insertValueToObj(key, value, obj);
}
if(index == (arr.length -1)){
resolve(obj);
}
}
});
}
});
thanks.
would like to know if there is a way to upload files at public folder using vuejs coding
I do have a code but it is build to move the file at laravel public folder. do vuejs have that kind of function?
here are what i have so far on my function. hope you guy's can help me
form code
<!-- Form Upload -->
<div class="row">
<div class="col-sm-6 offset-3">
<div class="form-group">
<label for="exampleFormControlFile1">Upload</label>
<input
type="file"
ref="file"
class="form-control-file"
#change="onFileChange"
>
<small class="text-muted">
for slideshow images
<br />
size: 1280 x 630 pixel for good quality
</small>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-primary"
data-dismiss="modal"
#click="uploadFile"
:disabled="disableBtn"
>Upload</button>
</div>
method code
onFileChange(e) {
this.file = this.$refs.file.files[0];
},
uploadFile() {
if (this.file == "") {
this.alertClass = "alert alert-danger";
this.alertMessage = "Please select a file";
this.showAlert = true;
} else {
this.disableBtn = true;
this.$parent.showLoading();
let requestUrl =
this.baseUrl + "/media";
let formData = new FormData();
formData.append("file", this.file,);
formData.append("mediatype", this.Mediatype);
let headers = {
headers: {
"Content-Type": "multipart/form-data"
}
};
this.$http
.post(requestUrl, formData, headers)
.then(response => {
this.alertClass = "alert alert-success";
this.alertMessage = response.data.message;
this.$refs.file.value = ''
this.showAlert = true;
this.$parent.hideLoading();
this.disableBtn = false;
this.$parent.getGallery();
})
.catch(() => {
this.disableBtn = false;
this.$parent.hideLoading();
this.alertClass = "alert alert-danger";
this.alertMessage =
"There is a problem in the request.";
this.showAlert = true;
});
}
}
//Follow this instruction
File
<input
type="file"
ref="image2"
v-on:change="handleFilesUpload()"
/>
In methods properties
handleFilesUpload() {
let uploadedFiles = this.$refs.image2.files;
let fileExtension = uploadedFiles[0].name.replace(/^.*\./, "");
//console.log("fileExtension", fileExtension);
let allowedExtensions = /(\.jpg|\.JPG|\.jpeg|\.JPEG|\.png|\.PNG|\.pdf|\.PDF|\.doc|\.docx)$/i;
if (!allowedExtensions.exec(uploadedFiles[0].name)) {
var message = "You can upload jpg, jpeg, png, pdf and docx file only";
this.$refs.image2.value = "";
this.documentFiles = [];
} else {
//console.log("uploadedFiles[i] = ", uploadedFiles[0]);
//Upload for single file
this.documentFiles = uploadedFiles;
//Upload for multiple file
/*
for (var i = 0; i < uploadedFiles.length; i++) {
this.documentFiles.push(uploadedFiles[i]);
}
*/
}
},
// After submit form
validateBeforeSubmit(e) {
let formData = new FormData();
for (var i = 0; i < this.documentFiles.length; i++) {
let file = this.documentFiles[i];
formData.append("files[" + i + "]", file);
}
axios.post('laravel-api-url', formData)
.then(res => {
console.log({res});
}).catch(err => {
console.error({err});
});
},
--In Laravel controller function--
public function save($request){
$total = #count($_FILES['files']['name']);
if ($total>0)
{
$allFiles = $this->uploadFiles($request);
$data['document_file_name'] = ($allFiles) ? $allFiles[0] :
$result = CreditMaster::create($data);
if ($result) {
return response()->json(array('status' => 1,
'message' => 'Data saved successfully!'));
} else {
return response()->json(array('status' => 0, 'message' => 'Save failed!'));
}
}
}
public function uploadFiles($request)
{
$storeFileName = [];
$total = #count($_FILES['files']['name']);
$diretory = '/save_directory_name/';
$path = public_path() . $diretory;
$fileForMate = time() . '_';
for ($i = 0; $i < $total; $i++) {
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
if ($tmpFilePath != "") {
$fileName = $fileForMate . $_FILES['files']['name'][$i];
$newFilePath = $path . $fileName;
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
array_push($storeFileName, $diretory.$fileName);
}
else
{
return $_FILES["files"]["error"];
}
}
}
return $storeFileName;
}
I have created Username and password field in login page and using mysql database with entity framework in asp.net page.
Here is my asp.net code:
<asp:TextBox ID="txtUsername" class="form-control" runat="server" placeholder="Username" required=""></asp:TextBox>
<asp:TextBox ID="txtPassword" class="form-control" TextMode="Password" runat="server" placeholder="Password" required=""></asp:TextBox>
<asp:Button ID="btnLogin" class="btn btn-primary block full-width m-b" runat="server" Text="Sign In" OnClick="btnSubmit_Click" />
Here is my code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUsername.Text != null)
{
Response.Write("<script>alert('Your username is correct!!!')</script>");
}
else
{
Response.Write("<script>alert('Please enter the Username!!!')</script>");
}
if (txtPassword.Text != null)
{
Response.Write("<script>alert('Your password is correct!!!')</script>");
}
else
{
Response.Write("<script>alert('Please enter the password!!!')</script>");
}
contractmanagement_dbEntities dbEntities = new contractmanagement_dbEntities();
var UserName = txtUsername.Text;
var Password = txtPassword.Text;
var login = from M in dbEntities.adminlogins.Where(M => M.Username == UserName && M.UserPassword == Password) select M;
if (login.Count() > 0)
{
var username = txtUsername.Text;
Session["username"] = username;
Response.Redirect("index.aspx");
}
else
{
Response.Write("<script>alert('Username or password is not Valid!!!')</script>");
}
}
In code behind I have set not equal to null for both username and password so how to show the error message like Please enter the username and Please enter the password if the respective username and password is empty?
You can add a hidden label for message on top of your login page and then in the code behind you can set its text to "your desired message" and make it visible like so :
txtLabel.Text = "Your desired message";
txtLabel.Visible = true;
Also, you have to move your login code to if block when both the username and password are not empty:
if((txtUsername.text != null) && (txtPassword.Text != null))
{
contractmanagement_dbEntities dbEntities = new contractmanagement_dbEntities();
var UserName = txtUsername.Text;
var Password = txtPassword.Text;
var login = from M in dbEntities.adminlogins.Where(M => M.Username == UserName && M.UserPassword == Password) select M;
if (login.Count() > 0)
{
var username = txtUsername.Text;
Session["username"] = username;
Response.Redirect("index.aspx");
}
else
{
txtLabel.Text = "Invalid Username or password";
txtLabel.Visible = true;
}
}
How can we pass this parameter to an MVC Controller ??
I am doing a dropdown of my entity and department wherein if I choose that entity, the department under it will be shown on the next dropdown for me to filter my data.
Here's my angular in view
scope.getEntity = http.get('GetEntity').success(function (entity) {
scope.entities = entity;
});
scope.selectEntity = function () {
var e = document.getElementById("entityList");
var entity = e.options[e.selectedIndex].value;
console.log(entity);
};
scope.getDepartment = http.get('GetDepartment').success(function (dept) {
scope.depts = dept;
});
here's my model wherein I get the data from my db.
public static List<string[]> LoadEntities()
{
string sScript = "SELECT [EntityID],[EntityName] FROM [NOP_PR].[dbo].[Entities] where LocationID=39 or LocationID=21";
List<string[]> results = new List<string[]>();
using (SqlConnection con = new SqlConnection(m_sConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(sScript, con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string[] r = new string[] { reader.GetInt64(0).ToString(), reader.GetString(1) };
results.Add(r);
}
}
}
return results;
}
public static List<string[]> LoadDepartment(string EntityID)
{
string sScript = "SELECT [DepartmentID],[DepartmentName] FROM [NOP_PR].[dbo].[Departments]"
+ " WHERE EntityID=" + EntityID + ";";
List<string[]> results = new List<string[]>();
using (SqlConnection con = new SqlConnection(m_sConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(sScript, con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string[] r = new string[] {
reader.GetInt64(0).ToString(),
reader.GetString(1) };
results.Add(r);
}
}
}
return results;
}
Here's my Controller
public JsonResult GetDepartment(string EntityID)
{
return Json(NomsConnection.LoadDepartment(EntityID), JsonRequestBehavior.AllowGet);
}
public JsonResult GetEntity()
{
return Json(NomsConnection.LoadEntities(), JsonRequestBehavior.AllowGet);
}
And my view
<div class="col-xs-4">
<div class="col-xs-10">
<h4><b>Search :</b></h4>
<div class="input-group">
<span class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</span>
<input type="text" name="search" data-ng-model="filter" class="form-control" placeholder="Search here (e.g. 151234 or Pille)" />
</div>
<br />
</div>
<div class="btn-group" role="group">
<button data-ng-click="exportData()" class="btn btn-warning"><i class="glyphicon glyphicon-export"></i>Export to Excel </button>
</div>
</div>
</div>
Hoping for someone to help !
To answer my problem, here is what I did.
PRApp.controller('DepartmentCtrl', ['$scope', '$http', function (scope, http) {
scope.EntityID = "";
scope.getEntity = http.get('GetEntity').success(function (entity) {
scope.entities = entity;
});
scope.selectEntity = function () {
var e = document.getElementById("entityList");
scope.EntityID = e.options[e.selectedIndex].value;
};
scope.getDepartment = http.get('GetDepartment?EntityID=' + scope.EntityID).success(function (dept) {
scope.depts = dept;
});
scope.loadDept = function () {
scope.selectEntity();
console.log(scope.EntityID);
scope.depts = null;
http.get('GetDepartment?EntityID=' + scope.EntityID).success(function (dept) {
scope.depts = dept;
});
}
scope.loadReport = function () {
scope.selectEntity();
console.log(scope.EntityID);
scope.depts = null;
http.get('GetDepartment?EntityID=' + scope.EntityID).success(function (dept) {
scope.depts = dept;
});
}
}]);
I created new controller for it.. ( optional only)
And added this code on my controller (MVC)
public JsonResult GetReportList(string from, string to, string EntityID="", string DepartmentID="")
{
DateTime fromd = DateTime.Now;
DateTime tod = DateTime.Now;
if (from != "undefined")
fromd = Convert.ToDateTime(from);
if (to != "undefined")
tod = Convert.ToDateTime(to);
fromd = new DateTime(fromd.Year, fromd.Month, 1, 0, 0, 0);
tod = new DateTime(tod.Year, tod.Month, tod.Day, 23, 59, 59);
return Json(NomsConnection.LoadPRfromDB_withParams(fromd, tod, EntityID, DepartmentID), JsonRequestBehavior.AllowGet);
}
public JsonResult GetDepartment(string EntityID)
{
return Json(NomsConnection.LoadDepartment(EntityID), JsonRequestBehavior.AllowGet);
}
public JsonResult GetEntity(string entity)
{
return Json(NomsConnection.LoadEntities(), JsonRequestBehavior.AllowGet);
}
And added this on my view to generate the dropdown
<div class="col-xs-12" data-ng-controller="DepartmentCtrl">
<h4><b>Search by Entity :</b></h4>
<select id="entityList" data-ng-click="loadDept()" class="form-control">
<option value="" selected>-- Select Entity --</option>
<option data-ng-repeat="e in entities" value="{{e[0]}}">{{e[1] | uppercase }}</option>
</select>
<h4><b>Search by Department :</b></h4>
<select id="deptList" class="form-control" data-ng-model="filter.DepartmentName">
<option value="" selected>-- Select Department --</option>
<option data-ng-repeat="t in depts" value="{{t[0]}}">{{t[1] | uppercase }}</option>
</select><br />
<input type="submit" class="btn btn-primary btn-sm" value="GO" />
</div>
That's it. I hope it helped !
You need to make your get-request dynamic by transfering additional parameters, and process this request in your backend "controller":
scope.getEntity = http.get('GetEntity', params: scope.selectEntity()).
success(function (entity) {
scope.entities = entity;
});
And in your controller process the JSONified entity parameter:
public JsonResult GetEntity(String entity)
{
//FIXME: do sth here with the entity parameter
return Json(NomsConnection.LoadEntities(), JsonRequestBehavior.AllowGet);
}
according with the angular documentation you should be using the $http service passing 'params', so:
$http({
url: 'yourUrl',
method: "GET",
params: {'EntityID': yourEntityId}
});
Hy, I'm stuck with this error message and I can not find an solution.
I get this message error in the Knockout JavaScript library v2.2.0:
Unhandled exception at line 1053, column 5 in
localhost:port/Scripts/knockout-2.2.0.debug.js 0x800a138f -
Microsoft JScript runtime error: Invalid operand to 'in': Object
expected If there is a handler for this exception, the program may be
safely continued.
It stops at this line of code in knockout-2.2.0.debug.js
if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
I use this WebApi:
public class ProductsController : ApiController
{
IEnumerable<Product> products = new List<Product>()
{
new Product { Id = 1, Name = "Tomato_Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts(){
return products.AsEnumerable(); }
The scripts that I use are in a header section
#section Testscripts
{
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/knockout-2.2.0.debug.js"></script>
}
And the Knockout code in the footer default script section
#section scripts
{
<script type="text/javascript">
var apiUrl = '#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "products" })';
function Product(data) {
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
this.Price = ko.observableArray(data.Price);
this.Category = ko.observable(data.Category);
}
function ProductViewModel() {
var self = this;
self.myproducts = ko.observableArray([]);
$.getJSON(apiUrl, function (allData) {
var mappedProducts = $.map(allData, function (item) { return new Product(item) });
self.myproducts(mappedProducts);
});
};
ko.applyBindings(new ProductViewModel);
}
and show the data in body:
<ul data-bind="foreach: myproducts">
<li>
<input data-bind="value: Id" />
<input data-bind="value: Name" />
<input data-bind="value: Category" />
<input data-bind="value: Price" />
</li>
</ul>
The bug is in your Product function.
You want to create an ko.observableArray from data.Price which is a decimal value and not an array of values, which results in this not so nice exception.
Change to ko.observable and it should work:
function Product(data) {
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
this.Price = ko.observable(data.Price);
this.Category = ko.observable(data.Category);
}