jQuery only retrieves certain words from API - javascript

When I search for a word in my dictionary service to an API through jQuery, I'm only receiving certain words back and all plural words, for example:
I can search for 'word' and get definitions, but then I search for 'words' the only response is 'Plural for word'. But when I search for 'test', I get nothing back, when there are definitions when you search for the URL in a web browser.
I feel the problem is in the part below:
if (json !== "No definition has been found.")
This is the JavaScript:
$(document).ready(function(){
$('#term').focus(function(){
var full = $("#definition").has("definition").length ? true : false;
if(full === false){
$('#definition').empty();
}
});
var getDefinition = function(){
var word = $('#term').val();
if(word === ''){
$('#definition').html("<h2 class='loading'>We haven't forgotten to validate the form! Please enter a word.</h2>");
}
else {
$('#definition').html("<h2 class='loading'>Your definition is on its way!</h2>");
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=" +word+ "&pretty=true&callback=?", function(json) {
if (json !== "No definition has been found."){
var meanings = "";
json["tuc"].forEach(function(tuc) {
tuc["meanings"].forEach(function(m) {
meanings += "<p>"+m["text"]+"</p>\n";
});
});
$("#definition").html(meanings);
}
else {
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=&pretty=true" + "?callback=?", function(json) {
console.log(json);
$('#definition').html('<h2 class="loading">Nothing found.</h2><img id="thedefinition" src=' + json.definition[0].image.url + ' />');
});
}
});
}
return false;
};
$('#search').click(getDefinition);
$('#term').keyup(function(event){
if(event.keyCode === 13){
getDefinition();
}
});
});
This is the HTML:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Matthew Hughes">
<meta name="Dictionary" content="A dictionary web service">
<title>Dictionary Web Application</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="dictionary.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<div id="top">
<header>
<h1>Dictionary Application</h1>
</header>
</div>
<div id="app">
<input type="text" placeholder="Enter a word..." id="term" />
<button id="search">Define!</button>
<section id="definition">
</section>
</div>
<footer>
<p>Created by Matthew Hughes</p>
</footer>
</div>
</body>
If anyone has any ideas or had a similar problem, please comment!

Related

Transferring Data between pages once a button is clicked

I am creating a webpage where the user is able to apply for a position at a company. What I am aiming to do is once the link for a certain job is clicked then the job reference number is already filled in with the appropriate data. But instead the textbox is filled with "undefined"
The JavaScript file for both the page that displays jobs, and the application form - Don't worry about the validate variable I didn't want to copy the whole file.
function storeJobNumber(jobRefNumber) {
var da = document.getElementById("DA");
var jd = document.getElementById("JD");
var qa = document.getElementById("QA");
var fed = document.getElementById("FED");
if (da.onclick) {
localStorage.setItem("jobNumber", jobRefNumber) == "188345"
}
if (jd.onclick) {
localStorage.setItem("jobNumber", jobRefNumber) == "188386"
}
if (qa.onclick) {
localStorage.setItem("jobNumber", jobRefNumber) == "188323"
}
if (fed.onclick) {
localStorage.setItem("jobNumber", jobRefNumber) == "188357"
}
}
function job_apply(){
if (localStorage.getItem("jobNumber") !== null) {
var jobNumber = document.getElementById("jobNumber")
jobNumber.value = localStorage.getItem("jobNumber");
}
}
function init() {
if (document.getElementById("applypage")!=null) {
var regForm = document.getElementById("regform");
job_apply();
regForm.onsubmit = validate;
}
else if (document.getElementById("jobspage") !=null) {
storeJobNumber();
}
}
window.onload = init;
The apply form HTML
<!DOCTYPE html>
<html Lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="CWA HELP DESK" />
<meta name="keywords" content="HTML, CWA, Help, Desk" />
<meta name="author" content ="Harry Keys" />
<title>Application Form</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<script src="apply.js"></script>
</head>
<body id="applypage">
<form id="regform" method="post" action="http://mercury.swin.edu.au/it000000/formtest.php" novalidate="novalidate">
<img src="images/logo.png" alt="Company Logo" />
<h1> Job Application Form </h1>
<fieldset>
<p><label for="jobNumber">Job Reference Number</label>
<input type="text" onkeyup="this.value=this.value.replace(/[^\d]/,'')" name="jobNumber" id="jobNumber" maxlength="5" size="7" required="required" readonly/>
</p>
The HTML file that contains the jobs available
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="Assignment Page 1" />
<meta name="keywords" content="Home, Page, Details, Company" />
<meta name="author" content ="Harry Keys" />
<title>Available Jobs </title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<script src="apply.js"></script>
</head>
<body id="jobspage">
Home
Jobs
About
Enhancements
<h1>Hartley Studios <img src="images/logo.png" alt="Company Logo" class="right"/> </h1>
<hr>
<section>
<fieldset class="JobsF">
<img src="images/Database.jpg" alt="Database Analyst"/>
<h3> Database Analyst </h3>
<p> The purpose of a Database Analyst is to Maintain data storage and access by designing physical databases...</p>
Discover
Apply
</fieldset>
<fieldset class="JobsF">
<img src="images/Software.jpg" alt="Software Developer"/>
<h3> Java Developer </h3>
<p> The purpose of a Java Developer is generally responsible for the development, design and implementation of Java products...</p>
Discover
Apply
</fieldset>
<fieldset class="JobsF">
<img src="images/QA.jpg" alt="QA Engineer"/>
<h3> QA Engineer </h3>
<p> The purpose of a QA Engineer is to put programs through rigorous tests, In an attempt to locate any areas of weakness...</p>
Discover
Apply
</fieldset>
<fieldset class="JobsF">
<img src="images/FED.jpg" alt="Front End Developers"/>
<h3> Front End Developer </h3>
<p> The front end of a website is the part users see and interact with – they play critical part of any business...</p>
Discover
Apply
</fieldset>
</section>
When the user clicks on the apply button for Database Analyst, the textbox "jobNumber" should contain the number 188345, but instead it contains nothing or sometimes "undefined"
You never add event listeners for the links. The function storeJobNumber only gets called on init, where you don't know which link is pressed yet. You need to add the event listeners to trigger when the links are clicked and then save the id to localstorage.
Like this:
function storeJobNumber(jobRefNumber) {
var da = document.getElementById("DA");
var jd = document.getElementById("JD");
var qa = document.getElementById("QA");
var fed = document.getElementById("FED");
// new code
da.addEventListener("click", function() {
localStorage.setItem("jobNumber", 188345);
});
jd.addEventListener("click", function() {
localStorage.setItem("jobNumber", 188386);
});
qa.addEventListener("click", function() {
localStorage.setItem("jobNumber", 188323);
});
fed.addEventListener("click", function() {
localStorage.setItem("jobNumber", 188357);
});
/* Old code
if (da.onclick) {
localStorage.setItem("jobNumber", jobRefNumber) == "188345"
}
if (jd.onclick) {
localStorage.setItem("jobNumber", jobRefNumber) == "188386"
}
if (qa.onclick) {
localStorage.setItem("jobNumber", jobRefNumber) == "188323"
}
if (fed.onclick) {
localStorage.setItem("jobNumber", jobRefNumber) == "188357"
}*/
}
Link to working pluker: http://plnkr.co/edit/EXD9jG4h2mDZNxvMKCRy?p=preview
The syntax of localStorage.setItem is localStorage.setItem(keyname, value) .It should be like localStorage.setItem("jobNumber", "188345") instead of localStorage.setItem("jobNumber", jobRefNumber) == "188345" .Ref https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Local_storage

How do I remove a to do list item after it is added

I really tried everything, almost every function in JS. But I cannot remove the list item from the to-do list once it is added. I have tried adding event listeners, onclick=" " etc but nothing works. Can someone please look at my code and tell me what I am doing wrong. Thank You, any help is much appreciated.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="script.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet href="style.css">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<meta charset="UTF-8">
<title>To-Do-List</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
</div>
</div>
<script>
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event){
const element = event.target;
if(element.type === "close"){
delete element;
}
}
</script>
</body>
</html>
JS:
$(document).ready(function(){
document.getElementById('addTask').addEventListener("click", function(){
var task = document.getElementById('task').value;
if(task == ""){
alert("You Must Enter A Value!");
}else{
document.getElementById('myUL').innerHTML += '<li>' + task + '</li>' + '<button class="close" >&#10007</button>' + '<br><br>' + '<button class="check" >✓</button>' + '<br><br>';
}
var button = document.querySelectorAll('.close');
for(var i = 0; i < button.length;i++){
button[i].addEventListener("click", function(){
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
});
}
var check = document.querySelectorAll('.check');
for(var i = 0; i < check.length;i++){
check[i].addEventListener("click", function(){
this.parentNode.style.textDecoration = "line-through";
});
}
});
});
Don't try to concatenate innerHTML strings when you have listeners attached to elements inside, else the listeners will be lost. Instead, append elements properly with appendChild.
delete element won't actually do anything, because element is a variable, not a property of an object - try using .remove() instead, to remove the li (and put the button inside the li so that the HTML is valid).
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event) {
const element = event.target;
if (element.className === "close") {
element.parentElement.remove();
}
}
document.getElementById('addTask').addEventListener("click", function() {
var task = document.getElementById('task').value;
if (task === "") return alert("You Must Enter A Value!");
const li = list.appendChild(document.createElement('li'));
li.textContent = task;
const button = li.appendChild(document.createElement('button'));
button.className = 'close';
button.textContent = '✗';
});
.close {
position: absolute;
left: 150px;
}
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
Your .querySelectorAll() simply needs to target .close rather than close. In addition to this, you'll probably want to target the close button's parent (the item itself), with .parentNode. Note that you probably don't want to hide it, but rather actually simply remove both the <li> and the close icon, so that you can add more items after removal of the item(s). This can be done with:
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
And can be seen working in the following:
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event) {
const element = event.target;
if (element.type === "close") {
delete element;
}
}
$(document).ready(function() {
document.getElementById('addTask').addEventListener("click", function() {
var task = document.getElementById('task').value;
if (task == "") {
alert("You Must Enter A Value!");
} else {
document.getElementById('myUL').innerHTML += '<li>' + task + '</li>' + '<button class="close" >&#10007</button>' + '<br><br>';
}
var button = document.querySelectorAll('.close');
for (var i = 0; i < button.length; i++) {
button[i].addEventListener("click", function() {
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
});
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="script.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<meta charset="UTF-8">
<title>To-Do-List</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
</body>
</html>
Also note that your stylesheet is missing a closing ", and you have two additional closing </div> that don't match anything in your above code.

JQuery chat is appending <scripts>

I am building a simple chat app. The issue I have encounter is that users can insert scripts through the chat. Obviously this is not something I want.
A (simplified version) of my code is:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="/stylesheets/style.css"/>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
body {
padding-top: 80px;
word-wrap: break-word;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="app">
<script src="/socket.io/socket.io.js"></script>
<script>
// on load of page
$(function() {
// when the client clicks SEND
$('#datasend').click(function() {
console.log('enviar data');
var message = $('#data').val();
$('#conversation').append('<b>me:</b> ' + message + '<br>');
$('#data').val('');
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if (e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<script src="scripts/locate.js"></script>
<div class="container" ng-controller="userController">
<div class="row">
<div class="col-sm-12">
<div class="well">
<h3>
<span class="fa fa-comment"></span>
Chat</h3>
<div>
<div id="conversation"></div>
<input id="data" style="width:200px;"/>
<input type="button" id="datasend" value="send"/>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
For example, if an user inserts this text:
<script> alert('big problem') </script>
An alert pops up. Any ideas of how to solve this?
Thanks in advance.
you need client side code and server side code to protect XSS
as for cleint code you can use this function
function strip_tags (input, allowed) {
allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('')
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi
var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi
return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''
})
}
usage :
var message = $('#data').val();
message= strip_tags(message, '<br><br/><br />');
$('#conversation').append('<b>me:</b> ' + message + '<br>');
also you can user php strip_tags function on server side
string strip_tags ( string $str [, string $allowable_tags ] )
more infromation
http://php.net/manual/ru/function.strip-tags.php
Thanks to what CodingWithSpike commented I managed to get to this solution:
// when the client clicks SEND
$('#datasend').click(function() {
console.log('enviar data');
var message = $('#data').val();
text = $('<span></span>').text(message);
user = $('<b> </b>').text('me: ');
div = $('<div> </div>');
div = div.append(user);
div = div.append(text);
$('#conversation').append(message);
$('#data').val('');
});
After I got to this solution I looked at what Ciprian Turco posted. It also manage to do the trick but it removed some stuff. Thats why I prefer this solution.

How to add mutilple dynamic items on listview?

I have two pages.The first page contains form with required fields and also a submit button(with validations).And In the second page Listview should be there. So, when i clicked on the Submit button in first page ,the entire fields should be display on the list.
I have used local storage for saving the data in the second page.It is perfect.But the data is not displaying exactly on the list.And I want to add multiple items dynamically in the firstpage,So that multiple items which are added by me can be seen in second page.
Here are my two pages code.
new.html
<!DOCTYPE HTML >
<html >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<link rel="stylesheet" href="./styles/new.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="./js-css/development-bundle/themes/start/jquery.ui.all.css">
<link rel="stylesheet" media="screen" type="text/css" href="js-css/development-bundle/themes/base/jquery.ui.datepicker.css" />
<script type="text/javascript" src="js-css/development-bundle/jquery-1.10.2.js"> </script>
<script type="text/javascript" src="js-css/development-bundle/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="js-css/development-bundle/ui/jquery.ui.datepicker.js"></script>
<script type="text/javascript">
$(function(){
var pickerOpts = {
appendText: "",
defaultDate: "+5",
showOtherMonths: true,
dateFormat: "dd/mm/yy",
};
$("#strtd").datepicker({
minDate: 0
});
$("#sub").datepicker({
maxDate: new Date,
minDate: new Date(2007, 6, 12)
});
$('#strtd').focus(function() {
this.blur();
});
$('#sub').focus(function() {
this.blur();
});
});
function back() {
window.open("file:///android_asset/www/index.html");
}
//form validation
function validateForm() {
localStorage.setItem("RecordName", document.myForm.RecordName.value);
localStorage.setItem("StartedDate", document.myForm.StartedDate.value);
localStorage.setItem("SubmitedDate", document.myForm.SubmitedDate.value);
var x = document.forms["myForm"]["name"].value;
var y= document.forms["myForm"]["strtd"].value;
var z= document.forms["myForm"]["sub"].value;
if (x==null || x=="") {
alert("Record name must be filled out");
return false;
}
else if (y==null || y=="") {
alert("Started Date must be filled out");
return false;
}
else if (z==null || z=="") {
alert("Submitted Date must be filled out");
return false;
}
else {
alert("New Record Created");
}
}
</script>
</head>
<body>
<form name="myForm" id="form" type="get" onsubmit="return validateForm()" action="lead.html">
<div id="top"> New Record</div>
<div>
<h5>Record Name <input type="text" name="RecordName" id="name"></h5>
</div>
<div >
<h5>Started Date <input id="strtd" type="text" name="StartedDate"></h5>
</div>
<div>
<h5>Submitted Date <input id="sub" type="text" name="SubmitedDate"></h5>
</div><br>
<div align="center">
<input type="submit" id="submit" value="Submit" >
</div>
</form>
<div align="center">
<button id="cancel" onclick="back()">Back</button>
</div>
</body>
</html>
and my second page lead.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./styles/lead.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"> </script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
<script>
function mylead1()
{
window.open("file:///android_asset/www/editlead.html");
}
function mylead2()
{
window.open("file:///android_asset/www/editlead.html");
}
function mylead3()
{
window.open("file:///android_asset/www/editlead.html");
}
function onBackKey()
{
window.open("file:///android_asset/www/new.html");
}
</script>
</head>
<body id="lead">
<div id="top" align="center" > Leads </div>
<img id="plus" src="./images/plus.png" onclick="onBackKey()" >
<div data-role="page" style="margin-top:100px;" >
<div data-role="main" id="content" style="min-height:60px;">
<ul id="unorder" data-role="listview" data-theme="a" data-dividertheme="b">
<li id="list" data-role="list-divider">
<label id="label1" > </label><br>
<label id="label2"></label><br>
<label id="label3"></label>
<img id="arrow" src="./images/Arrow#2x.png" style="margin-left:250px" onclick="mylead1()">
</li>
</ul>
</div>
</div>
</body>
<script>
//local storage
document.getElementById("label1").innerHTML= localStorage.getItem("RecordName");
document.getElementById("label2").innerHTML= localStorage.getItem("StartedDate");
document.getElementById("label3").innerHTML= localStorage.getItem("SubmitedDate");
</script>
<script>
$("#submit").click( function() {
$("ul").append("<li></li>").listview("refresh");
li.text("#label1");
$("#unorder").append(li);
$("#unorder").listview("refresh");
})
</script>
</html>
My requirement is to get the added data(in new.html) dynamically on second page(lead.html)
`Please guide me for resolving it.Thanks :)
local storage is working fine , so m not focusing on it.
Here concern is displaying all data from first page in second that too in list format
this is the most simplest way to do this,
ON FIRST PAGE
on form submit suppose you are calling one function name redirect
function redirect()
{
var form = $("form[name='myForm']");
form_data = form.serialize();
window.location = "secondpage.html?"+form_data // eg: secondpage.html?single=Single2&multiple=Multiple&multiple=Multiple3&radio=radio1
}
ON SECOND PAGE
function which will parse url and give parameters as objects
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
var url = window.location.href ; //'www.example.com?ferko=suska&ee=huu';
var parameters = $.parseParams( url.split('?')[1] || '' ); // object { ferko: 'suska', ee: 'huu' }
var li='';
$.each( parameters, function( key, value ) {
// write html code
li += "<li>"+value+"</li>"
});
$("ul").html(li);
<ul>
</ul>

Cannot read property 'value' of null

I have spent probably an hour attempting to get this figured out... I keep getting this error no matter what I try:
Cannot read property 'value' of null
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 101 Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<h1>Hello, world!</h1>
<div id="login_box"><form class="form-inline" action="JavaScript: login();" method="post">
<input type="text" class="input-small" id="login_username" name="username" placeholder="Username">
<input type="password" class="input-small" id="login_password" name="password" placeholder="Password">
<label class="checkbox"><input type="checkbox" id="login_autologin" name="autologin"> Remember me </label>
<button type="submit" class="btn" name="login">Sign in</button>
</form></div>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/overall_js.js"></script>
</body>
</html>
and the related JS file (overall_js.js):
function login() {
$("#login_box").html("logging you in....");
console.log(document.getElementById("login_username").value);
$.post("user.php?mode=login", {
username : document.getElementById("login_username").value,
password : document.getElementById("login_password").value,
autologin : document.getElementById("login_autologin").value,
}).done(function(data) {
result = JSON.parse(data);
if (result.status == 3) {
$("#login_box").html(
"Welcome back, " + result.user_row.username + "!");
} else {
$("#login_box")
.html("You was not logged in: , " + result.error_msg);
}
});
}
Thanks if you can figure this out! I am also new to jQuery and JS so if anyone has any suggestions to make it more "Standard", any tips are appreciated!
This line
$("#login_box").html("logging you in....");
replaces the content of your <div>. You remove the form and all input elements...
See corrections needed below, lines 6 and 7:
function login() {
$("#login_box").append("logging you in....");
var u = $('#login_username').val();
var p = $('#login_password').val();
var al = $('#login_autologin').is(':checked');
console.log(u, p, al);
$.post("user.php?mode=login", {
username : u,
password : p,
autologin : al,
}).done(function(data) {
result = JSON.parse(data);
if (result.status == 3) {
$("#login_box").html(
"Welcome back, " + result.user_row.username + "!");
} else {
$("#login_box")
.html("You was not logged in: , " + result.error_msg);
}
});
}

Categories

Resources