ajax callServer ajp still empty - javascript

I am trying to make a website for a project so it will be locally and I am in the point where I want to use Ajax for a login form I made. I dont know very much about ajax but this is a code I found it doesnt work but I dont know what else I should do, and what exactly am I expecting. An ajp file with what inside? Thanks in advance
This is the javascript code:
function callServer(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlString =
"<profile>" +
"<username>" + escape(username) +"</username>" +
"<password>" + escape(password) +"</password>" +
"</profile>";
// Build the URL to connect to
var url = "file:///C:/Users/admin/Documents/project/savelogin.jsp";
// Open a connection to the server
xmlHttp.open("POST", url, true);
// Tell the server you're sending it XML
xmlHttp.setRequestHeader("Content-Type", "text/xml");
// Set up a function for the server to run when it's done
xmlHttp.onreadystatechange = confirmUpdate;
// Send the request
xmlHttp.send(xmlString);
}
This is the html code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="login.js"></script>
<title>Project-Login</title>
</head>
<body>
<form id="loginform">
<div>
<p id="insertinfo">Type your info to log in your account:</p>
<label for="Username">Username:</label>
<input type="text" id="username" placeholder="Type your username"/>
</div>
<div>
<label for="password">Type password:</label>
<input type="text" id="password" placeholder="Type your password"/>
</div>
<div class="loginButton">
<input type="submit" value="Log in" class="loginbutton" onclick="callServer()" />
</div>
</form>
</body>
</html>

What will you be doing with the values that you retrieve from HTML?
Her is an example from w3schools:
http://www.w3schools.com/ajax/ajax_php.asp
But what you want is:
<script>
function retrieveValues() {
var value1 = document.getElementById("username").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "thePhpPage.php?q=" + value1, true);
xmlhttp.send();
}
But here the variables are passed onto a php function. If you want something similar on your local machine you need to install lamp or wamp depending on your OS.

Related

javascript function with variable needed to trigger a url with value from within script

i have an html page with some inputs, i need to trigger a js function that will ultimately lead to triggering a url GET or POST (with out credentials) the problem is i need to see this in my url
http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/oven
instead I see this
http://localhost:8080/?keyword=oven&email=
Don't worry about the email; I am using a thymleaf for front end and java for back end database to save email.
For now i really need to trigger the url with the right url which is this
http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/oven
my code is as follows (index.html)
<div class="col span-2-of-2">
<form action="">
<input type="text" name="keyword" id="keyword" placeholder="Search">
<input type="text" name="email" id="email" placeholder="Email (Optional)">
<button type="submit" onclick="equipmentSearchFn()">Search</button>
</form>
</div>
for script i have within my html file (index.html)
<script>
function equipmentSearchFn() {
let keyword;
let email;
let url;
keyword = document.getElementById("keyword").value;
email = document.getElementById("email").value
document.getElementById("keyword").innerHtml = keyword;
document.getElementById("email").innerHtml = email;
let xmlHttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlHttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
}
}
url = "http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/" + keyword;
//window.location = url + keyword;
xmlHttp.open('GET', url, true);
xmlHttp.send();
}
</script>
i am much obliged...
You have two problems here. The first it the "submit" button. Unless you stop the click event with javascript, the button will POST the values to your Form.
The second problem is the AJAX request, which I think you don't need at all.
function equipmentSearchFn() {
let keyword;
let email;
let url;
keyword = document.getElementById("keyword").value;
email = document.getElementById("email").value
url = "http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/" + keyword;
window.location = url + keyword;
}
<div class="col span-2-of-2">
<form action="">
<input type="text" name="keyword" id="keyword" placeholder="Search">
<input type="text" name="email" id="email" placeholder="Email (Optional)">
<button type="button" onclick="equipmentSearchFn()">Search</button>
</form>
</div>

How can I fix this html code to not display sensitive information to the user?

I am creating a html form to capture applicants' inputs and then send a POST request to an api with the data. I do not know how to go about hiding three specific values from something like 'View Page Source' or console.log(). I need to store the values securely and still be able to use them in the HTML form.
I know I will probably have to rewrite my solution but I do not know the best way to go about this. Is there a way to store the values of the api keys in a database?
Here are the three values in question:
<body>
<main role="main" class="container-fluid">
<form id="form1" name="form1" onsubmit="beforeSubmit(); return false;">
<div class="aspNetHidden">
<input type="hidden" name="merchantID" id="merchantID" />
<input type="hidden" name="login" id="login" />
<input type="hidden" name="password" id="password" />
</div>
<script type="text/javascript">
var merID = "1234567";//need to store these values somewhere else!!!!!!!
var log = "API123";
var pass = "1234567";
//even if these values are moved they would be viewable by something like console.log(obj)
document.getElementById("merchantID").value = merID;
document.getElementById("login").value = log;
document.getElementById("password").value = pass;
</script>
And here is where I make the API call:
<script type="text/javascript">
beforeSubmit = function () {
//======================================================================================================
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
//======================================================================================================
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://someurl.com/enroll.svc/JSON/CreateMerchant", true);
xhttp.setRequestHeader("Content-type", "application/json");
var obj = JSON.stringify($('#form1').serializeObject());
console.log(obj);//security concern! all someone would have to do is cntrl+shift+j when the form is submitted
//this log command would display the entire JSON object including the merchant ID, Login and Password
xhttp.send(obj);
} //=====================================================================================================
</script>
I am very new to this. The code does what it is supposed to aside from sensitive information easily being viewed by inspecting the page source. Any suggestions of for a better/more secure way would be appreciated.
Its shouldn't be too hard put your api in a php variable then insert your variable into your database table.
Then use select to take it out when you need it also php is not readable from view source.
If you don't know how to input and select from databases there are plenty of tutorials out there.
Your code is a horrid mix of unnecessary serialisation you are not using and a weird event handling of beforesubmit.
This is how a generic jQuery ajax looks like
$(function() { // page load
$("#form1").on("submit", function(e) {
e.preventDefault(); // cancel the submit
$.post("https://someurl.com/enroll.svc/JSON/CreateMerchant", // url
$(this).serialize(), // serialising the form
function(result) {
console.log(result); // do something with the result of the submission
});
});
});
<form id="form1" name="form1">
<div class="aspNetHidden">
<input type="hidden" name="merchantID" id="merchantID" />
<input type="hidden" name="login" id="login" />
<input type="hidden" name="password" id="password" />
</div>
</form>

AJAX not working when pressing submit button

I am practicing the basics of AJAX.
When I click Submit nothing happens.
Here’s my code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>FIRST AJAX!</title>
<script>
function alertMe(){
var field1 = document.getElementById("Field1").value;
var parser = "parse.php";
var values = "name="+filed1;
var xml = new XMLHttpRequest();
xml.open("POST", parser, true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
document.getElementById('output').innerHTML = xml.responseText;
}
}
xml.send(values);
document.getElementById('output').innerHTML = " Loading ... ";
}
</script>
</head>
<body>
<input type="text" name="Field1" id="Field1"/>
<input type="submit" name="Fsend" onClick="alertMe();"/>
<p id="output"></p>
</body>
</html>
Thank you.
The problem is you are declaring a variable called field1, and then calling it as fiLEd1.
Try checking the console for errors, it's always useful
var values = "name="+filed1;
has a typo, should be...
var values = "name="+field1;
Also, input elements should be within a form and you probably want to use type="button" since you are not submitting the form. Finally, all standard attributes should be in lowercase, should be onclick, not onClick.
<!doctype html> <html> <head> <meta charset="utf-8"> <title>FIRST AJAX!</title> <script>
function alertMe(){
var field1 = document.getElementById("Field1").value;
var parser = "parse.php";
var values = "name="+field1;
var xml = new XMLHttpRequest();
xml.open("POST", parser, true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.onreadystatechange = function(){
if ( xml.readyState == 4 && xml.status == 200){
document.getElementById('output').innerHTML = xml.responseText;
}
}
xml.send(values);
document.getElementById('output').innerHTML = " Loading ... ";
}
</script>
</head>
<body><form>
<input type="text" name="Field1" id="Field1"/>
<input type="button" value="Submit" name="Fsend" onclick="alertMe();"/>
</form> <p id="output"></p>
</body> </html>

Form Validation in a pop up window

Hi I am displaying a pp up window based on the value stored in a localStorage.In the pop up window there is a form containing email and password.The user has to enter his email and password.Now what I need is that, the email entered by user has to be sent to a url and the url returns a status(either 1 or 0).If the url returns 1 then the user can just continue with the log in process.Otherwise an error message should be shown.The url is in the format http://www.calpinemate.com/employees/attendanceStatus/email/3".Here in the place of email highlighten should come the email entered by user in the form.In this way I have to pass the email.In this way I am doing form validation.But I don't know how to do.
Here is my userinfo.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<b>Enter your Email ID and Password</b><br><br>
<form id="userinfo">
<label for="user"> Email : </label>
<input type="text" id="user" />
<br><br>
<label for="pass">Password : </label>
<input type="password" id="pass" />
<br>
<br>
<input type="button" id="login" value="Log In" />
</form>
</body>
</html>
This is the form in the pop up window
Here is my test.js
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pwd = document.querySelector('input#pass');
var login = document.querySelector('input#login');
login.addEventListener('click', function() {
var userStr = user.value;
login();
window.close();
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.updateIcon();
});
});
function login(){
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/3';
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
localStorage.username=userStr;
localStorage.password=pwd;
}
else{ alert('error');}
}
}
});
var url = urlPrefix + encodeURIComponent(userStr) + urlSuffix;
req.open("GET", url);
req.send(null);
}
});
This is my javascript.When the user presses the log in button,whatever the user enters in the email textbox gets stored in localStorage.username.Now what I need is that I have to check whether such an email id exists by passing the email to the above specified url.And if it exists only it should be stored in localStorage.username.Please anyone help me. I have tried using the above code.But noting happens.Please help me
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
It is a contact form. You can change it to validation.
Add a Button or link to your page like this
<p>click to open</p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.

Sending parameters with ajax not working

I'm trying to send some variables using ajax to a php page and then displaying them in a div but it isn't working.
Html code :
<div id="center">
<form>
<input type="text" id="toSearch" class="inputText" title="Search for ...">
<select name="thelist1" id="ecoElem" class="comboBox">
<option>-- Ecosystem Element --</option>
</select>
<select name="thelist2" id="ecoActor" class="comboBox">
<option>-- Ecosystem Actor --</option>
</select>
<input type="button" value="Search" id="searchButton" onclick="loadData();">
</form>
</div>
<div id="resBox">
</div>
The loadData function :
function loadData(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
searchT = document.getElementById('toSearch').value;
ecoElem = document.getElementById('ecoElem').value;
ecoActor = document.getElementById('ecoActor').value;
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('resBox').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","databaseRead.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("text=" + searchT + "&elem=" + ecoElem + "&actor=" + ecoActor);}
and finally the php page :
<?php
$searchT = $_POST['text'];
$ecoElem = $_POST['elem'];
$ecoActor = $_POST['actor'];
echo $searchT;
?>
That's it , I've been working on this for a few hours but still can't figure it out.
Try changing the button so that the onclick return false (in case that is submitting the form)...
<input type="button" value="Search" id="searchButton" onclick="loadData();return false;">
Also, you might want to URL encode the values from the textbox, otherwise somebody entering a = or a & will mess it all up...
xmlhttp.send("text=" + encodeURIComponent(searchT) + "&elem=" + + encodeURIComponent(ecoElem) + "&actor=" + + encodeURIComponent(ecoActor));}
You could also use JQuery.
function loadData(){
var searchT = $('#toSearch').val();
var toSearch = $('#ecoActor ').val();
var ecoActor = $('#ecoActor').val();
$.post("databaseRead.php"),{ text:searchT, elem:toSearch, actor:ecoActor },
function(data){
$('#resBox').html(data);
});
}

Categories

Resources