I'm working on a page that is supposed to interact with the server via AJAX, but my experience with AJAX is extremely limited. Here's how the page is supposed to work.
When the button is clicked, if the "test" radio button is clicked, just display a pop up saying the input was valid.
When the button is clicked, if the "live" radio button is clicked, the program is supposed to send a request to the server using the URL "http://cs.sfasu.edu/rball/351/exam2.php" with the contents of the input box being the value for the "name" parameter.
The page will then send back a JSON object that I need to parse into a regular variable.
I'll leave the rest of the JSON stuff alone since that's not what I asked.
So far I have the design of the page done, but like I said I don't really know what I'm doing with the AJAX stuff. I have some code written for it, but not sure that it's right.
Here is my code:
<html>
<head>
<title>anner, Taylor</title>
<style type = "text/css">
canvas {
border: 2px solid black;
}
</style>
<script type = "text/javascript">
window.onload = function() {
var TTcanvas = document.getElementById("myCanvas");
var TTcontext = TTcanvas.getContext("2d");
TTcontext.strokeStyle = "red";
TTcontext.fillStyle = "red";
TTcontext.fillRect(250,50,100,100);
TTcontext.stroke();
TTcontext.beginPath();
TTcontext.moveTo(600, 0);
TTcontext.lineTo(0, 200);
TTcontext.lineWidth = 5;
TTcontext.strokeStyle = "black";
TTcontext.stroke();
}
function validate() {
var TTinput = document.getElementById("3letters").value;
if(TTinput.length < 3 || TTinput.length > 3) {
alert("Please enter 3 letters");
}
var TTtest = document.getElementById("test");
var TTlive = document.getElementById("live");
if(TTtest.checked == true) {
alert("Input is valid");
}
else if(TTlive.checked == true) {
return ajaxStuff();
}
}
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
var TTresponse = TTrequest.responseText;
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML.TTresponse;
}
}
}
</script>
</head>
<body>
<h1>Tanner, Taylor</h1>
<canvas id = "myCanvas" width = "600" height = "200"></canvas> <br>
<form>
Enter 3 letters: <input type="text" id="3letters"> <br>
<input type = "radio" id = "test" value = "test">Test
<input type = "radio" id = "live" value = "live">Live <br>
<input type = "button" id = "check" value = "Send" onclick="validate()">
</form>
<div id="myDiv">
</div>
</body>
</html>
And here is a link to my page on our server:
cs.sfasu.edu/cs351121/exam2.html
Also, I know it says exam, but this is actually just a review we were given for the actual exam that's next week. I'm just trying to figure out how this works but don't know what I'm doing wrong.
I'm not sure what the problem is. The code is correct
Ok now i get the problem. You are calling the request variable outside the scope. You are declaring the request variable inside your ajaxStuff function so its only accessible in that area. Thats why it is undefined. Try this:
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML=TTrequest.responseText;
}
}
}
to get the result just do this
TTrequest.send();
var response=TTrequest.responseText;
I know, I do not see the jQuery tag, but consider it if there are no framework restrictions.
Example:
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});
Related
I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.
<!DOCTYPE html>
<html>
<head>
<title>Fizzbuzz Input Field</title>
<script src="scripts.js"></script>
</head>
<body>
<form>
<input type="number" id="userInput"></input>
<button onclick="fizzBuzz()">Go</button>
</form>
</body>
</html>
window.onload = function() {
alert("Page is loaded");
};
var fizzBuzz = function() {
var userInput = document.getElementById("userInput");
fizzBuzz.onclick = function() {
if(userInput.value == 10) {
document.write("awesome");
};
};
}
Grab the element from the input, in this case, "userInput". grab your button by querying it, or putting an id on it etc... Don't bother with putting a function on the HTML, avoid bad practice. Add an event listener to the button, check to see if it equals 10 and append your text, preferably somewhere suitable.
var input = document.getElementById("userInput");
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click', function(a) {
if (input.value === '10') {
button.after("awesome");
}
})
<input type="number" id="userInput">
<button>Go</button>
I think what you are looking for is eval before using it, you should search the web for why eval is evil.
What you want is something like this:
var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
// First we get the numeric value written to the input (or NaN if it's not a number)
var inputValue = parseInt(document.getElementById('userInput').value, 10);
// Define the element to which write the text (you usually want a DIV for this)
var outputElement = document.getElementById('outputDiv');
if ( ! isNaN(inputValue) ) {
outputElement.innerHTML = "awesome!";
}
else {
// The value is not a number, so just clean the result
outputElement.innerHTML = "";
}
});
Of course, for this to work, you should have at least:
<input type="number" id="userInput" />
<button id="myButton">Go</button>
<div id="outputDiv"></div>
I don't have any idea how you want the awesome to be displayed. Made it an alert. Have fun.
<script>
function fizzBuzz() {
var fizzBuzz = document.getElementById("userInput").value;
if(fizzBuzz != 10){
alert('Number is not equal to ten!');
}else {
alert('awesome');
}
}
</script>
You are setting a property 'onclick' of function 'fizzBuzz',
you should use the input event.
var userInput = document.getElementById('userInput');
userInput.oninput = function() {
if( this.value == 10 ) alert('awesome');
}
I am trying to use JavaScript in an online examination assignment in HTML. As a requirement of the project, we have to use text input forms as well as radio buttons and the like. I have dealt with the part of radio buttons but for some reason my text input forms do not work. My problem will be clearly stated using this code snippet from the main project:
<html>
<head>
<title></title>
<script type="text/javascript">
var test, name, matr, myname, count = 0;
function form(){
test = document.getElementById("test");
test.innerHTML = "Count = "+count;
test.innerHTML += "<form> \
First name:<br> \
<input type='text' name='name'><br>\
<button onclick='check()'>Submit Answer</button>";
}
function check(){
myname = document.getElementsByName("name");
if (myname[1].value == "myname")
{
count++;
}
form();
}
window.addEventListener("load", form, false);
</script>
</head>
<body>
<div id = "test"></div>
</body>
</html>
What this code aims to do is that when the user inputs "myname" into the form called 'First name' and clicks 'Submit', the counter on the top should increment.
Can someone please shed some light on what I am doing wrong and how it may be resolved.
As Pluto mentioned, arrays in javascript start at 0. You can also look at tinkering with the form element. It is not closed nor is the type, get or post specified. I got it working in the example below by removing the form completely. This is because the button press was trying to submit the form and therefore load a new page.
https://jsfiddle.net/jpm68eub/
var test, name, matr, myname, count = 0;
function form() {
test = document.getElementById("test");
test.innerHTML = "Count = " + count;
test.innerHTML += "</br> First name:<br> \
<input type='text' name='name'><br>\
<button onclick='check()'>Submit Answer</button>";
}
function check() {
myname = document.getElementsByName("name");
if (myname[0].value == "myname") {
count++;
}
form();
}
form();
you need to prevent the default action of the onclick event. To do this, try something like this:
function check(e){
e.preventDefault();
myname = document.getElementsByName("name");
if (myname[0].value == "myname")
{
count++;
}
form();
}
the above user was also correct about where javascript arrays start (they start at 0)
Is there a way to get the ID of a radio button using JavaScript?
So far I have:
HTML
<input type="radio" name="fullorfirst" id="fullname" />
JavaScript
var checkID = document.getElementById(fullname);
console.log(checkID);
It outputs as null.
Essentially what I want to do is:
document.getElementById(fullname).checked = true;
...in order to change the radio button fullname to be checked on page load.
you should put fullname between quotes, since it's a string:
document.getElementById("fullname");
function checkValue() // if you pass the form, checkValue(form)
{
var form = document.getElementById('fullname'); // if you passed the form, you wouldn't need this line.
for(var i = 0; i < form.buztype.length; i++)
{
if(form.buztype[i].checked)
{
var selectedValue = form.buztype[i].value;
}
}
alert(selectedValue);
return false;
}
Hope this helps.
JavaScript Solution:
document.getElementById("fullname").checked = true;
Jquery Solution:
$("#fullname").prop("checked", true);
I am trying to learn JavaScript, PHP and some basic client-side form validations in trying to build this basic JavaScript tutorial that interacts with PHP and HTML. WHat I am trying to do is interrupt a form submission event, i.e. user forgets to enter a valid email format in the email submission input and clicks on the submit button which should then display an error message and not allow the form to be submitted. But I can't get this to work for me. What happens is that I am instead taken to the support_process.php page when that should not happen. Any help at all would be greatly appreciated.
Here is my index.html code for the form:
<div>
<form id="frmSupport" name="frmSupport" method="post" action="support_process.php">
<fieldset id="fastSupport">
<legend><strong>Fast Support</strong></legend>
<p>If you've already booked the Singing Rails Girls coach,</br> and have not gotten a confirmation number,</br> drop us a line and we'll respond within 24 hours.</p> </p>
<p>
<label for="email">Email:</label>
<input type="text" value="your email" name="name" id="email" tabindex="10" />
<p>
<span id="errorMsg"></span>
</p>
<input type="submit" value="Submit">
</p>
<p><b>Ed's "Blah Blah Blah" Tour Status</b></p>
<label for="tourStatus" class="inline">
<input type="radio" name="tour status" value="booked" id="tourStatus_0" tabindex="40" />Ed already toured here
</label>
<label for="tourConf" class="inline" >
<input type="radio" name="tour conf" value="paid" id= "tourStatus_1" tabindex="50" />Ed confirmed his tour date
</label>
</br>
</fieldset>
</form>
</div>
Comments Section
Comments:
<script src="myscript.js">
</script>
And here is my corresponding JavaScript file:
//alert("Hello, world!"); // this is a JavaScript alert button //
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro...");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
// Handling the form submit event
document.getElementById("frmSupport").onsubmit = function(){
//prevent a form from sumbitting if no email.
if (document.getElementById("email").value == "") {
document.getElementById(errorMsg).innerHTML = "OOPS!";
//to stop the form from submitting:
return false;
}else {
//reset and allow form submission:
document.getElementById("errorMsg").innerHTML = "";
return true;
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers();
// This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White- Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var intervalHandle = setInterval(changeImage, 5000);
myImage.onclick = function() {
clearInterval(intervalHandle);
}
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
And here is my corresponding php file for the event interrupter (for refusing to allow the form to be submitted if user leaves email field blank or something):
<?php
//some php script can go here
echo "This is the support confirmation page...sorry, nothing fancy here!"
?>
<h1>Thank you, we will contact you shortly!</h1>
<a href="index.html" target="_blank" >Back</a>
<?php
// More php code can go here, and so forth and so on..
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_GET); */
error_log(message);
?>
Here's a problem:
if (document.getElementById("email").value == "") {
document.getElementById(errorMsg).innerHTML = "OOPS!";
//to stop the form from submitting:
return false;
}else {
//reset and allow form submission:
document.getElementById("errorMsg").innerHTML = "";
return true;
}
In the first part of the if, you're trying to get a reference to the errorMsg element using a non-existent variable:
document.getElementById(errorMsg).innerHTML = "OOPS!";
In the second, you're accessing the element by its id properly:
document.getElementById("errorMsg").innerHTML = "";
You need to surround 'errorMsg' with single or double quotes.
You should definitely look into using a debugger to help you find problems like these. Chrome Developer Tools are a good place to start.
On page 1, I have a div containing information.
<div id='information'></div>
And on page 2, I have a form with a textarea and a button.
<form>
<textarea id='new-info'></textarea>
<input type='submit' id='submit-info' value='pass'/>
</form>
Now what I want is when I click the submit button, the text inputted in the text area will be posted in div#information changing its previous content.
I have seen many other post on how to change div content, but those were unrelated to my problem.
One way is to do like what the other answers mentioned, to have each tab communicate to a central server that will get/send data to keep both tabs updated using AJAX for example.
But I'm here to tell you about another way though, it's to use what we already have designed for this kind of task exactly. What so called browser localStorage
Browser storage works like this pseudo code:
//set the value, it works as a hash map or assoc array.
localStorage .setItem("some_index_key", "some data") ;
// get the value by it's index key.
localStorage .getItem("some_index_key") ; // will get you "some data"
Where all the data will be shared among all open tabs for the same domain. And you can add event listener so whenever one value change, it will be reflected on all tabs.
addEvent(window, 'storage', function (event) {
if (event.key == 'some_index_key') {
output.innerHTML = event.newValue;
}
});
addEvent(myInputField, 'keyup', function () {
localStorage.setItem('some_index_key', this.value);
});
Check out this DEMO, you edit one field on page-A, and that value will be reflected on page-B offline without the need to burden the network.
To learn more, read this.
Real live example. The background color is controlled from another tab.
var screenone = document.getElementById('screenone');
screenone.addEventListener('keydown', screenOneFunction);
screenone.addEventListener('change', screenOneFunction);
function screenOneFunction()
{
document.body.style.backgroundColor = this.value;
localStorage.setItem("color1", this.value);
}
var screentwo = document.getElementById('screentwo');
screentwo.addEventListener('keydown', function (evt) {
localStorage.setItem("color2", this.value);
});
screentwo.addEventListener('change', function (evt) {
localStorage.setItem("color2", this.value);
});
var thebutton = document.getElementById('thebutton');
thebutton.addEventListener('click', function (evt) {
localStorage.clear();
screenone.value = "";
screentwo.value = "";
document.body.style.backgroundColor = "";
});
var storageHandler = function () {
document.body.style.backgroundColor = localStorage.color2;
var color1 = localStorage.color1;
var color2 = localStorage.color2;
screenone.value = color2;
screentwo.value = color1;
};
window.addEventListener("storage", storageHandler, false);
.screenone{ border: 1px solid black;}
input{ margin: 10px; width: 250px; height: 20px; border:round}
label{margin: 15px;}
<html>
<head>
</head>
<body>
<label> Type a color name e.g. red. Or enter a color hex code e.g. #001122 </label>
<br>
<input type="text" class="screenone" id="screenone" />
<label> This tab </label>
<br>
<input type="text" class="screentwo" id="screentwo" />
<label> Other opned tabs </label>
<br>
<input type="button" class=" " id="thebutton" value="clear" />
</body>
</html>
Hope this will give you an idea of how you can do it:
Page 2
HTML
<form>
<textarea id='new-info'></textarea>
<input type='submit' id='submit-info' value='pass'/>
</form>
JS
$("form").submit(function(e){
e.preventDefault();
$.post('save_data.php', { new_info:$("#new-info").val() }).done(function(data){
// Do something if you want to show that form has been sent
});
});
save_data.php
<?php
if (isset($_POST['new-info'])) {
// Update value in DB
}
?>
Page 1
HTML
<div id='information'>
</div>
JS
setInterval(search_after_info, 1000);
function search_after_info() {
$.get('get_data', function(data) {
$("#information").html(data);
});
}
You mean some thing like this ?
$("#submit-info").click(function() {
var content = $("#new-info").text();
$("#information").html(content);
});
If you thing about server side, tell more about technology, which you use.
This is exactly as the following:
Page 1:
<form action="test2.htm" method="get">
<textarea name ='new-info'></textarea>
<input type = 'submit' id='submit-info' value ='pass' onclick="postData();"/>
Page 2
<div id="information"></div>
<script>
if (location.search != "")
{
var x = location.search.substr(1).split(";")
for (var i=0; i<x.length; i++)
{
var y = x[i].split("=");
var DataValue = y[1];
document.getElementById("information").innerHTML = DataValue;
}
}
</script>