javascript serialize on appended divs - javascript

Is it possible to serialize appended forms in jquery? I tried both button.on(click) and form.on(submit), but got a problem. When I use the onclick button it gives me an undefined serialization. When I use form submit, it gives me nothing.
Here's my JS Code:
function main_login(){
$('.main-login').click(function(){
var adpas = prompt("Enter password: ");
if(adpas !== null){
$.ajax({
type: 'post',
url: 'init.php',
data: {data: adpas},
success: function(data){
if(data == "success"){
$('#main-note').css('display', 'initial');
$('#main-note').append(''+
'<div id="note_app" style="height: 450px; width: 700px; background-color: white; border-radius: 10px;">'+
'<div style="height:12px; width:15px; border-radius:10px; background: linear-gradient(red, white);" align="center">X</div>'+
'<center><form action="" id="formmsg" method="post"><input type="text" id="note-title" style="width: 98%; height: 20px; font-size:16px"/>'+
'<textarea id="note-texts" style="width: 98%; height: 400px; resize: none;"></textarea></center>'+
'<input type="submit" value="Encode Lecture" name="btn-lecture" id="btn-lecture"></form></div>');
$('#formmsg').on('submit', function() {
alert($(this).serialize());
});
}
else{
alert('You don\'t have any administrative rights to open this link.');
}
}
});
}
});
}
Another question:
It seems that every time I successfully click "main-login class", it gives me the same number of divs it is clicked. Is there anyway to make the button trigger only once, only if the password was accepted and successful?
Tried jQuery.one(); it worked but both for successful and failed login.
Thanks in advance.

Basically you are trying to attach an event to an element which was created dynamically! So here event delegation helps you and instead of keeping event inside success of ajax, which is obviously not a good thing, put it outside! Following will be the changes you need to do!!
$('.main-login').click(function(){
var adpas = prompt("Enter password: ");
if(adpas !== null){
$.ajax({
type: 'post',
url: 'init.php',
data: {data: adpas},
success: function(data){
if(data == "success"){
$('#main-note').css('display', 'initial');
$('#main-note').append(''+
'<div id="note_app" style="height: 450px; width: 700px; background-color: white; border-radius: 10px;">'+
'<div style="height:12px; width:15px; border-radius:10px; background: linear-gradient(red, white);" align="center">X</div>'+
'<center><form action="" id="formmsg" method="post"><input type="text" id="note-title" style="width: 98%; height: 20px; font-size:16px"/>'+
'<textarea id="note-texts" style="width: 98%; height: 400px; resize: none;"></textarea></center>'+
'<input type="submit" value="Encode Lecture" name="btn-lecture" id="btn-lecture"></form></div>');
}
else{
alert('You don\'t have any administrative rights to open this link.');
}
}
});
}
});
Now your form submit event:
$('#main-note').on('submit','#formmsg', function() {
console.log($(this).serialize());
});
That should work now.

Related

jQuery css("display","table-cell") isn't immediately applied

<table style="border: none; margin-top: 40px; width: 100%;">
<tr>
<td id="adparser" style="width: 74.5%;"/>
<td id="thumbnailsSection" style="border: 2px solid black; display: none;">
<div style="text-align: center;">
<img src="arrow-right.png" style="border: 1px solid black; float: left; width: 16px; height: 16px;"/>
Identified Ads
</div>
<ol id="thumbnailsList" style="list-style-type: none;">
<div class="thumbnail">
<img src="https://s3.amazonaws.com/hiro-marketplace/thumb/413ce7c54ae87f9644b27a6d38790c2a.png"
style="width: 256px; height: 256px;"/><br/>
More Details<span><img src="play.png" style="width: 24px; height: 24px;"/></span>
</div>
<!-- More items... -->
</ol>
</td>
</tr>
</table>
Ok, so #thumbnailsSection starts with "display: none".
Later:
function requestChainsButtonClicked()
{
$.ajax(
{
type: "GET",
url: "json_simple.json" + queryString,
success: function(data,status,XMLHttpRequest)
{
if (($.isArray(data))&&(data.length>0)&&($.isPlainObject(
data[0])))
{
nodeID=0;
chartConfig.nodeStructure=buildTreeNode(data[0]);
}
new Treant(chartConfig);
$(".viewCell").click(viewThumbnailsClicked);
}
});
So when the user clicks a button, the content of the first table cell is built, and when the user clicks one of the .viewCell buttons (which are part of the tree in the first cell):
function viewThumbnailsClicked()
{
$.ajax(
{
type: "GET",
url: "thumbnails.json",
error: function(XMLHttpRequest,status,message)
{
$("#thumbnailsSection").css("display","none");
alert(status + ": " + message);
},
success: function(data,status,XMLHttpRequest)
{
var thumbnailsListSelector=$("#thumbnailsList");
thumbnailsListSelector.empty();
if ($.isArray(data))
{
for (var index=0;index<data.length;index++)
{
var thumbnailHTML="<div class=\"thumbnailItem\">";
thumbnailHTML+="<img class=\"thumbnail\" src=\"";
thumbnailHTML+=data[index].thumbUrl + "\"/><br/>";
thumbnailHTML+="More Details<span><img src=\"";
thumbnailHTML+="play.png\" class=\"details\"/>";
thumbnailHTML+="</span></div>";
thumbnailsListSelector.append(thumbnailHTML);
}
}
$("#thumbnailsSection").css("display","table-cell");
}
});
So, I would expect the second table cell (#thumbnailsSection) to appear immediately when I click the button, but it doesn't happen! Only after I click again the button that builds the first table cell, the second one is displayed.
What's actually the issue? Do I need to do some refresh on the table to see the second cell? Thanks.
Try It on ajax success but I am not sure
$("#thumbnailsSection").css("display","table-cell");
var thumbnailsListSelector=$("#thumbnailsList");
thumbnailsListSelector.empty();
if ($.isArray(data))
{
for (var index=0;index<data.length;index++)
{
var thumbnailHTML="<div class=\"thumbnailItem\">";
thumbnailHTML+="<img class=\"thumbnail\" src=\"";
thumbnailHTML+=data[index].thumbUrl + "\"/><br/>";
thumbnailHTML+="More Details<span><img src=\"";
thumbnailHTML+="play.png\" class=\"details\"/>";
thumbnailHTML+="</span></div>";
thumbnailsListSelector.append(thumbnailHTML);
}
}

Checking if searched item exists in database - PHP won't output anything but will still add item to the database

I'm learning PHP and am looking to solve my PHP, JS and SQL issue.
If necessary, to ensure you understand exactly what the issue is, you may need you to set up the HTML, CSS, PHP and JS to work with your SQL database. I ask of your time only if you have it.
As you can probably tell, I have a search bar. The user types their interest into the search bar and it adds that interest to the database. If their interest exists in the database (as in someone else has the same interest) it uses an if statement to say so. However, for some reason it will not do anything if an interest is found (not even that test alert). It will however insert something into the database (in this case the number of other existing interests) which is very strange. I have inserted comments in the PHP file to explain what is happening and where the issue is.
Here is the PHP, JS, CSS and HTML respectively:
<?php
error_reporting(E_ALL ^ E_NOTICE);//TO REMOVE THE ANNOYING KEYWORD ERRORS
function connect() {
return new PDO('mysql:host=localhost;dbname=mysite', 'username', 'pw', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
//GET THE USERS IP
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else{
$ip=$_SERVER['REMOTE_ADDR'];
}
$pdo = connect();
//OUTPUT THE SEARCHBAR SUGGESTIONS (OBTAIN SUGGESTIONS FROM DATABASE)
$testing = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM interests WHERE interestName LIKE (:testing) ORDER BY id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':testing', $testing, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
$interestName = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['interestName']);
$interestlist = '<li onclick="set_item(\''.str_replace("'", "\'", $rs['interestName']).'\')">'.$interestName.'</li>';
if (strlen($_POST['keyword']) > 0){
echo $interestlist; //THIS IS THE SUGGESTION BAR OUTPUT WITH THE SUGGESTIONS
}
}
//EVERYTHING ABOVE THIS WORKS.. THIS IS THE ISSUE HOWEVER:
if(isset($_POST['counter'])=="counter"){
//INSERT THE INTEREST INTO THE DATABASE, WITH THE USER'S IP.
$interestid=$_POST['interestinput'];
$insertion = "INSERT INTO users (ipaddress, interest)
VALUES ('$ip', '$interestid')";
$pdo->query($insertion);
//INSERTION WORKS. NOW I WANT TO CHECK IF INTEREST EXISTS. IF IT DOES EXIST, PRINT 'Users exist!':
$item ="SELECT * FROM `users` WHERE interest LIKE '$interestid'";
$result = $pdo->query($item)->fetchAll();
$counted = count($result); //COUNT NUMBER OF RESULTS, THEN INSERT IT AS A TEST.
$insertion = "INSERT INTO users (ipaddress, interest)
VALUES ('$ip', '$counted')";
if (count($result) > 1) {
$pdo->query($insertion); //TEST IF IT WORKS -- THIS INSERTS THE TOTAL NUMBER OF SAME INTERESTS. IT WORKS!
//BUT..
echo ("Users exist!"); //THIS DOES NOTHING? <--------- THE ISSUE
echo "<script> alert('Test'); </script>"; //THIS ALSO DOES NOTHING (as a test)
}
}
?>
//THIS FUNCTION IS CALLED WHEN THE USER HITS ENTER:
function enterPressed(e, field) {
if (e.keyCode == 13) {
var tb = document.getElementById("searchbox");
if (field.value.length > 0) {
document.getElementById('searching').style.display='block';
document.getElementById('searchdisappear').style.display='none';
$.ajax({
type: 'POST',
url: './php/phprefresh.php',
data: {interestinput: field.value, counter: "counter"},
});
}
}
}
//THIS FUNCTION GIVES INTEREST SUGGESTIONS (PULLED FROM THE DATABASE):
function autocomplet() {
var workchecker = 0
var min_length = 1;
var keyword = $('#searchbox').val();
if (keyword.length == min_length) {
$.ajax({
url: './php/phprefresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#interest_list_id').show();
$('#interest_list_id').html(data);
}
});
} else {
$('#interest_list_id').hide();
}
}
//THIS FUNCTION SETS THE SUGGESTION INTO THE SEARCH BOX WHEN CLICKED
function set_item(item) {
$('#searchbox').val(item);
$('#interest_list_id').hide();
}
/*Input*/
input.interestsearch {
margin: auto;
margin-top: 30px;
width: 540px;
height: 30px;
font-size: 22px;
display: block;
padding: 2px 2px 2px 8px;
outline: none;
}
.input_container {
padding: auto;
margin: auto;
margin-top: -10px;
width: 520px;
display: block;
outline: none;
font-size: 20px;
}
.input_container ul {
list-style: none;
border-radius: 15px;
padding: 5px;
color: black;
}
.input_container ul li:hover {
border: 1px solid black;
border-radius: 15px;
cursor: pointer;
width: 500px
}
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Testsite</title>
<link rel="stylesheet" type="text/css" href="./css/main.css">
<script src ="./js/search.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body">
<!-- SEARCH BAR -->
<div id="searchdisappear" style="display:block;">
<center><h1> INTEREST SEARCH </h1></center>
<input class="interestsearch" id="searchbox" maxlength="200" type="text" title="Search for an interest" onkeyup="autocomplet();" autocomplete="off" onkeypress="enterPressed(event, searchbox);" placeholder="Search for an interest.."/>
<div class="input_container">
<ul id="interest_list_id"></ul>
</div>
</div>
<!-- CONNECTING PEOPLE WITH SAME INTEREST-->
<div id="searching" style="display:none;">
<center> <p>Finding people..</p></center>
</div>
</html>
Do not hesitate to ask any questions about the code. I am happy to answer anything!
I really appreciate anyone's time. It has been driving me crazy for far too long.
Add a
<div id="response"></div>
to your HTML which will display the result then add a success: argument in the enterPressed function. ie.
function enterPressed(e, field) {
if (e.keyCode == 13) {
var tb = document.getElementById("searchbox");
if (field.value.length > 0) {
document.getElementById('searching').style.display='block';
document.getElementById('searchdisappear').style.display='none';
$.ajax({
type: 'POST',
url: './php/phprefresh.php',
data: {interestinput: field.value, counter: "counter"},
success: function() {
$("#response").html("<p>User Exists</p>");
}
});
}
}
}
If you want to display echo text (in HTML form) from phprefresh.php change the success: to
success: function(data) {
$("#response").html(data);
}

Node Jquery load pages into div error

// Userlist data array for filling in info box
var userListData = [];
// DOM Ready =============================================================
$(document).ready(function() {
// Populate the user table on initial page load
populateTable();
// Username link click
$('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);
// Add User button click
$('#btnAddUser').on('click', addUser);
// Delete User link click
$('#userList table tbody').on('click', 'td a.linkdeleteuser', deleteUser);
//Set Default page to Home.html
$('#content').load('views/home.html');
//Call navBar function
navBar();
projectBtn();
});
// Functions =============================================================
//Navbar function
function navBar() {
$('ul#navtest li a').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
function projectBtn() {
$('a.projectbutton').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
// Fill table with data
function populateTable() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON( '/users/userlist', function( data ) {
// Stick our user data array into a userlist variable in the global object
userListData = data;
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function(){
tableContent += '<tr>';
tableContent += '<td>' + this.username + '</td>';
tableContent += '<td>' + this.email + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#userList table tbody').html(tableContent);
});
};
// Show User Info
function showUserInfo(event) {
// Prevent Link from Firing
event.preventDefault();
// Retrieve username from link rel attribute
var thisUserName = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);
// Get our User Object
var thisUserObject = userListData[arrayPosition];
//Populate Info Box
$('#userInfoName').text(thisUserObject.fullname);
$('#userInfoAge').text(thisUserObject.age);
$('#userInfoGender').text(thisUserObject.gender);
$('#userInfoLocation').text(thisUserObject.location);
};
// Add User
function addUser(event) {
event.preventDefault();
// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addUser input').each(function(index, val) {
if($(this).val() === '') { errorCount++; }
});
// Check and make sure errorCount's still at zero
if(errorCount === 0) {
// If it is, compile all user info into one object
var newUser = {
'username': $('#addUser fieldset input#inputUserName').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'age': $('#addUser fieldset input#inputUserAge').val(),
'location': $('#addUser fieldset input#inputUserLocation').val(),
'gender': $('#addUser fieldset input#inputUserGender').val()
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
// Clear the form inputs
$('#addUser fieldset input').val('');
// Update the table
populateTable();
}
else {
// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);
}
});
}
else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;
}
};
// Delete User
function deleteUser(event) {
event.preventDefault();
// Pop up a confirmation dialog
var confirmation = confirm('Are you sure you want to delete this user?');
// Check and make sure the user confirmed
if (confirmation === true) {
// If they did, do our delete
$.ajax({
type: 'DELETE',
url: '/users/deleteuser/' + $(this).attr('rel')
}).done(function( response ) {
// Check for a successful (blank) response
if (response.msg === '') {
}
else {
alert('Error: ' + response.msg);
}
// Update the table
populateTable();
});
}
else {
// If they said no to the confirm, do nothing
return false;
}
};
.border {
border: 4px solid black; }
.back2 {
background-color: #232323; }
.marginleft {
margin-left: 8%; }
.margin {
margin-right: 4%;
margin-left: 4%;
margin-top: 2%;
margin-bottom: 2%; }
.padding {
padding: 1%; }
.margintop {
margin-top: 1%; }
.margintop2 {
margin-top: 5%; }
.iconmargintop {
margin-top: 50px; }
.fill {
height: 100%;
width: 100%; }
p {
color: #ffffff; }
label {
color: #ffffff; }
h1 {
color: #ffffff; }
h2 {
color: #ffffff; }
th {
color: #ffffff; }
span {
color: #ffffff; }
h3 {
color: #ffffff; }
.projectseltext {
padding: 1%;
margin: 1%; }
.background {
background-color: #333333;
position: relative;
height: 100%; }
#blacktext {
color: black; }
.disablelink {
pointer-events: none;
cursor: default; }
.nav {
background-color: #b2b2b2; }
.nav a {
color: #ffffff;
font-size: 11px;
font-weight: bold;
padding: 14px 10px;
text-transform: uppercase; }
.nav li {
display: inline; }
.back1 {
background-color: #0c0c0c; }
.fit {
height: 100%;
width: 100%; }
.well {
background-color: #333333; }
.backg1 {
background-color: #333333; }
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="project">
<div class="container-fluid row">
<a href="#" title="projectnew" class="projectbutton">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin col-md-3" style="width:150px;" />
<h1 class="margin" style="margin-top:75px;">New Projects</h1>
</div>
</a>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<link rel="stylesheet" href="stylesheets/bootstrap.min.css" />
<link rel="stylesheet" href="stylesheets/main.css" />
<script src="build/js/jquery-2.2.4.min.js"></script>
<script src="build/js/bootstrap.min.js"></script>
<script src="build/js/global.js"></script>
<title></title>
</head>
<body class="background">
<div class="container-fluid nav navbar-inverse">
<ul id="navtest" class="margintop">
<li>
Home
</li>
<li>
Projects
</li>
<li>
Contact
</li>
<li>
Resume
</li>
<li>
About
</li>
<li>
Database
</li>
</ul>
</div>
<div id='content' class="tab-content" />
</body>
</html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="projectnew">
<div class="row">
<div class="container col-md-12 margintop marginleft">
Back
</div>
<div class="container-fluid margin">
<a href="" data-toggle="tab">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin" style="width:150px" />
<h1 class="margin">Comming soon.</h1>
</div>
</a>
</div>
</div>
</div>
</body>
</html>
This file is temporary, i know the contents wont do anything.
The function navBar works perfectly, however when trying to apply the same method to another class and div it seems to fail.
Whenever i click on the projectbutton class it redirects to error.html. For some reason the javascript is not seeing/handling the class on click and the href being an unsupported type redirects me to error.html. However i'm not sure what is wrong with my code.
welcome;
In your HTML code, <a href="projectnew" class="projectbutton"> you have an href for your a element, if you click on this, it will go to the page "www.yourdomain.com/projectnew" since this page does not exist, you will be redirected to your error page...
To solve this problem, you should use preventDefault, in order to prevent your link element to operate things that you do not want.
$('a.projectbutton').click(function(event) {
event.preventDefault();
var page = $(this).attr('href');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
I did not try it out, but it should work.
Read more about preventDefault: https://api.jquery.com/event.preventdefault/
OR;
Since the main problem is your href attributes in your a elements, try to remove them;
Home
Use title as your specifier in your JS;
$('a.projectbutton').click(function() {
var page = $(this).attr('title'); //changed this into title.
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});

How to get control back from a php script to my main page?

I have a javascript code in my main HTML page Smartmeter.html by which I am displaying meter data which is getting changed every 5s.
Now I need to insert this meter data which is getting changed in the javascript function into mysql via php every 30s.
Means I need to stay on the Smartmeter.html page as the javascript function is getting executed 5s and in the meantime also insert this meter data(variable--target) into mysql every 30s.
How can I achieve this? Can someone help me with some code or suggestions.
My Smartmeter.html page:
<html>
<head></head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
window.onload=dynamic;
var target=100;
function dynamic()
{
var1=Math.random();
target=target + var1 * 1000;
target=Math.round(target);
if(target>123457)
{
target=15647;
}
document.getElementById('hidden').value = target;
func();
}
function func()
{
//configuration of the reading displayed
var primary = document.getElementById("d").getElementsByClassName("imge")[0].getElementsByTagName("h2")[0];
primary.innerHTML=target;
alert('test');
document.forms["myForm"].submit();
// window.location.href = "http://localhost/SUA/Data_insertion.php?target=" + target;
setTimeout(dynamic, 5000);
}
</script>
<body>
<style>
.imge
{
position: absolute;
top: 40%;
left: 30%;
margin-top: -150px;
margin-left: -150px;
}
h2{
position: absolute;
top: 116px;
left: 165px;
width: 100%;
}
p
{
position: absolute;
top: 120px;
left: 250px;
width: 100%;
}
input {
display: inline-block;
float: bottom;
}
</style>
<body bgcolor="#BDBDBD">
<form action="Data_insertion.php" method="post" id="myForm">
<input type="hidden" id="hidden" name="reading" value=""><br>
<input type="submit" value="submit">
</form>
<div id="d">
<div class="imge">
<img src="meter.jpg" width="450" height="350" alt="" />
<h2>1234578 </h2>
<p><font size="5">kWh</font></p>
</div>
</div>
</body>
</html>
jQuery-Solution:
function submitValue(url, key, value){
$.ajax({
type: "POST",
url: url,
data: {
key: key,
value: value
},
success: function(data){
alert("done: "+data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error');
}
});
}
Process your data like this:
<?php
switch($_POST['key']){
case "voltage": setVoltage($_POST['value']); break;
case "current": setCurrent($_POST['value']); break;
default: http_response_code(404); die() break;
}
echo "successful set ".$_POST['key']." to ".$_POST['value'];
function setVoltage($voltage){
/* sql magic */
}
function setCurrent($current){
/* sql magic */
}
?>
EDIT
For your Problem this simple version should work:
function sendValue(){
$.ajax({
type: 'POST',
url: 'Data_insertion.php',
data: {
reading: target
},
success: function(data){
alert('done');
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error');
}
});
}
function init(){
// remove this line from function func()
setTimeout(dynamic, 5000);
setTimeout(sendValue, 30000);
}
and Change
<body bgcolor="#BDBDBD">
<form action="Data_insertion.php" method="post" id="myForm">
<input type="hidden" id="hidden" name="reading" value=""><br>
<input type="submit" value="submit">
</form>
to
<body bgcolor="#BDBDBD" onLoad="init()">
<button onClick="sendValue(target)">Submit</button>

Close toggle when clicking away from div

I have a calendar that opens up when the input is clicked, and it can be closed by a cross(X. I need the calendar to close when clicking anywhere else on the page. I have tried various methods on Stackoverflow but I think there are conflicts with the original scripts. I'm guessing there is something I can add to the closeClaendar function to close when outside of div?
function closeCalendar(calendarId) {
$("#" + calendarId).hide();
}
function CalendarMonthChanged(contract, product, dropdtls, form, ticketType, dateselectorid) {
$calendar = $("#CalendarWrapper");
var loader = '<%= Html.StaticImage(Url, "ajax-loader.gif") %>';
$calendar.find(".table").html("<div class = 'calendar-loading' style='width:175px;'><img src = '" + loader + "' /></div>");
var qty = 2;
var dataArray = {
contract: contract,
productId: product,
dropdtls: dropdtls,
formNumber: form,
ticketType: ticketType,
numTickets: qty,
dateSelectorId: dateselectorid
};
$.ajax({
type: "POST",
url: '<%= Url.Action("Calendar", "productapi", null) %>',
data: dataArray,
success: function (response) {
$calendar.html(response);
toggleLayer("CalendarForm1");
}
});
}
<div id="CalendarWrapper">
<div id="Allocation">
<div id="CalendarForm1" class = "CalendarForm" style="display:none;">
<div class="allocation_form bg">
<div class="calendar_header">
<a href="javascript:closeCalendar('CalendarForm1');">
<span class="m-xs-10 halflings remove red"></span>
</a>
<select name="calendar_month" class="form-control" onchange="CalendarMonthChanged('<%= Model.ContractID %>','<%= Model.AWItemId %>',this.value,'<%= Model.FormNumber %>', '<%= Model.TicketType %>', <%= (int)Model.DateSelector %>); ">
<%= Model.Months %>
</select>
</div>
<div id="Loading" class="Loading" style="width:175px;height:172px;display:none;"></div>
<%= Model.Days %>
</div>
</div>
</div>
</div>
Here is one easy way by adding a click handler to document.
jsFiddle: http://jsfiddle.net/6pcq7pvo/3/
$(document).on("click", function (e) {
if ($("#calendar").is(":visible") && !$(event.target).is('#calendar *, #calendar')) {
// user clicked somewhere in the document but not inside the calendar
$("#calendar").hide();
$("#btnOpenCalendar").show();
} else if (event.target.id === "btnOpenCalendar") {
// user clicked the "Show calendar" button
$("#btnOpenCalendar").hide();
$("#calendar").show();
}
else if ($(event.target).is('#calendar span'))
{
// user clicked a date in the calendar
// for demo purposes only; normally your calendar plugin handles this for you
alert("Clicked date: " + $(event.target).text());
}
});
#calendar {
height: 100px;
width: 100px;
border: 1px solid black;
background-color: #ccc;
display: block;
overflow: hidden;
}
#calendar span {
display: inline-block;
width: 17px;
border:1px solid #ddd;
cursor: pointer;
}
#btnOpenCalendar { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>click anywhere in this frame, but outside of the "calendar" (gray box) to close calendar</h3>
<div id='calendar'><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span>
</div>
<input id='btnOpenCalendar' type='button' value='Show calendar' />
Try this:
$(document).click(function(){
if($("#" + calendarId).is(':visible')){
$("#" + calendarId).hide().css("visibility", "hidden");;
}
});
also on your anchor click do, following to avoid hiding the calendar again:
$(document).on('click', 'a', function (e) {
//show calendar
$("#" + calendarId).show()
e.stopPropagation();
});
or instead of e.stopPropagation(); you can also use e.preventDefault();

Categories

Resources