How to load content from another php page using jQuery .load() function? - javascript

I'm using a simple .load() function from Jquery to load a div element with id from another file in the same folder when changing the selected option in selector. But I can't make it work. Nothing happens when I change the selected option the server gives error "No such file or directory" and My alert ("Before load") does work.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<select id="productType" onchange="load_special_data()">
<option id="Book" selected>Book</option>
<option id="DVD">DVD</option>
<option id="Furniture">Furniture</option>
</select>
<div id="specialData"></div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery("#productType").change(load_special_data());
});
function load_special_data()
{
var selected_id = $("#productType option:selected").attr("id");
alert("Before load");
try {
jQuery("#specialData").load('form_special_data.php #Book', null, function (responseText, textStatus, xhr) {
alert(textStatus); // see what the response status is
});
} catch (e) {
alert(e.message);
}
}
</script>
</html>
Content of form_special_data.php:
<div id="Book">
<label for="weight">Weight (KG) </label>
<input type="number" required class="form-control" name="weight" id="weight">
<small>Please provide book weight in KG</small>
</div>
<div id="Furniture">
<label for="height">Height (CM) </label>
<input type="number" required class="form-control" name="height" id="height">
<label for="width">Width (CM) </label>
<input type="number" required class="form-control" name="width" id="width">
<label for="length">Length (CM) </label>
<input type="number" required class="form-control" name="length" id="length">
</div>

First of all, you shouldn't invoke the load_special_data function more than once.
Remove the onchange="load_special_data()", and leave it like this:
<select id="productType">
Put all the JQuery related functions inside the jQuery(document).ready(function(){ ...
Like this:
jQuery(document).ready(function() {
jQuery("#productType").change(load_special_data());
function load_special_data() {
var selected_id = $("#productType option:selected").attr("id");
alert("Before load");
try {
jQuery("#specialData").load('form_special_data.php #Book', null, function (responseText, textStatus, xhr) {
alert(textStatus); // see what the response status is
});
} catch (e) {
alert(e.message);
}
}
});
About the No such file or directory error, that's one of the easiests errors to fix. Verify that the file name and path are correct.
Finally, I don't know what's your final goal here, but I'd use AJAX instead of "load" because it's more practical and easier to use.

Related

Select / Deselect All Checkboxes using jQuery in Thymeleaf

I am trying to add the function of selecting and deselecting all fields. What I have now doesn't work for me and I don't know why? Does anyone know why?
.....
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://igoradamenko.github.io/awsm.css/css/awsm.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<title>Report</title>
<script>
$("#selectAll").click(function() {
$("input[type=checkbox]").prop("checked", $(this).prop("checked"));
});
</script>
</head>
....
<label for='selectAll'><input id="selectAll" type="checkbox">Select All </label>
<input checked="checked" type="checkbox">Test</label>
<label th:each="item : ${userConfig.isEnableMap}">
<input checked="checked" type="checkbox" th:text="${item.key}" th:field="*{isEnableMap['__${item.key}__']}"/>
</label>
I added changes and it works now
<script>
$(document).ready(function () {
$("#selectAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
});
</script>
You can try :
$("input[type=checkbox]").prop("checked",true);

jQuery code not executing code when javascript is executed?

Code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<div class="container mt-4">
<h1 class="text-left" style="margin-bottom: 50px">Daily Fridge & Freezer Monitoring Record</h1>
<form action="/auth/21-TEMP-01b" method="post" id="form">
<div class="form-group">
<label>Select Fridge Or Freezer</label>
<select class="form-control" id="fridgeFreezer" name="fridge">
<option value="Fridge-1">Fridge 1</option>
<option value="Fridge-2">Fridge 2</option>
</select>
</div>
<div class="form-group fridges Fridge-1">
<h4>Fridge 1</h4>
<label>Temperature °C</label>
<input class="form-control" type="number" id="temperature-1" name="temperature-1">
<label>Comments</label>
<textarea class="form-control" rows="3" id="comments-1" name="comments-1"></textarea>
</div>
<div class="form-group fridges Fridge-2">
<h4>Fridge 2</h4>
<label>Temperature °C</label>
<input class="form-control" type="number" id="temperature-2" name="temperature-2">
<label>Comments</label>
<textarea class="form-control" rows="3" id="comments-2" name="comments-2"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
$(this).find("option:selected").each(function(){
if($(this).attr("value")=="Fridge-1"){
$(".fridges").not(".Fridge-1").hide();
$(".Fridge-1").show();
}
else if($(this).attr("value")=="Fridge-2"){
$(".fridges").not(".Fridge-2").hide();
$(".Fridge-2").show();
}
else{
$(".fridges").hide();
}
});
})
.change();
var temp1 = document.getElementById('temperature-1');
var form = document.getElementById('form');
form.addEventListener('submit', function(e) {
if(temp1.value === '' || temp1.value == null) {
e.preventDefault()
document.querySelector('#fridgeFreezer [value="Fridge-1"]').selected = true;
alert("temp1 not fully filled")
}
})
});
</script>
</body>
</html>
Idea
I am trying to create form validation.
Running the above code details
You will see when you change the option in the drop down menu - different div element loads up. This is done through the jQuery code in the script.
Option 1
Option 2
Next, Javascript
I will be using Javascript to validate the form.
I only have started out validating the first div element of fridge 1. If value is empty I have an alert saying which input has not been filled.
In this scenario I have cleared out all data from Fridge 1 to run the if statement for the error.
Notice this line of code:
document.querySelector('#fridgeFreezer [value="Fridge-1"]').selected = true;
This re-selects the option to the one has the error.
But when I run it - this happens.
Div element of fridge-2 is still showing? How come is the jQuery not executing ?
You have to trigger a change event if you want the change event listener to execute.
form.addEventListener('submit', function(e) {
if(temp1.value === '' || temp1.value == null) {
e.preventDefault()
$('#fridgeFreezer').val("Fridge-1"); // can be simplified like this
$('#fridgeFreezer').trigger("change"); // important line
alert("temp1 not fully filled")
}
})

Check a checkbox in an html page

Good afternoon,
I am trying to tick a checkbox in my html page using a script.
Unfortunately, I get the following error message :
SCRIPT5007: Unable to set property 'checked' of undefined or null reference
File: ajax3, Line: 37, Column: 5
Do you have an idea what went wrong in my code?
Thanks a lot and have a great Sunday.
Laurent
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo for Ajax Auto Refresh</title>
<link rel="stylesheet" type="text/css" href="css/mystyle_day.css" />
<script src="jquery-2.1.3.min.js"></script>
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* update counter */
$('#message-list').data('counter',response.current);
/* check if with response we got a new update */
if(response.update==true){
$('#message-list').html(response.news);
sayHello();
}
});
}
//Every 1 sec check if there is new update
setInterval(check,1000);
</script>
<script>
function sayHello(){
//console.log("Coucou");
check();
}
function check() {
document.getElementById("chk1").checked = true;
}
function uncheck() {
document.getElementById("chk1").checked = false;
}
</script>
</head>
<body>
<div id="message-list" data-counter="<?php echo (int)$db->check_changes();?>">
</div>
<input type="checkbox" name="chk1" id="chk1"> Living room<br>
<input type="checkbox" name="chk2" id="chk2"> Entrance<br>
<input type="checkbox" name="chk3" id="chk3"> Kitchen<br>
</body>
</html>
As suggested by nmnsud and gcampbell, I have replaced value="chk1" by id="chk1". The correct bit of code is now the following :
<input type="checkbox" name="chk1" id="chk1"> Living room<br>
<input type="checkbox" name="chk2" id="chk2"> Entrance<br>
<input type="checkbox" name="chk3" id="chk3"> Kitchen<br>
Thanks a lot for your contribution. Best wishes,
Laurent

Javascript Code isn't submitting to Parse

I am creating an app to send an object to a class in Parse, but the data in the form is being passed and nothing happens. I can submit data directly from the function showAlert, but no alert appears after setNotification and and showALert is used. Here is my code:
<!doctype html>
<head>
<meta charset="utf-8">
<title>My Parse App</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.18.min.js"></script>
</head>
<body>
<div id="main">
<h1>You're ready to use Parse!</h1>
<p>Read the documentation and start building your JavaScript app:</p>
<ul>
<li>Parse JavaScript Guide</li>
<li>Parse JavaScript API Documentation</li>
</ul>
<div style="display:none" class="error">
Looks like there was a problem saving the test object. Make sure you've set your application ID and javascript key correctly in the call to <code>Parse.initialize</code> in this file.
</div>
<div style="display:none" class="success">
<p>You're message has now been submited.'</p>
</div>
</div>
<div class="login">
<form class="login-form" name="login-form">
<h2>Compose Message</h2>
<input type="text" name="school" id="school" placeholder="School Code" />
<p> </p>
<input type="text" name="name" id="name" placeholder="Name" />
<p> </p>
<input type="text" name="password" id="password" placeholder="Message" />
<p> </p>
<input type="button" value="Set Notification" onClick="setMessage();">
<p> </p>
<input type="button" value="Send Notification" onClick="showAlert();">
</form>
</div>
<script type="text/javascript">
function setMessage (){
var textField = form.school.value
var textField1 = form.name.value
var textField2 = form.password.value
}
function showAlert() {
Parse.initialize("appkey", "javascript key");
var TestObject = Parse.Object.extend(textField);
var testObject = new TestObject();
testObject.save({teacher: textField1), message:textField2)}, {
success: function(object) {
$(".success").show();
alert('The Message has been sent!');
},
error: function(model, error) {
$(".error").show();
alert('There has been an error.');
}
});
}
</script>
</body>
</html>
I am dusting off my Javascript knowledge to create an page that syncs to an iOS app. Any help is greatly appreciated!

How to submit form data to html5 local database

I am writing this very small application to run on an iPod. It is meant to store information based on a workout that I enter in. The storage will be html5 local database. My question is how do I get the information from the form which has multiple exercises and create a new record for each exercise? The html is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>lower</title>
<meta name="description" content="" />
<meta name="author" content="john" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="work.js" type="text/javascript" charset="utf-8"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="viewport" content="width=device-width; initial-scale=0.5; maximum-scale=0.6; minimum-scale=0.6; user-scalable=0;" />
</head>
<body>
<h1>Lower Body</h1>
<div>
<form method="post" id="workout_form">
<div>
<table id="hipadd">
<label for="hipAddReps">Hip Adductor</label>
<tr><td>Seat <input type="text" id="hipAddSeatSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="hipAddReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="hipAddWeight" size="3" /></td></tr>
</table>
</div><br />
<div>
<table id="hipab">
<label for="hipAbReps">Hip Abductor</label>
<tr><td>Seat <input type="text" id="hipAbSeatSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="hipAbReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="hipAbWeight" size="3"/></td></tr>
</table>
</div><br />
<div>
<table id="legcurl">
<label for="legCurlReps">Leg Curl</label>
<tr><td>Back <input type="text" id="legCurlBackSetting" size="1"/></td><td>Feet </td><td><input type="text" id="legCurlFeetSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="legCurlReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="legCurlWeight" size="3"/></td></tr>
</table>
</div><br />
<div>
<table id="legext">
<label for="legExtensionReps">Leg Extension</label>
<tr><td>Back <input type="text" id="legExtensionBackSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="legExtensionReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="legExtensionWeight" size="3"/></td></tr>
</table>
</div><br />
<div>
<table id="legpress">
<label for="legPressReps">Leg Press</label>
<tr><td>Back <input type="text" id="legPressBackSetting" size="1"/></td><td>Seat </td><td><input type="text" id="legPressSeatSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="legPressReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="legPressWeight" size="3"/></td></tr>
</table>
</div><br />
<div>
<table id="glute">
<label for="gluteReps">Glute</label>
<tr><td>Seat <input type="text" id="gluteSeatSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="gluteReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="gluteWeight" size="3"/></td></tr>
</table>
</div><br />
<div>
<button type="button" onclick="insertData()">Submit</button>
</div>
</form>
</div>
</body>
</html>
and the JavaScript I have so far is
$(function(){ initDatabase();
});
function initDatabase() {
try {
if (!window.openDatabase) {
alert('Local Databases are not supported by your browser.');
} else {
var shortName = 'WorkoutDB';
var version = '1.0';
var displayName = 'Workout Database';
var maxSize = 100000;
db = openDatabase(shortName, version, displayName, maxSize);
createTables();
}
} catch(e) {
if (e == 2) {
// Version mismatch.
console.log("Invalid database version.");
} else {
console.log("Unknown error "+ e +".");
}
return;
}
}
$(document).ready(function(){
db.transaction(function (transaction) {
//transaction.executeSql('drop table workout');
transaction.executeSql('CREATE TABLE IF NOT EXISTS workout(name TEXT, back TEXT, seat TEXT, feet TEXT, reps TEXT, weight TEXT);', [], nullDataHandler, errorHandler);
}
);
//insertData();
});
function insertData(){
var data = [$("label[for=hipAddReps]").text(), '', $('#hipAddSeatSetting').val(), '', $('#hipAddReps').val(), $('#hipAddWeight').val()];
db.transaction(function (transaction) {
transaction.executeSql("INSERT INTO Workout(Name, Back, Seat, Feet, Reps, Weight) VALUES (?, ?, ?, ?, ?, ?)", [data[0], data[1], data[2], data[3], data[4], data[5]]);
});
}
function errorHandler(transaction, error){
if (error.code==1){
// DB Table already exists
} else {
// Error is a human-readable string.
console.log('Oops. Error was '+error.message+' (Code '+error.code+')');
}
return false;
}
function nullDataHandler(){
console.log("SQL Query Succeeded");
}
so what I want is to fill in all of the fields on this form and hit the submit button at the bottom and have a new record inserted for each exercise I have.
Since you are going to make an application for the iOS (iPod), you would normally do this in objective C, however to do it in HTML5 you should look into a good framework. Take a look at Phonegap. They even have a getting started guide to get you up and running quickly. An alternative is appcelerator, although its not entirely free.
If you want to save form data to your phone you will need to consider using a light weight database, or flat file storage. Here is a link to phonegap's storage recommendations.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
var db = window.openDatabase("test", "1.0", "Test DB", 1000000);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Open Database</p>
</body>
</html>
If you would like a great book about iphone, ipod and iOS development I would recommend Big Nerd Ranch's book, its a great first time book that walks you through all the red tape with apple's dev account setup.
Good luck, and I recommend re-posting your question with phonegap, and iOS tags to get more exposure.

Categories