First time poster! Apologies for the large about of code.
The plan is to have a list of users and on clicking on each user a div popup will appear allowing changes to the users details.
Rather than the popup closing when the record is updated I'd like the popup to remain open and show the new details.
At the moment I can open the popup and edit the form without the popup closing. As soon as I add the following the form closes on submit.
$( "#popup > #skills" ).load( "popup_u_skills.php?uid=" + uid );
If I pass don't pass a variable in the url then the popup stays open. The BIG problem I have is that I need to variable to be passed to get the users information from my DB.
My code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// show popup
$(".showpopup").click(function() {
// user id variable
var uid = $(this).attr( "uid" );
$("#popup").fadeIn();
$( "#popup > #details" ).load( "popup_u_details.php?uid=" + uid ).show();
//$( "#popup > #skills" ).load( "popup_u_skills.php?uid=" + uid );
// close popup
$(".closepopup").click(function() {
$("#popup").fadeOut();
});
// open inner options within popup
$(".open_inner_popup").click(function() {
var inneropt = $(this).attr( "option" );
$( "#details, #skills, #history" ).hide();
$.get( "pop_u_skills.php", { uid : uid } );
$( "#"+inneropt ).show();
});
// if change of skill
$("#chg_skill").click(function(event){
// use gloabel uid variable from openpopup
var user = uid;
// set array variable
var selected = new Array();
// foreach checkbox cheked pushed into array
$("input:checkbox[name=checkbox]:checked").each(function() {
selected.push($(this).val());
});
// prevent form action
event.preventDefault();
// post selected array and uid to php page
$.post(
"run_php.php",
{ name: selected, uid: user },
function(data) {
$('#stage').show();
$('#stage').html("Saved!" + data);
});
});
// end open popup
});
// end dom
});
</script>
<style>
#popup {
width:400px;
padding:10px;
display:none;
-webkit-box-shadow: 3px 3px 3px 0px #EEE;
box-shadow: 3px 3px 3px 0px #EEE;
border:1px solid #CCC;
-webkit-border-radius: 5px;
border-radius: 5px;
z-index:1;
}
.closepopup {
color:#FF0000;
font-weight:bold;
text-decoration:none;
}
#stage {
display:none;
color:#009900;
}
#details, #skills, #history {
display:none;
}
</style>
</head>
<body>
<?
$uid = date("H:s:i");
?>
<div id="overlay">
<div class="showpopup" uid="<? echo $uid; ?>">Popup</div>
<div id="popup">
x
<br>
Details Skills History
<div id="details"><? include "popup_u_details.php"; ?></div>
<div id="skills"><? include "popup_u_skills.php"; ?></div>
<div id="history">History</div>
</div>
</div>
</body>
</html>
POPUP_U_SKILLS.PHP
<div id="stage"> </div>
<? echo $_GET["uid"]; ?>
<form name="form1" method="post" action="">
<p>Option 1
<input type="checkbox" name="checkbox" value="1">
</p>
<p>
Option 2
<input type="checkbox" name="checkbox" value="2">
</p>
<p>
Option 3
<input type="checkbox" name="checkbox" value="3">
</p>
<p>
<input type="submit" name="chg_skill" id="chg_skill" value="Update">
</p>
</form>
After re-visiting jquery I have discovered the answer to my problem. Quite simple really.
To keep the popup div open on clicking a submit button within it I needed to include the code below within the submit function. e.g.
$(".submitwithinpopup").click(function() {
Do stuff...
// don't close popup afterwards
return false;
});
Related
A brief explanation of how this simple jQuery wizard works
Sessions are used to save data for each step.
consists of a session variable to save in what step we are.
consists of a session variable to store the form data.
Each time we change the step we save the data of the form and the step in session with an ajax request.
If the data is updated the data is retrieved from the session.
This wizard form consists of 3 steps.
As I can correct the errors and validate the form with php if there is a field without data do not let go to the next step, until all fields of the form are completed by the user.
There are warning errors in each of the form fields in each text input shows me a warning message.
Notice: Undefined index: datos_form in C:\xampp\htdocs\prueba\wizar.php on line 229
I would like to add a cookie to the session where the steps are saved to avoid erasing the data stored in the session in case the browser is closed in error, create a session cookie with a validation time of 30 days.
now to remove the cookie from the data saved by the user create a cancel button, the cancel button will delete the cookie, including the data saved in the session.
My complete code:
wizar.php
<?php
session_start();
// check if there is a previous step.
if ( !empty($_SESSION['datos_form']['__paso__']) ) {
$paso = $_SESSION['datos_form']['__paso__'];
}
// if there is no previous step we set step 1.
else{
$paso = '1';
}
?><!DOCTYPE html>
<html>
<head>
<title>Form por pasos</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
mostrar_paso(<?= $paso; ?>);
});
function animacion(caso){
switch(caso) {
case 1:
$(".backdrop").css("background-position", `0px 0px`);
break;
case 2:
$(".backdrop").css("background-position", `0px -16px`);
break;
case 3:
$(".backdrop").css("background-position", `0px -32px`);
break;
default:
$(".backdrop").css("background-position", `0px 0px`);
};
};
function mostrar_paso(paso)
{
var data = $( "#form" ).serialize();
var url = 'saveTemp.php?paso=' + paso;
var valor_radio = $('input:radio[name=radio]:checked').next("label").text();
$.ajax({
type: "POST",
url: url,
data: data
})
.done(function( resp ) {
$('.step').css( "display", "none" );
$('#paso'+paso).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(paso);
});
};
</script>
</head>
<body>
<div class="setup">
<ul class="backdrop">
<li class="process item1">step 1</li>
<li class="process item2">step 2</li>
<li class="process item3">FINALIZE</li>
</ul>
</div>
<form id="form" action="procesar.php">
<div id="paso1" class="step">
<input type="text" name="campo1" value="<?= $_SESSION['datos_form']['campo1']; ?>">
<select class="form-select" name="sexo">
<?php
if( !empty($_SESSION['datos_form']['sexo']) ) {
$sexo = $_SESSION['datos_form']['sexo'];
echo '<option value="'.$sexo.'" selected="selected">'.$sexo.'</option>';
}
else{
echo '<option disabled selected="selected">I am...</option>';
}
?>
<option value="Mem">Men</option>
<option value="Woman">Woman</option>
<option value="I prefer not to say">I prefer not to say</option>
</select>
<?php
if( !empty($_SESSION['datos_form']['condiciones']) ) {
echo '<input type="checkbox" name="condiciones" checked>';
}
else{
echo '<input type="checkbox" name="condiciones">';
}
?>
...
onclick="mostrar_paso('numero de paso') -->
continuar
</div>
<div id="paso2" class="step">
<?php
$r =array(
1 => 'Product 1',
2 => 'Product 2',
3 => 'Product 3',
);
foreach ($r as $key => $value)
{
if( $_SESSION['datos_form']['radio'] == $key ) {
echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'" checked="checked" >';
echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
}
else{
echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'" >';
echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
}
}
?>
Atras
continuar
</div>
<div id="paso3" class="step">
<div id="div_producto"></div><br>
<input type="text" name="campo3" value="<?= $_SESSION['datos_form']['campo3']; ?>">
<input type="submit" name="cancel">
Atras
<input type="submit" name="Terminar">
</div>
</form>
</body>
</html>
saveTemp.php
Note: This file is responsible for saving the step and data of the form.
<?php
session_start();
// We save the form data in a session variable
$_SESSION['datos_form'] = $_POST;
// we added the step also to the array, you can not use this name (__paso__) as name in the form
$_SESSION['datos_form']['__paso__'] = $_GET['paso'];
As I can correct the errors and validate the form with php if there is
a field without data do not let go to the next step, until all fields
of the form are completed by the user.
You need to code validation rules under saveTemp.php something like this :
<?php
session_start();
//form validation
switch($_GET['paso']){
case 2:
if(empty($_POST['campo1'])){//you may add any validation rule you want here
die(json_encode(array('status' => FALSE,'message' => 'please fill campo ....')));
}
if(empty($_POST['sexo'])){
die(json_encode(array('status' => FALSE,'message' => 'please select sexo ....')));
}
if(empty($_POST['condiciones'])){
die(json_encode(array('status' => FALSE,'message' => 'please select condiciones ....')));
}
break;
case 3: //step 2 validation here
if(empty($_POST['radio'])){//you may add any validation rule you want here
die(json_encode(array('status' => FALSE,'message' => 'please fill radio1 ....')));
}
break;
}
// We save the form data in a session variable
$_SESSION['datos_form'] = $_POST;
// we added the step also to the array, you can not use this name (__paso__) as name in the form
$_SESSION['datos_form']['__paso__'] = $_GET['paso'];
die(json_encode(array('status' => TRUE,'message' => 'Temporary saved....')));
and then check response under ajax call for status, so you need to change ajax call like this:
$.ajax({
type: "POST",
url: url,
data: data,
dataType: 'json'
})
.done(function( resp ) {
if(resp.status)
{
$('.step').css( "display", "none" );
$('#paso'+paso).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(paso);
}else{
var old_paso = paso-1;
alert(resp.message);
$('.step').css( "display", "none" );
$('#paso'+old_paso).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(old_paso);
}
});
notice that I add "dataType" to your ajax call and set it to json
There are warning errors in each of the form fields in each text input
shows me a warning message.
that because you did not check for existence of variable before getting its value, the code you post is form.php but warning complain about wizar.php line number 229, check that line and use empty function just like the rest of your code
here is a sample wizar.php without notice/warning:
<?php
session_start();
// check if there is a previous step.
if ( !empty($_SESSION['datos_form']['__paso__']) ) {
$paso = $_SESSION['datos_form']['__paso__'];
}
// if there is no previous step we set step 1.
else{
$paso = '1';
}
?><!DOCTYPE html>
<html>
<head>
<title>Form por pasos</title>
<style type="text/css">
.backdrop {
position: absolute;
width: 630px;
height: 16px;
background: url(//drh.img.digitalriver.com/DRHM/Storefront/Site/avast/cm/images/avast/2014/breadcrumb-3.png) no-repeat;
list-style-type: none;
text-transform: uppercase;
}
.step {
padding-top: 30px;
display: none;
}
.step-1 {
display: block;
}
.setup {
width: 100%;
height: 100px;
padding: 50px 0px 0px 50px;
background-color: rgba(29, 36, 36, 0.25);
}
.process {
position: absolute;
top: -30px;
color: #e8e8e8;
font-size: 1.1em;
}
.process.item2 {
padding-left: 190px;
}
.process.item3 {
padding-left: 400px;
}
.process.item4 {
padding-left: 580px;
}
.process.item5 {
padding-left: 690px;
}
.process.item6 {
padding-left: 790px;
}
ul li {
margin: 0;
padding: 0;
border: none;
list-style: none;
list-style-type: none;
white-space: nowrap;
}
.step{
display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.step').css( "display", "none" );
$('#paso'+<?= $paso; ?>).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(<?= $paso; ?>);
});
function animacion(caso){
switch(caso) {
case 1:
$(".backdrop").css("background-position", `0px 0px`);
break;
case 2:
$(".backdrop").css("background-position", `0px -16px`);
break;
case 3:
$(".backdrop").css("background-position", `0px -32px`);
break;
default:
$(".backdrop").css("background-position", `0px 0px`);
};
};
function mostrar_paso(paso)
{
var data = $( "#form" ).serialize();
var url = 'saveTemp.php?paso=' + paso;
var valor_radio = $('input:radio[name=radio]:checked').next("label").text();
$.ajax({
type: "POST",
url: url,
data: data,
dataType: 'json'
})
.done(function( resp ) {
if(resp.status)
{
$('.step').css( "display", "none" );
$('#paso'+paso).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(paso);
}else{
var old_paso = paso-1;
alert(resp.message);
$('.step').css( "display", "none" );
$('#paso'+old_paso).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(old_paso);
}
});
};
</script>
</head>
<body>
<div class="setup">
<ul class="backdrop">
<li class="process item1">step 1</li>
<li class="process item2">step 2</li>
<li class="process item3">FINALIZE</li>
</ul>
</div>
<form id="form" action="procesar.php">
<div id="paso1" class="step">
<input type="text" name="campo1" value="<?= (!empty($_SESSION['datos_form']['campo1'])) ? $_SESSION['datos_form']['campo1'] : '' ; ?>">
<select class="form-select" name="sexo">
<?php
if( !empty($_SESSION['datos_form']['sexo']) ) {
$sexo = $_SESSION['datos_form']['sexo'];
echo '<option value="'.$sexo.'" selected="selected">'.$sexo.'</option>';
}
else{
echo '<option disabled selected="selected">I am...</option>';
}
?>
<option value="Mem">Men</option>
<option value="Woman">Woman</option>
<option value="I prefer not to say">I prefer not to say</option>
</select>
<?php
if( !empty($_SESSION['datos_form']['condiciones']) ) {
echo '<input type="checkbox" name="condiciones" checked>';
}
else{
echo '<input type="checkbox" name="condiciones">';
}
?>
...
onclick="mostrar_paso('numero de paso') -->
continuar
</div>
<div id="paso2" class="step">
<?php
$r =array(
1 => 'Product 1',
2 => 'Product 2',
3 => 'Product 3',
);
foreach ($r as $key => $value)
{
if( !empty($_SESSION['datos_form']['radio']) AND $_SESSION['datos_form']['radio'] == $key ) {
echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'" checked="checked" >';
echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
}
else{
echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'" >';
echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
}
}
?>
Atras
continuar
</div>
<div id="paso3" class="step">
<div id="div_producto"></div><br>
<input type="text" name="campo3" value="<?= (!empty($_SESSION['datos_form']['campo3'])) ? $_SESSION['datos_form']['campo3'] : ''; ?>">
<input type="submit" name="cancel">
Atras
<input type="submit" name="Terminar">
</div>
</form>
</body>
</html>
I would like to add a cookie to the session where the steps are saved
to avoid erasing the data stored in the session in case the browser is
closed in error, create a session cookie with a validation time of 30
days.
PHP's native session, already using cookie if visitor browser support cookie and the expiration time can be set in php.ini or at runtime by setting session.cookie_lifetime
now to remove the cookie from the data saved by the user create a
cancel button, the cancel button will delete the cookie, including the
data saved in the session.
And finally use session_destroy function to delete that cookie under procesar.php file
I'm creating a 5 star rating system with html php and jquery i dont know how to stop the stars rating when user has clicked on rating.
In my code when user click on 4 stars the alert box shows 4 stars but when the user move his mouse from stars the stars shows 0 rating.
here is my code, i'm not posting the css here
HTML :
<div class="rating">
<div class="ratings_stars" data-rating="1"></div>
<div class="ratings_stars" data-rating="2"></div>
<div class="ratings_stars" data-rating="3"></div>
<div class="ratings_stars" data-rating="4"></div>
<div class="ratings_stars" data-rating="5"></div>
</div>
JQUERY :
$('.ratings_stars').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
}
);
$('.ratings_stars').click(function() {
$('.ratings_stars').removeClass('selected'); // Removes the selected class from all of them
$(this).addClass('selected'); // Adds the selected class to just the one you clicked
var rating = $(this).data('rating');
alert(rating);
// Get the rating from the selected star
$('#rating').val(rating); // Set the value of the hidden rating form element
});
Guessing because you haven't said what you expect to happen. It could be that you want the selected rating, and the stars before it, to be highlighted.
So instead of this
$(this).addClass('selected');
you use this, similar to how you have previously.
$(this).prevAll().andSelf().addClass('selected');
But I would also remove the hover class so that it's obvious to the user on click
$(this).prevAll().andSelf().addClass('selected').removeClass('ratings_over');
Demo
<!--SAVE AS WHATEVAUWANNA.HTML AND TEST-->
<html>
<head>
<title>Rating System jQuery Plug by Aldanis Vigo</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js'></script>
<style type='text/css' language='css'>
.record{
opacity: .50;
}
#value-display{
position: relative;
top: -5px;
margin-left: 10px;
color: orange;
font-weight: bold;
}
</style>
</head>
<body>
<span value='0' id='ratingbar'>
<img class='record' number='1'/>
<img class='record' number='2'/>
<img class='record' number='3'/>
<img class='record' number='4'/>
<img class='record' number='5'/>
<span id='value-display'>0 / 5</span>
</span>
</body>
<script>
//Change these variables to your liking!!
var iconsrc = 'https://upload.wikimedia.org/wikipedia/commons/a/ae/Record2.png';
var iconwidth = '20px';
var iconheight = '20px';
var value = $('#ratingbar').attr('value');
$('#ratingbar img').each(function(){
//Set the icon for each
$(this).attr('src', iconsrc);
$(this).attr('width', iconwidth);
$(this).attr('height', iconheight);
$(this).hover( function(){
$(this).css('opacity','1');
$(this).prevAll().css('opacity','1');
});
$(this).click( function(){
//Clear all of them
$(this).parent().attr('value',$(this).attr('number'));
$(this).parent().children('#value-display').html($(this).attr('number') + ' / 5');
//Color up to the selected ones.
$('#ratingbar img').each( function(){
if($(this).attr('number') <= $(this).parent().attr('value')){
$(this).css('opacity','1');
}else{
$(this).css('opacity','.50');
}
});
});
$(this).mouseout( function(){
$(this).css('opacity','.50');
$(this).prevAll().css('opacity','.50');
//Color up to the selected ones.
$('#ratingbar img').each( function(){
if($(this).attr('number') <= $(this).parent().attr('value')){
$(this).css('opacity','1');
}
});
});
});
</script>
</html>
I have an HTML form that is split into three major components. The top portion is essentially a header for displaying a magazine name. This information does not change.
The middle portion is a table developed through a MySQL query for displaying the story information as a table of contents after it is entered in the bottom portion, which is a data entry screen.
The bottom portion, is a data entry screen for entering the information concerning each story contained in the magazine issue.
After entering the data and pressing the submit button in the bottom portion, the middle portion should be updated through the MySQL query to reflect the newly entered story. That was not happening.
Note: The code previously associated with this question has been removed for purposes of clarity. The solution was associated with how the various forms were called. My thanks to Sulthan Allaudeen for providing potential solutions. Currently, I am not familiar with utilizing jquery-ajax. Eventually I will need to learn.
As the OP wanted to know how do the jquery and ajax call
Step 1 :
Recognize the Input
Have a button with a class trigger
$(".trigger").click(function()
{
//your ajax call here
}
Step 2 :
Trigger your ajax call
$.ajax({
type: "POST",
url: "yourpage.php",
data: dataString,
cache: false,
success: function(html)
{
//your action
}
});
Step 3 :
Inside your success function show the result
$("#YourResultDiv").html(data);
For that you should create a div named as YourResultDiv
Note :
Inside your yourpage.php You should just print the table and it will be displayed as the output
Here's a brief example of displaying the results of submitting a form without leaving the current page. Form submission is done with the help of Ajax.
Each form has it's own button for submission, hence the loop over matching elements in onDocLoaded.
1. blank.php form is submitted to this script
<?php
echo "-------------------------------<br>";
echo " G E T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_GET ); echo "<br>";
echo "-------------------------------<br>";
echo " P O S T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_POST ); echo "<br>";
echo "<hr>";
if (count($_FILES) > 0)
{
var_dump($_FILES);
echo "<hr>";
}
?>
2. blank.html Contains 2 forms, shows the result of submitting either of them to the above script.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(elem, className){elem.classList.toggle(className);}
function toggleClassById(targetElemId, className){byId(targetElemId).classList.toggle(className)}
function hasClass(elem, className){return elem.classList.contains(className);}
function addClass(elem, className){return elem.classList.add(className);}
function removeClass(elem, className){return elem.classList.remove(className);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
// callback gets data via the .target.result field of the param passed to it.
function loadFileObject(fileObj, loadedCallback){var reader = new FileReader();reader.onload = loadedCallback;reader.readAsDataURL( fileObj );}
function myAjaxGet(url, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("GET", url, true);
ajax.send();
}
function myAjaxPost(url, phpPostVarName, data, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(phpPostVarName+"=" + encodeURI(data) );
}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
forEachNode( allByClass('goBtn'), function(elem){elem.addEventListener('click', onGoBtnClicked, false);} );
}
function onGoBtnClicked(evt)
{
evt.preventDefault();
var thisElem = this;
var thisForm = thisElem.parentNode;
myAjaxPostForm('blank.php', thisForm, onPostSuccess, onPostFailed);
function onPostSuccess(ajax)
{
byId('tgt').innerHTML = ajax.responseText;
}
function onPostFailed(ajax)
{
//byId('tgt').innerHTML = ajax.responseText;
alert("POST FAILED!!!!");
}
return false;
}
</script>
<style>
#page
{
display: inline-block;
border: solid 1px gray;
background-color: rgba(0,0,0,0.2);
border-radius: 6px;
}
.controls, .tabDiv
{
margin: 8px;
border: solid 1px gray;
border-radius: 6px;
}
.tabDiv
{
overflow-y: hidden;
min-width: 250px;
background-color: white;
border-radius: 6px;
}
.tabDiv > div
{
padding: 8px;
}
</style>
</head>
<body>
<div id='page'>
<div class='tabDiv' id='tabDiv1'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Name: </label><input name='nameInput'/><br>
<label>Age: </label><input type='number' name='ageInput'/><br>
<input type='file' name='fileInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<div class='tabDiv' id='tabDiv2'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Email: </label><input type='email' name='emailInput'/><br>
<label>Eye colour: </label><input name='eyeColourInput'/><br>
<label>Read and agreed to conditions and terms: </label><input type='checkbox' name='termsAcceptedInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<!-- <hr> -->
<div class='tabDiv'>
<div id='tgt'></div>
</div>
</div>
</body>
</html>
The solution to refreshing the form to display the addition of new data was to re-call it through the following line: "include("new_stories.inc.php");". This line is imediately executed just after the MySQL insert code in the data entry section of the form.
The middle section of the form "new_stories.inc.php" (the table of contents) queries the MySQL data base to retrieve the story information related to the current magazine issue. Re-calling the form is equivalent to a re-query.
There are a lot of solutions out there as to how to save the position of draggable DIVs but I haven't found any that will help with using a While loop in php.
I have a database of "needs" and I want to display all the "needs" that match the persons username and status=inprogress. This could be 1 need or 1,000,000 needs depending on if the criteria is met.
I want to save the position of the need (DIV) automatically when it's moved. Is this possible? I wanted to store the values in a database using SQL if I can.
Here the code I currently have that displays the "needs" (divs)
Header
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
#set div { width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0; }
#set { clear:both; float:left; width: 368px; height: 120px; }
p { clear:both; margin:0; padding:1em 0; }
</style>
<script>
$(function() {
$( "#set div" ).draggable({
stack: "#set div"
});
});
</script>
Body
<div id="set">
<?
$query = mysql_query("SELECT * FROM needs WHERE (needsusername='$username' OR workerusername='$username') AND status='inprogress'");
while ($rows = mysql_fetch_assoc($query)) {
$title = $rows['titleofneed'];
$status = $rows['status'];
echo "
<div class='ui-widget-content'>
$title<br>Status: $status<br>
</div>
";
}
?>
</div>
Insert Query
$x_coord=$_POST["x"];
$y_coord=$_POST["y"];
$needid=$_POST["need_id"];
//Setup our Query
$sql = "UPDATE coords SET x_pos=$x_coord, y_pos=$y_coord WHERE needid = '$needid'";
//Execute our Query
if (mysql_query($sql)) {
echo "success $x_coord $y_coord $needid";
}
else {
die("Error updating Coords :".mysql_error());
}
You can use the stop event of draggable to get noticed when an element has reached a new position. Then you just have to get the offset as described in the docs.
Assuming you have a setup like that:
<div id="set">
<div data-need="1"></div>
<div data-need="2"></div>
<div data-need="3"></div>
<div data-need="4"></div>
<div data-need="5"></div>
</div>
I've used a data attribute to store the id of the "need", you can later on use that id to store the position of the "need" in the database.
Now as mentioned before, use the stop event to send an ajax call to the server with the id of the need and the x and y postion of it. Be aware hat this is the position of the screen so if you have different screen sizes you should probably use positions relative to a parent container with a desired position.
$(function() {
$( "#set div" ).draggable({
stack: "#set div",
stop: function(event, ui) {
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
var need = ui.helper.data("need");
//Do the ajax call to the server
$.ajax({
type: "POST",
url: "your_php_script.php",
data: { x: pos_x, y: pos_y, need_id: need}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
This way every time a draggable element reaches a new positions e request will be sent to your_php_script.php. In that script you then only have to grab the post parameters and store them in the database.
There is a working fiddle, of course the ajax request is not working but you can see whats going on in the console.
I am building a jQuery dialog with tabs in a PHP script. The script uses the 'include' directive inside of a loop, iterating over the tabs and including the other scripts. Each of the included files has the data for the tab and a <script> tag with a jQuery document.ready() function in it. Without the loop, it essentially does this:
<div id="tabDialog">
<div id="tabs">
<ul>
<li><a href="#tab1'>Tab1</a></li>
<li><a href="#tab2'>Tab2</a></li>
</ul>
<div id="tabContainer">
<div id="tab1">
<?php include "tab1.php"; ?>
</div>
<div id="tab2">
<?php include "tab2.php"; ?>
</div>
</div>
</div>
</div>
and, for example, tab1.php might have something like:
<script type="text/javascript">
$(document).ready (function () {
alert ('tab1 loaded');
});
</script>
The problem is, upon creating and opening the dialog using the <div id="dialog"> as the dialog's DIV, the document's ready function is called a second time. Here is the dialog code:
$("#tabDialog").dialog ({
autoOpen: false,
minWidth: 450,
minHeight: 400,
width: 600,
height: 500
}).dialog ('open');
What is the cause of this and what would be the best way to remedy the situation? I'm trying to keep each tab's functionality in separate files because they can be used in multiple situations and I don't have to replicate the code associated to them.
Thanks for any help or advice.
I believe I've found the reason and created a reasonably good fix. When jQuery creates the dialog, it moves the DIV that contains the contents of the dialog around in the DOM (to the very end of the document) and surrounds that div with the necessary scaffolding that a dialog requires (probably by using the .append() function or something similar). Because the DIV which was being dynamically had Javascript contained within it, jQuery was calling the document.ready() function after the DIV was relocated in the DOM (i.e. a second time). Therefore, prior to building the dialog, I .remove() every script tag within the dialog's DIV like this:
$("#tabDialog").find ("script").remove ();
$("#tabDialog").dialog ({
autoOpen: true,
minWidth: 450,
minHeight: 400,
width: 600,
height: 500
});
Doing this removes the SCRIPT tag from the DIV which it was originally loaded in, but the SCRIPT itself still exists. I'm still researching this because I don't completely understand where the Javascript code that was dynamically loaded actually "lives," but I suspect it's located somewhere outside of the DOM. I verified this in Chrome, Firefox, and Exploder 8.
I verified that any scripts that were originally contained within the loaded DIVs still function as expected by putting a button in the DIV and assigning a .click() function. Here is a small test that demonstrates this:
<html>
<head>
<link href="css/redmond/jquery-ui-1.8.1.custom.css" type="text/css" rel="stylesheet" media="screen" />
<link href="css/style.css" type="text/css" rel="stylesheet" media="screen" />
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
</head>
<body>
<div id="dialogContents" style="display: none;">
<div style="border: 1px solid black; height: 98%;">
<form id="testForm">
<input type="text">
</form>
<button id="testButton">Test</button>
<script type="text/javascript">
$(document).ready (function () {
alert ("ready");
$("#testButton").click (function () {
alert ('click');
});
});
</script>
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready (function () {
//
// Remove all the scripts from any place in the dialog contents. If we
// do not remove the SCRIPT tags, the .ready functions are called a
// second time. Removing this next line of Javascript demonstrates this.
//
$("#dialogContents").find ("script").remove ();
$("#dialogContents").dialog ({
width: 300,
height: 300,
title: 'Testing...'
});
});
</script>
</html>
I appreciate the help people provided in this thread!
I haven't used .dialog() too much, but do you need to use jQuery's ready() method in your script?
Looks like .dialog() has callback options you could take advantage of.
Script in tab:
<script type="text/javascript">
function onOpen() { alert('tab1 loaded') };
</script>
dialog:
$(this).dialog ({
autoOpen: false,
minWidth: 450,
minHeight: 400,
width: 600,
height: 500,
open: function(event, ui) { onOpen(); } // call function in script
}).dialog ('open');
So I have to say that I am not 100% sure why it is happening even though I understand that the dialog does maintin it's own state so this might be one of the reasons. But I could be way off. But the way to get around it is to use something like this instead:
$(document).one('ready', function () {
alert ('tab1 loaded');
});
This will make sure that it only runs once when the page loads.
I also had this problem, but the cause in my case was something different. I had a self-closing div element inside of the div that was used as the dialog holder. When I replaced the self-closing element with a closing tag, the document ready function stopped firing twice and only fired once, as expected.
For example, this caused the document ready function to fire twice:
$("#foo").dialog({
// ...
});
...
<div id="foo" title="My Dialog">
<div id="bar" />
</div>
Whereas this only fired the document ready function once:
$("#foo").dialog({
// ...
});
...
<div id="foo" title="My Dialog">
<div id="bar"></div>
</div>
You probably don't need the .dialog('open') call; use the option autoOpen : true instead.
Here's the resulting text of the page. I did a view-source and then removed any extraneous stuff from the page to try and make it simpler.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link href="css/redmond/jquery-ui-1.8.1.custom.css" type="text/css" rel="stylesheet" media="screen" />
<link href="css/style.css" type="text/css" rel="stylesheet" media="screen" />
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
</head>
<body>
<div id="tabDialog" style="position: relative; display: none;" title="Test Dialog">
<div id="tabs" style="position: absolute; top: 5px; bottom: 40px; left: 3px; right: 3px;">
<ul>
<li><a href='#tab1'>Tab #1</a></li><li><a href='#tab2'>Tab #2</a></li>
</ul>
<div class="tab_container" style="position: absolute; top: 35px; bottom: 0px; left: 1px; right: 1px; overflow: auto;">
<div id='tab1' class='tabPage ui-dialog-content'>
<form id="tab1Form">
More testing... <input class="keypressMonitor" type="text">
</form>
Testing...<br/>
Testing...<br/>
<script type="text/javascript">
$(document).ready (function () {
alert ('tab1 loaded');
$("#tab1Form").bind ('save', function () {
alert ("in tab1Form.save ()");
});
});
</script>
</div>
<div id='tab2' class='tabPage ui-dialog-content'>
<form id="tab2Form">
<div style="position: absolute; left: 1px; right: 1px; top: 1px; bottom: 1px;">
Testing: <input class="keypressMonitor" type="text">
<textarea id="testArea" class="keypressMonitor tinymce" style="position: absolute; top: 30px; bottom: 2px; left: 2px; right: 2px;"></textarea>
</div>
</form>
<script type="text/javascript">
$(document).ready (function () {
$("#tab2Form").bind ('save', function () {
alert ("in tab2Form.save ()");
});
});
</script>
</div>
</div>
</div>
<div id="dialogButtons" style="position: absolute; bottom: 3px; left: 3px; right: 15px; text-align: right; height: 32px;">
<button class="applyButton" disabled>Apply</button>
<button class="okButton" disabled>Ok</button>
<button class="cancelButton">Cancel</button>
</div>
</div>
<script type="text/javascript">
$(document).ready (function () {
$("#tabs").tabs ();
$("button").button ();
/**
* Pressing the cancel button simply closes the dialog.
*/
$(".cancelButton").click (function () {
$("#tabDialog").dialog ("close");
});
$("#tabDialog").dialog ({
open: function () {
},
autoOpen: true,
minWidth: 450,
minHeight: 400,
width: 600,
height: 500,
height: 'auto'
});
});
</script>
</body>
</html>
Puts your script into create method:
$.dialog({
<your parameters>
create: function() {
<your script>
}
}
With this method your script is called once only you create the dialog, not twice!