I want the script to read the global element, detect if its value equals 1 and if so, display a load of text but for some reason it doesn't seem to work.
var z = sessionStorage["system"]
if (z == 1) {
document.getElementById("titlesystem").innerHTML = "Your System";
document.getElementById("bodysystem").innerHTML = "Amazing!
}
<h2 id="titlesystem"></h2>
<p id="bodysystem"></p>
If I understand it right, you want to read some value stored in session (in php stored in $_SESSION) as a client from javascript.
First: session is server-side thing, clients don't know that they are in session.
But there is a way, how to send value.
This is what came to my mind:
<h2 id="titlesystem"></h2>
<p id="bodysystem"></p>
<input type="hidden" value=<?php echo $_SESSION["value"]?> id="mySessionValue">
<script>
var sessionValue = document.getElementById("mySessionValue").value;
if (sessionValue == 1)
{
document.getElementById("titlesystem").innerHTML = "Your System";
document.getElementById("bodysystem").innerHTML = "Amazing!"
}
</script>
Related
I have a list of scientific publications displayed on a website and would like to load additional content as the user arrives at the end of a list of 10 publications, and presses a button to load another 10 publications.
I make an Ajax call to load the next 10 publications
I am trying to display html code that is echo-ed from php script but I cannot appear to display the html. In the console, I am getting '1' as a value for my HTML. I do not understand:
1. why I am getting the value of '1';
2. Also, is it good practice to echo HTML to be displayed via javascript?
JS (AJAX call):
var resp = xmlhttp.responseText;
var respArray = resp.split('|');
var response = respArray[1];
var publicationList = respArray[0];
var currentHTML = document.getElementById('showPubs').innerHTML;
if(response == '1'){
console.log('more publications available');
var currentHTML = document.getElementById('showPubs').innerHTML;
document.getElementById('showPubs').innerHTML += publicationList;
}else{
document.getElementById('showPubs').innerHTML += '<div id="noMorePub">No more publications</div>';
}
PHP:
$recentPublications .= '
<div id="pub'.$articleID.'" class="pub20">
<div class="divImg">'.$avatarPathHTML.'</div>
<div class="contentPub">
<div class="datepub">
<div class="fullName"><a class="sfullNme" href="2profile.php?username='.$articleUsername.'">'.$fullname.'</a></div>
<div class="date">'.$submitDate.'</div>
</div>
<div class="divLink">
'.$articleTitle.'
</div>
<div class="authorString">'.$author_string.'</div>
</div>
<hr class="pubSeparator">
</div>
';
echo $recentPublications.'|1';
I guess better idea is not use this dirty hack
echo $recentPublications.'|1';
and
var respArray = resp.split('|');
var response = respArray[1];
var publicationList = respArray[0];
if(response == '1'){
You can just check length of response. if length of response is equal 0 bytes then other publications are not available.
The good practice is to separate concerns. Therefore, in your example, server-side script should only provide data to be displayed (ex. JSON via), and frontend should make AJAX call to specific endpoint.
I am developing one quiz game in which I have set of rules. For every correct question user should get +3 marks, so I have define one variable. One page and have set the value, but I don't know how to carry to next page
function Question1cont() {
var mark;
var x = document.getElementById("fermi").checked;
var y= document.getElementById("Newton").checked;
var z= document.getElementById("Angstrom").checked;
var q= document.getElementById("Tesla").checked;
if ( x === true)
{
mark = 3;
}
if ( y === true)
{
mark = -1;
}
if ( z === true)
{
mark = -1;
}
if ( q === true)
{
mark = -1;
}
if ( y === false && z=== false && q === false && x=== false )
{
mark = 0;
alert ( "please any answer then continue");
return false;
}
window.location = "file:///C:/Users/dell/Desktop/practice/images/Question_2.html";
}
You want to send the results of the form to the subsequent page. There is where you do the work to determine the value of what just got passed in.
Alternately, you can have a hidden object where you place the value, and send that as part of the form:
<input type="hidden" id="values" name="values" value="">
As it stands right now, you are trying to send the whole thing to "location"
window.location = "file:///C:/Users/dell/Desktop/practice/images/Question_2.html";
That will not pass anything along. You need to send your form with a action="Question_2.html" on it
I don't see in your code where your form is in the HTML. Presumably you have a tag like this:
<form name="thisform" action="Question_2.html" method="POST">
Have you considered having all the "pages" in one HTML document? Then you wouldn't have to worry about passing state/variables around between pages:
<div id="page1" style="display:none">
<input type="checkbox" id="fermi" />
<input type="checkbox" id="Newton" />
</div>
<div id="page2" style="display:none">
<!-- Other questions here -->
</div>
<script type="text/javascript">
QuestionCheck();
// Code here to hide one div tag and show the other, etc
</script>
Another way is to pass variables via the query string of the URL. https://www.google.com/search?q=javascript+read+query+string
If this is being hosted on a server, then you'll be able to use the localStorage JavaScript object https://developer.mozilla.org/en/docs/Web/API/Window/localStorage (I'm not sure it works when running local files).
I have a form, which uses the following input towards the end:
<input type="hidden" id="ct_count" name="ct_count" value=""/>
The initialisation of the form is:
<form action="email_submission.php" method="post" id="form1" onsubmit="mySubmit();">
And the mySubmit function is:
function mySubmit() {
document.getElementById('ct_count').value = ct;
document.getElementById("form1").submit();
}
When i hit submit, I want to pass the value of ct, which is a variable count on the page, to email_submission.php and store it in a session variable. The session variable is returning blank on every submit, and i'm unsure if the value of the "ct" variable used is being passed through on the hidden field.
Is someone able to pick up where i'm going wrong? There are already variables stored correctly through this, so it's not my session settings as far as i know.
tldr: What's the correct way to take a javascript variable count and pass it through form submit to php?
EDIT:
this is the code for adding fields.
intiial loop for the variable "ct"
function new_link()
{
ct++;
<?php $ct = $ct + 1; ?>
document.getElementById("sec4_lender").setAttribute('name', 'sec4_lender_<?php echo $ct;?>');
document.getElementById("sec4_balance").setAttribute('name', 'sec4_balance_<?php echo $ct;?>');
document.getElementById("sec4_termdate").setAttribute('name', 'sec4_lender_<?php echo $ct;?>');
document.getElementById("sec4_security").setAttribute('name', 'sec4_security_<?php echo $ct;?>');
document.getElementById("sec4_description").setAttribute('name', 'sec4_description_<?php echo $ct;?>');
document.getElementById("sec4_status").setAttribute('name', 'sec4_status_<?php echo $ct;?>');
document.getElementById("sec4_repayment").setAttribute('name', 'sec4_repayment_<?php echo $ct;?>');
document.getElementById("sec4_repayment2").setAttribute('name', 'sec4_repayment_2_<?php echo $ct;?>');
var div1 = document.createElement('tr');
div1.id = 'sect4busloan_div_'+ct+'';
// link to delete extended form elements
var delLink = '<tr style="text-align:right;margin-right:65px">Del</tr>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(parentEle.childNodes[eleId]);
var newct = ct - 1;
ct = newct;
<?php $ct = $ct - 1;?>
}
You're taking the input's value and always setting it to ct -
document.getElementById('ct_count').value = ct;
You should get a warning or error about ct in the console if you do it this. What you should do is set a variable to the value of the input -
var ct = document.getElementById('ct_count').value;
It also appears that you never set the value of the hidden field, so in the example I post here ct's value will always be blank.
It turned out that while bug testing i had moved that single session out of the conditionals for my script. So for every page other than the first i was moving on to, it was requesting a blank variable.
Idiocy at its finest. Thank you very much for everyone helping in this matter.
I am creating a PHP login script. So far I have only worked on the registration.
My question is, how can I handle validation in PHP without refreshing the page? I want to output the feedback that the user has entered information wrongly, but I don't want to refresh the page. This is because I am using AJAX, so I want it to output on the page.
Is this possible?
See here, if you "sign up" without filling in any of the boxes it shows you some error messages. The problem is that it reloads the page as it does it. Is there a way to not reload the page and still show this data?
http://marmiteontoast.co.uk/fyp/login-register/test/index.php
This is an example of the if statement for just the username. This is repeated with all the other fields too:
if(isset($_POST['username'])){
$username = mysql_real_escape_string(trim($_POST['username']));
if(strlen($username) > 3){
// passed
if(strlen($username) < 31){
// passed
} else {
$_SESSION['status']['register']['error'][] = 'The Username is greater than 30 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is less than 4 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The Username is not entered.';
}
Once it passes all the validation it does:
header('Location:index.php');
And the errors are output on the index page by:
<?php
if(isset($_SESSION['status']['register']['error'])){
?>
<div class="alert alert-error">
<p><strong>There's a problem!</strong><br /><br />
<?php
foreach($_SESSION['status']['register']['error'] as $error){
// Outputs list of all errors, breaks to new line
echo $error . '<br />';
}
?>
</p>
1. Is it possible to output these dynamically with PHP?
2. Could I do the validation on the front end, then just pass it to the PHP to pass to the database?
2a. How would I handle running a username exists check if I do it front end?
This is something I actually just made the other day!
I have a file called "register.js", a file called "register_process.php" and some html.
How my server is set up:
html_docs (www):
ajax:
register_process.php
js:
register.js
jquery-1.6.2.js
register.html
so within my register.html, my code looks like such:
<script type="text/javascript" src="js/md5.js"></script> <!-- this is in my head -->
<script type="text/javascript" src="js/jquery-1.6.2.js"></script>
<!-- everything else is in my body -->
<div id="error_message" style="display: none;">
</div>
<div id="register_div">
<input type="text" name="username" id="username"><br>
<input type="password" name="password" id="password"><br>
<input type="submit" name="submitbutton" id="reg_button" value="Register" onclick="AttemptRegisterAjax(); return false;"><br>
</div>
This calls the function inside of my register.js file. That functions looks like such:
function AttemptAjaxRegister(){
var url = "ajax/register_process.php?";
url += "time=" + (new Date().getTime()) + "&un=";
var username_ele = document.getElementById("reg_username");
var password_ele = document.getElementById("reg_password");
var error_ele = document.getElementById("error_message");
var username = username_ele.value;
var password = password_ele.value;
if((username.length >=4) && (password.length >= 4)){
url += encodeURIComponent(username) + "&pw=" + encodeURIComponent(password);
console.log(url);
$.get(url, function(data, status, xhr){
data = data.trim();
if(data != "true"){
error_ele.innerText = data;
error_ele.style = "display: block;";
}else{
window.location = "/profile.php";
}
});
}else{
error_ele.innerText = "Please make sure your password and username are both 4 characters long";
error_ele.style = "display: block;";
}
}
now, inside of your php, you'll want to set everything up just like how you had it to register, but you'll want to actually just call die($YourErrorMessage); or if the registration was successful, die("true");
Not directly, you will need to use another tool for that, most likely Javascript.
Yes but that would be a terible practice. the best way to validate on both.
2a. I believe you would need to use a database.
thsi tutorials might help you out.
Easy jQuery Ajax PHP Contact Form
How to create a Sign Up form registration with PHP and MySQL
I want to use time in pagination.In my script when click on next the timer restarts..i think session will help me.but i don't understand how to collect correct time in session and display that in another page in pagination.This is my javascript code:
var myTime = "20";
function countDown() {
document.form.seconds.value = myTime;
if (myTime == 0)
{
location.href="abc.php";
}
else if (myTime > 0)
{
myTime--;
setTimeout("countDown()",2000);
}
}
and this is how i set the time in my php file:
<form name="form">
Time Left: <input type="text" name="seconds" size="3">
</form>
Using session is really very simple. Just include: session_start(); at the beginning of every PHP file of your script.
Then, in order to set a time variable, use this: $_SESSION['theTime'] = $currentDateTime;
where $currentDateTime = date('m/d/Y h:i:s a', time());
Now, this $_SESSION['theTime'] variable will be passed on to every PHP file if you include session_start(); at the beginning of each. To find out difference between two times, refer this: php: datetime() difference between 2 datetime with 2 variables