Showing Javascript variables in a modal - javascript

On my website I'm trying to make a modal that informs the user of their username (generated from their forename and surname) and informs the users that they have been added to a moderation que for their account to be approved. I create the account within a php file called with ajax and then use JSON to feedback a integer that informs the javascript if the process was successful and if so what the user's username is. My modal opens fine if the account was created and the information is displayed about the approval process, however I cannot seems to get it to display the section with the username in. Can you try and see where I'm going wrong.
Javascript
var RegisterSuccess = new Array();
var RegisterSuccess = JSON.parse(Feedback);
if (RegisterSuccess[0] == 0){
$('#mdlInfo').html('<p>Your account has been created under the username: "<strong><span id="spnUsername"></span></strong>". You <strong>must</strong> remember this as you will require it to login to your account.</p>');
$('#mdlInfo').html('<p>Your account has also been added to a moderation que. You must wait until a member of staff activates your account!</p>');
$('#spnUsername').html(RegisterSuccess[1]);
$("#mdlRegister").modal("show");
PHP Output code
$Feedback = json_encode(array($RegisterSuccess, $username));
echo $Feedback;
Thanks in advance!

Why don't you just return a proper json_encoded array from PHP? No need to assign a variable, just do
echo json_encode(["success"=>"true","username"=>"$username"]);
and in the javascript (no need to assign the RegisterSuccess as array either), just do
var returnValue = JSON.parse(Feedback);
(you should avoid calling the variable RegisterSuccess - chose a neutral name so you can use it for both success and error without issues. Then just do
$('#mdlInfo').html('<p>Your account has been created under the username: <strong><span id="spnUsername">'+returnValue['username']+'</span></strong>. You <strong>must</strong> remember this as you will require it to login to your account.</p><p>Your account has also been added to a moderation que. You must wait until a member of staff activates your account!</p>');
$("#mdlRegister").modal("show");

Related

How to submit a form and execute javascript simultaneously

As a follow-up to my last question, I have run into another problem. I am making a project on google homepage replica. The aim is to show search results the same as google and store the search history on a database. To show results, I have used this javascript:-
const q = document.getElementById('form_search');
const google = 'https://www.google.com/search?q=';
const site = '';
function google_search(event) {
event.preventDefault();
const url = google + site + '+' + q.value;
const win = window.open(url, '_self');
win.focus();
}
document.getElementById("s-btn").addEventListener("click", google_search)
To create my form, I have used the following HTML code:-
<form method="POST" name="form_search" action="form.php">
<input type="text" id="form_search" name="form_search" placeholder="Search Google or type URL">
The terms from the search bar are to be sent to a PHP file with the post method. I have 2 buttons. Let's name them button1 and button2. The javascript uses the id of button1 while button2 has no javascript and is simply a submit button.
The problem is that when I search using button1, the search results show up but no data is added to my database. But when I search using button2, no results show up( obviously because there is no js for it) but the search term is added to my database. If I reverse the id in javascript, the outcome is also reversed. I need help with making sure that when I search with button1, it shows results and also saves the data in the database. If you need additional code, I will provide it. Please keep your answers limited to javascript, PHP, or HTML solutions. I have no experience with Ajax and JQuery. Any help is appreciated.
Tony since there is limited code available so go with what you had stated in your question.
It is a design pattern issue not so much as so the event issue.
Copy pasting from Wikipedia "software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. Rather, it is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system."
So here is how things play out at present;
forms gets submitted to specific URL i.e. based on action attribute
Requested page gets Query sting in php and lets you play around with it
then from there on .....
3. either you get results from database and return response
4. or you put search request into database and return success response
Problem statement
if its 3 then search request is not added to database if its 4 then results in response to search request are not returned.
Solution
you need to combine both 3 and 4 in to one processing block and will always run regardless of the search query is.
So our design pattern could use mysql transaction so whole bunch of queries would run a single operation example
$db->beginTransaction(); // we tell tell mysql we will multiple queries as single operation
$db->query('insert query');
$results= $db->query('search query');
$db->commit(); // if we have reached to this end it means all went fine no error etc so we commit which will make database record insert query into database. If there were errors then mysql wont record data.
if($results) {echo $results;} else {echo 'opps no result found';}
slightly more safe version
try {
$db->beginTransaction(); // we tell tell mysql we will multiple queries as single operation
$db->query('insert query');
$results= $db->query('search query');
$db->commit(); // if we have reached to this end it means all went fine no error etc so we commit which will make database record insert query into database. If there were errors then mysql wont record data.
if($results) {echo $results;} else {echo 'opps no result found';}
} catch (\Throwable $e) {
// An exception has been thrown must rollback the transaction
$db->rollback();
echo 'oho server could not process request';
}
We have effectively combined two query operation into one always recording into database and always searching in database.

AngularJS + PHP Login authentication

I'm building a WebApp where i have a login page and also some user restrictions.
I have my app running perfect but now I'm stuck in the login process.
The WebApp is based on AngularJs, PHP and a database with MYSQL.
Also, I'm asking this because i didn't found any good answer or work process on the first steps of the login process. Also keep in mind I'm not an AngularJs advanced user, I'm still learning, so sorry if I'm making somethins stupid.
What i have:
Right now I have a simple login system (working) using only PHP, like this:
index.php
<?php session_start();
include ('dist/php/config.php');
if(isset($_GET['out'])){
session_destroy();
back("#");
}
if((!empty($_POST['user'])) && (!empty($_POST['password']))){
$p = ['user'=>$_POST['user'], 'password'=>$_POST['password']];
$r = sql("select * from users where user= :user and password = :password",$p);
if($r != 0){
foreach($r as $ln){
$_SESSION['loggedin']=$ln['name_user'];
}
} else {
$msg = "<div class='login_fb'><p>User or password incorrect</p></div>";
}
}
if(!empty($_SESSION['loggedin'])){
include "system.php";
} else { ?>
<head>
<meta charset="UTF-8" />
[... rest of head ...]
</head>
<body>
[... rest of body with login form ...]
</body>
<?php } ?>
My routing system is controlled with AngularJs ui-router.
The problem this system (at least i don't know how to do it) is to keep the user data reusable even after the page refresh.
My objective
What i want is:
Login into the WebApp;
Store user data to be used in all pages; For example, it's name or it's ID;
Be able to refresh the page and don't lose the logged state;
Control the user access based on it's power level (master, admin, user, guest);
Secure Login system;
Prevent users to access a further page when changing the URL manually. For example: Typing webapp.com/#/order and with this they jump the login process;
I've alreay found some examples, but they are way to complex (i mean, lack of explanation or plain code), or have some of these failures. I also found this great answer here but it already start the explanation with user logged in.
Also, i saw some reference to use $cookieStore (or just $cookie, since it's deprecated) like this:
app.run(['loginService', function(loginService){
var username = $cookieStore.get('username');
var password = $cookieStore.get('password');
loginService.login(username, password);
}]);
But is it ok to use this code? Is it safe? Because we'll have to handle the password value.
What i want to know
So, with this is mind, what i want to know is:
Is it ok, recommended or is there a better option to handle the login process than the one I'm using at the momment?
How can i prevent the users to access the WebApp without the login process?
How can i store the user data to control it's access to restricted areas or to just simple show a message with his name?
How to keep the user logged in even after the refresh?
If it's okay to stay using the same login system I'm using now, how can i keep the user information reusable trought all the other pages and also keep it reusable after a page refresh?
Hope you guys can help me.

Calling: GetRespondentEmail Specific

The following code is used to send an email to the respondent of a google form. The onsubmit call is from the spreadsheet that stores the responses.
I am not sure how to get the forms ID to use the solution given in several other places. Basically I just need to know how to call the getRespondentEmail(). I've tried calling it using FormApp.getActive() but I read that only works when you are working in the form it's self.
If you want to offer a solution that requires using the form ID, an explanation of how to get the ID would be great.
var GetUserEmail = getRespondentEmail().
var subject = "Skiver Production Report Successfully Submitted";
var textbody = "You have successfully submitted a Skiver Production Report. Do not reply to this email as it is not monitored.";
var message = "You have succesfully submitted a Skiver Production Report. Do not reply to this email as it is unmoinitored." ;
var cc = "techlab#worldwidefoam.com";
var sendername = "Quality Function";
GmailApp.sendEmail("bob#notArealemail.com", subject, textbody, {
cc: cc,
name: sendername,
htmlBody: message
});
To get the id of an element you can simply use the document.getElementById(arg) method. For example:
var myForm = document.getElementById("ID");
For simply calling getRespondentEmail you just place getRespondentEmail() in your code. Your first line is doing this correctly but the . at the end needs to be removed or replaced with a ;, which is likely causing your error:
var GetUserEmail = getRespondentEmail(); // replace . with ;
Lastly if you would like to use getRespondentEmail() anywhere make sure it is in a global scope. Meaning it's not defined in any functions or closures.

LoadRunner parameterization multiple columns

I am using LoadRunner true client AJAX protocol for recording purpose.
I have successfully recorded the script and tried to create a parameter in a table (text file) containing username and password as column names.
The text file has a name username by itself.
In the Vuser script when I create a JavaScript variable like this:
login_name=LR.getParam("username")
I replaced the username with above parameter and it works fine, but for password I am not able to create a separate variable to pass. It is passing the same username into password box and login fails.
What is my mistake, what do I need to change in the parameter list to update the password?
loadrunner encrypts the password by default look for lr_decrypt in the script , right click on the argument inside this function and select restore original value .
now select the restored value and parametrise it. it works:)

How to save entered text in JS/Html

How do i save entered/ inputted text using JavaScript/ html.
What do I want:
Name or code etc to be entered in a box (prompt box eksample) and then I want it to be displayed/ printed on the page and I want it to remain there so other people that visit can see it.
What I have:
I have code that shows a prompt box where you can enter text then displays it in green. However what i want is for the entered text to remain on the website for others to see...
function mobCode() {
mobCode = prompt("Insert Code", "Code here");
document.getElementById("mC").innerHTML = mobCode;
document.getElementById("mC").style.color="green";
}
<p id="mC"> Mob Code </p>
<button type="button" onclick="mobCode()"> Click to Add </button>
What you will probably have to do is write a script that will send the entered input to a database you build which can store that information,and then have your js access the database to display it in a certain area of your page.
Check out this Q & A one of the answers is a nice article to help explain the idea behind it: Send data from javascript to a mysql database
If you want to deal easier with persistence of the data, instead of setting up database and using server side script you can look at Facebook's Parse. The free plan is quite usefull for small projects. There is a JavaScript SDK that can be used directly from your javascript code.
Also you can view statistics from the Parse dashboard.
Here is some saple code for example:
// Create a new Parse object
var Post = new ParseObject("Post");
var post = new Post();
// Save it to Parse
post.save({"title": "Hello World"}).then(function(object) {
alert("Yay! It worked!");
});

Categories