how to remember the radio selection? - php

after I post it use ajax,the value of radio disappear,but I want the radio part to remember the selection. I need the page to remember the radio button selections when I leaves and returns. Would this require database? If so, how do i implement it? I try to add the select =selected ,but it do not help.
<input value="<?php echo $key; $key++;?>" type="radio" class="radioOrCheck" name="answer<?php echo $num_select;?>"
id="0_answer_<?php echo $num_select;?>_option_<?php echo $key;?>"
below it is the full code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
<link href="css/iconfont.css" rel="stylesheet" type="text/css" />
<link href="css/test.css" rel="stylesheet" type="text/css" />
<style>
.hasBeenAnswer {
background: #5d9cec;
color:#fff;
}
</style>
</head>
<body>
<p>
</p>
<div class="main">
<!--nr start-->
<div class="test_main">
<div class="nr_left">
<div class="test">
<form action="" method="post">
<div class="test_title">
<!--
<p class="test_time">
<i class="icon iconfont"></i><b class="alt-1">01:40</b>
</p>-->
<font><?php echo "<input type='button' name='test_jiaojuan' value='sub' onClick='getinput($ans_json,$id_json)'>";?>
</font>
</div>
<div class="test_content">
<div class="test_content_title">
<h2>word</h2>
<p>
<span>has</span><i class="content_lit"><?php echo $cnt_sel;?></i><span>title</span><span>sum</span><i class="content_fs"><?php echo $cnt_sel*10;?></i><span>min</span>
</p>
</div>
</div>
<div class="test_content_nr">
<ul>
<!--begin select-->
<?php
foreach($results as $temp){
$sql_2="SELECT `description`,`input`,`select_id` FROM `select` WHERE `select_id`=?";
$res_2=pdo_query($sql_2,$temp[0]);
$row = $res_2[0];
?>
<li id="qu_0_<?php echo $num_select;?>">
<div class="test_content_nr_tt">
<i><?php echo $num_select;?></i><font>
<p>
<?php
echo $row[0];
?>
</p>
</font>
</div>
<div class="test_content_nr_main">
<ul>
<?php
if ($row[1]) {
$arr = rtrim($row[1],"<br />");
$arr = explode('<br />', $arr);
foreach($arr as $key => $a){
?>
<li class="option">
<input value="<?php echo $key; $key++;?>" type="radio" class="radioOrCheck" name="answer<?php echo $num_select;?>"
id="0_answer_<?php echo $num_select;?>_option_<?php echo $key;?>"
/>
<label for="0_answer_<?php echo $num_select;?>_option_<?php echo $key;?>">
<p class="ue" style="display: inline;"><?php echo strip_tags($a,"<img>");//echo trim($a); ?></p>
</label>
</li>
<?php
}
}
if ($row['hint']) {
?><h4><?php echo $MSG_HINT;?></h4><?php
echo $row['hint'];
}
?>
</ul>
</br></br>
</div>
</li>
<?php
$num_select=$num_select+1;
}
?>
<p>
<?php
?>
</p>
<!--end select-->
</ul>
</div>
</form>
</div>
</div>
<div class="nr_right">
<div class="nr_rt_main">
<div class="rt_nr1">
<div class="rt_nr1_title">
<h1>
<i class="icon iconfont"></i>answer
</h1>
<!-- <p class="test_time">
<i class="icon iconfont"></i><b class="alt-1">01:40</b>
</p>-->
</div>
<div class="rt_content">
<div class="rt_content_tt">
<h2>chose</h2>
<p>
<span>sum</span><i class="content_lit"><?php echo $cnt_sel;?></i><span>answer</span>
</p>
</div>
<div class="rt_content_nr answerSheet">
<ul>
<?php
$temp=1;
for($temp=1;$temp<=$cnt_sel;$temp++){
?>
<li><?php echo $temp;?></li>
<?php
}
?>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!--nr end-->
<div class="foot"></div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery.easy-pie-chart.js"></script>
<script src="js/jquery.countdown.js"></script>
<script>
$(function() {
$('li.option label').click(function() {
debugger;
var examId = $(this).closest('.test_content_nr_main').closest('li').attr('id');
var cardLi = $('a[href=#' + examId + ']');
if(!cardLi.hasClass('hasBeenAnswer')){
cardLi.addClass('hasBeenAnswer');
}
});
});
$(function() {
$('li.option').click(function() {
debugger;
var examId = $(this).closest('.test_content_nr_main').closest('li').attr('id');
var cardLi = $('a[href=#' + examId + ']');
if(!cardLi.hasClass('hasBeenAnswer')){
cardLi.addClass('hasBeenAnswer');
}
});
});
/*window.onbeforeunload = function(event){
var msg = '';
msg +='do not like?\n';
//msg += '';
return msg;
};*/
function getinput(ans_json,results_json) {
var sum=<?php echo $cnt_sel;?>;
var blank_cnt=0;
var well_cnt=0;
for (var i = 1; i <= sum; i++) {
var radio_name = new String("answer" + i.toString());
var ans_s = $('input:radio[name=' + radio_name + ']:checked').val();
if(!(ans_s)){
blank_cnt++;
}}
//var json = getjson();
var msg = "ok";
if (confirm(msg) == true) {
var radio = new Array();
for (var i = 1; i <= <?php echo $cnt_sel;?>; i++) {
var radio_name = new String("answer" + i.toString());
var ans_s = $('input:radio[name=' + radio_name + ']:checked').val();
if(!(ans_s)){
ans_s=-1;
}
var judge=0;
var answer_true= parseInt(ans_json[i-1]);
var id_true=parseInt(results_json[i-1]);
if(ans_s == answer_true){
judge=1;
}
$.ajax({
type: "GET",
url: "select_ajax.php",
data: {
select_id: id_true,
contest_id:<?php echo $cid;?>,
result:judge
},
success: function(msg){
well_cnt++;
}
});
}
if(well_cnt==5){
alert('success');
}
setTimeout(function (){
window.location.href = "contest.php?cid="+<?php echo $cid;?>;
}, 1000);
} else {
return false;
}
}
</script>
</body>
</html>

You can do it by storing your radio button value in javascript localStorage and then set that localStorage value to your radio button again.

Related

Can not deserialize instance of String out of START_OBJECT token

I've gone through the other answers to this question, but no one seems to be able to apply it universally. Other questions just go unanswered.
Obviously, I'm getting "Can not deserialize instance of String out of START_OBJECT token." in my console. I believe it happens when I attempt to stringify(response) from my websocketdata.
Here is the code.
<?php /**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
*/ ?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<script type="text/javascript"
src='http://martialparks.com/wp-content/themes/js/gamesparks-rt.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/gamesparks.js'></script>
<script type='text/javascript'
src='http://martialparks.com/wp-content/themes/js/gamesparks-functions.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/hmac-sha256.js'></script>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php
wp_head();
?>
</head>
<body <?php body_class() ?>>
<body onload="init()">
<!--Start Header Wrapper-->
<div class="header_wrapper">
<div class="header">
<!--Start Container-->
<div class="container_24">
<div class="grid_24">
<div class="logo"> <a href="<?php echo esc_url(home_url()); ?>"><img src="<?php if (business_directory_get_option('business_directory_logo') != '') { ?><?php echo esc_url(business_directory_get_option('business_directory_logo')); ?><?php
} else {
echo esc_url(get_template_directory_uri() . '/images/logo.png');
}
?>" alt="<?php bloginfo('name'); ?>" /></a></div>
</div>
<div class="clear"></div>
</div>
<!--End Container-->
<div class="clear"></div>
</div>
<div class="clear"></div>
<!--Start Menu Wrapper-->
<div class="menu_wrapper">
<div class="top_arc"></div>
<div class="menu-container">
<div class="container_24">
<div class="grid_24">
<?php business_directory_nav(); ?>
</div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="bottom_arc"></div>
</div>
<!--End Container-->
<div class="clear"></div>
</div>
<!--End Header Wrapper-->
<div class="clear"></div>
<div class="wrapper">
<!--Start Container-->
<div class="container_24">
<div class="grid_24">
<br/>
<br/>
<br/>
<input id="apiKey" type="hidden" value="A319082inSk2"/>
<input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
<label for="apiCredential">Api Credential</label><input id="apiCredential"/>
<label for="username">User Name</label><input id="username"/>
<label for="password">Password</label><input id="password"/>
<button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
<button onClick='gamesparks.authenticationRequest(username, password, loginResponse)'>Login</button>
<button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
<button onClick='customEvent()'>Custom Event</button>
<button onClick='testRT()'>Test RT</button>
<i>Special thanks to the awesome team at GameSparks!</i>
<div id="messages"></div>
<br/>
<br/>
User Name
<div id="displayName" style="color: blue;"></div>
Coins
<div id="Coins" style="color: red;"></div>
Exp
<div id="Exp" style="color: green;"></div>
Leader Points
<div id="LeadP" style="color: darkgreen;"></div>
Hero Points
<div id="HeroP" style="color: purple;"></div>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
<h3>Find a Park</h3>
<div id="map"></div>
<script>
function initMap() {
var Velocity = {lat: 38.308101, lng: -85.815464};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: Velocity
});
var marker = new google.maps.Marker({
position: Velocity,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDSHCinT3IVWFCLUudbsMZV6644GNrGiwc&callback=initMap">
</script>
<script type="text/javascript">
//Create a gamesparks object to be used
var gamesparks = new GameSparks();
//Initialse the SDK
function init() {
gamesparks.initPreview({
key: document.getElementById('apiKey').value,
secret: document.getElementById('apiSecret').value,
credential: document.getElementById('apiCredential').value,
onNonce: onNonce,
onInit: onInit,
onMessage: onMessage,
logger: console.log,
});
}
function accountDetailsResponseCreator() {
var response = {
displayName: 'A User',
currencies: {Coins: 'A coin', Exp: 'A exp', LeadP: 'A lead p', HeroP: 'A hero p'}
}
accountDetailsResponse(response)
}
//Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
function onNonce(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
}
//Callback to handle when the SDK is initialised and ready to go
function onInit() {
console.log("Initialised");
}
//Callback to handle async messages from the gamesparks platform
function onMessage(message) {
console.log("onMessage");
}
//Response handler examples
function registerResponse(response) {
console.log(JSON.stringify(response));
}
function loginResponse(response) {
console.log(JSON.stringify(response));
}
function accountDetailsResponse(response) {
console.log (JSON.stringify(response));//logs the string to console
document.getElementById("displayName").innerHTML = (response.displayName);
document.getElementById("Coins").innerHTML = (response.currencies.Coins);
document.getElementById("Exp").innerHTML = (response.currencies.Exp);
document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string. I've tried doing each line with semicolons at the end, and all in a group with commas separating them. Both just give me the first variable and delete the rest.
}
function customEvent() {
gamesparks.sendWithData(
"LogEventRequest",
{
eventKey: "FIRST_EVENT",
NUMBER_ATTR: 123,
STRING_ATTR: "this is a string",
JSON_ATTR: {key1: 12, key2: "abc"}
},
function (response) {
console.log(JSON.stringify(response));
}
);
}
var apiKey = "2974660weiMa";
var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
var myTimer = null;
var myRTSession = function () {
};
var numCycles = 0;
myRTSession.started = false;
myRTSession.onPlayerConnectCB = null;
myRTSession.onPlayerDisconnectCB = null;
myRTSession.onReadyCB = null;
myRTSession.onPacketCB = null;
myRTSession.session = null;
myRTSession.start = function (connectToken, host, port) {
var index = host.indexOf(":");
var theHost;
if (index > 0) {
theHost = host.slice(0, index);
} else {
theHost = host;
}
console.log(theHost + " : " + port);
myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
if (myRTSession.session != null) {
myRTSession.started = true;
myRTSession.session.start();
} else {
myRTSession.started = false;
}
};
myRTSession.stop = function () {
myRTSession.started = false;
if (myRTSession.session != null) {
myRTSession.session.stop();
}
};
myRTSession.log = function (message) {
var peers = "|";
for (var k in myRTSession.session.activePeers) {
peers = peers + myRTSession.session.activePeers[k] + "|";
}
console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
};
myRTSession.onPlayerConnect = function (peerId) {
myRTSession.log(" OnPlayerConnect:" + peerId);
if (myRTSession.onPlayerConnectCB != null) {
myRTSession.onPlayerConnectCB(peerId);
}
};
myRTSession.onPlayerDisconnect = function (peerId) {
myRTSession.log(" OnPlayerDisconnect:" + peerId);
if (myRTSession.onPlayerDisconnectCB != null) {
myRTSession.onPlayerDisconnectCB(peerId);
}
};
myRTSession.onReady = function (ready) {
myRTSession.log(" OnReady:" + ready.toString());
if (myRTSession.onReadyCB != null) {
myRTSession.onReadyCB(ready);
}
};
myRTSession.onPacket = function (packet) {
myRTSession.log(" OnPacket:" + packet.toString());
if (myRTSession.onPacketCB != null) {
myRTSession.onPacketCB(packet);
}
};
function testRT() {
myRTSession.stop();
gamesparks.initPreview({
key: apiKey,
secret: apiSecret,
credential: "",
onNonce: onNonceRT,
onInit: onInitRT,
onMessage: onMessageRT,
logger: console.log,
});
}
function onNonceRT(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
}
function onInitRT() {
console.log("Initialised");
gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
sendMatchmakingRequest();
}
});
}
//Callback to handle async messages from the gamesparks platform
function onMessageRT(message) {
//console.log("message " + JSON.stringify(message));
if (message["#class"] === ".MatchFoundMessage") {
var accessToken = message["accessToken"];
var host = message["host"];
var port = message["port"];
myRTSession.stop();
if (myTimer) {
clearTimeout(myTimer);
}
myTimer = setInterval(mainRTLoop, 10);
myRTSession.start(accessToken, host, port);
} else if (message["#class"] === ".MatchNotFoundMessage") {
console.log("MATCH NOT FOUND");
sendMatchmakingRequest();
}
}
function sendMatchmakingRequest() {
gamesparks.sendWithData("MatchmakingRequest",
{
skill: 1,
matchShortCode: "Match_STD"
},
function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
console.log("Match OK...");
}
}
);
}
function mainRTLoop() {
if (myRTSession.started) {
myRTSession.session.update();
var data = RTData.get();
data.setLong(1, numCycles);
myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);
numCycles++;
}
}
</script>
</body>
</html>
For the life of me, I have no idea what is happening or how to fix it. The problem pops up when I activate a button that references line 173
function loginResponse(response) {
console.log(JSON.stringify(response));
}
But don't let that affect your impartiality. I compared this code to earlier versions of the code I have and could not identify a change in any of my functions.
Well, bottom line is this: When you are an idiot, don't post questions to stackoverflow. No one will respond. Not because they are mean, but because learning the basics is important.
So the problem originated for me in the top of my code with this:
<button onClick='gamesparks.authenticationRequest(username, password, loginResponse)'>Login</button>
Weird, right? Not really. What had done was try to alter the input for the authentication request to match my html element inputs (see where my elements are labeled as username and password?) It didn't work, and I obviously just shelved that and moved on...and forgot. What I did was change "username" to "testuser". This matched the value I was trying to authenticate. Now, my baby is returning values on my testuser, and running like a dream.
Thanks for the tough love, stackoverflow.

How to make an id from a PHP while echo loop make work with JQuery AJAX

I want to make an id reference "logout" work when clicked from my php code. Please this would aid me very well in continuing the project. this method is important because it involves phonegap
php file
The php file gets user details from the database. the logout id is used to call the php page through an AJAX request and then log the user out and redirect them.
<?php
session_start();
$con = mysqli_connect("localhost", "*****", "*****", "*****");
//check connection...
if ($con === false) {
die ("couldn't connect to SQL Server");
}
if (isset($_SESSION['people_email'])){
$selectdata = "SELECT * FROM people WHERE people_email = '".$_SESSION['people_email']."'" ;
$query = mysqli_query($con, $selectdata);
while ($row = mysqli_fetch_array($query)) {
echo '<div class="ui fluid card">';
echo '<div class="extra content">';
echo '<div class="left floated meta">';
echo '<a href="#" id="logout">';
echo '<i class="remove circle icon"></i>';
echo "Log out";
echo '</a>';
echo '</div>';
echo '<div class="right floated meta">';
echo '<a>';
echo '<i class="plus icon"></i>';
echo "Upload a photo";
echo '</a>';
echo '</div>';
echo '</div>';
echo '<div class="image">';
echo '<img src="/images/avatar2/large/kristy.png">';
echo '</div>';
echo '<div class="content">';
echo '<a class="header">'.$row['people_name'].'</a>';
echo '<div class="meta">';
echo '<span class="date">'.$row['people_name'].'</span>';
echo '</div>';
echo '<div class="description">'.$row['people_email'].'</div>';
echo '</div>';
echo '<div class="extra content">';
echo '<a><i class="send icon"></i>'.$row['people_username'].'</a>';
echo '<a><i class="alarm icon"></i>'.$row['people_username'].'</a>';
echo '</div>';
echo '</div>' ;
}
}
else {
echo "no";
}
?>
this is the HTML file.
the html file graps the user data for php echo and displays them.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<!-- Path to your custom app styles-->
<link rel="stylesheet" href="css/my-app.css">
<link rel="stylesheet" href="Semantic/semantic.min.css">
<!--<link rel="stylesheet" type="text/css" href="css/index.css" />-->
<title>MyApp</title>
</head>
<body>
<!-- Views -->
<div class="views">
<!-- Your main view, should have "view-main" class -->
<div class="view view-main">
<!-- Pages container, because we use fixed navbar and toolbar, it has additional appropriate classes-->
<div class="pages navbar-fixed toolbar-fixed">
<!-- Page, "data-page" contains page name -->
<div class="page " data-page="profile">
<!-- Top Navbar. In Material theme it should be inside of the page-->
<div class="navbar bar-color">
<div class="navbar-inner">
<div class="left"><i class="bell icon"></i>
</div>
<div class="center"><form><input size="50px" type="search" placeholder="Search"/></form></div>
<div class="right">
<!-- Right link contains only icon - additional "icon-only" class-->
<i class="building outline icon"></i>
</div>
</div>
</div>
<!-- Toolbar. In Material theme it should be inside of the page-->
<div class="toolbar toolbar-bottom bar-color">
<div class="toolbar-inner">
<!-- Toolbar links -->
<i class="eye icon"></i>
<i class="calendar icon"></i>
<i class="plus icon"></i>
<i class="user icon"></i>
</div>
</div>
<!-- Scrollable page content -->
<div class="page-content" >
<div id="profile" style="height:90%; width:90%;margin:auto;position:relative;top:20px;"></div>
</div>
</div>
</div>
</div>
</div>
<script src="js/jquery-2.2.3.min.js"></script>
<script src="Semantic/semantic.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: 'get',
url: 'profile.php',
dataType: 'html',
success: function (response) {
$('#profile').html(response);
}
});
$("#logout").click(function() {
$.ajax({
type: 'get',
url: 'logout.php',
success: function (response) {
if (response == "success") {
window.location.href="login.html";
}else{
alert("You were not logged out");
}
}
});
});
});
</script>
</body>
</html>
You can include data attributes like data-page-id in the log out button html and use jQuery's attr() function to fetch that data.
<div id='logout' data-info='some_info'></div>
$('#logout').attr('data-info'); //returns the value
But I don't see why you need this extra info since it's just a log out button and you can bind it's id to click event.

Trying to show jqmobile grid(trirand) in a jquery mobile windows

Using JQuery Mobile I want to pop a dialog box where the user can enter in search filters and then when they submit the query show the jqmobile grid(trirand) inside a modal window. Is this possible. Here is my code below:
qr.php
<?php require_once '../auth.php'; require_once '../jqSuitePHP/jq-config.php'; // include the PDO driver class require_once '../../jqSuitePHP/php/jqGridPdo.php'; // Connection to the server $conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD); // Tell the db that we use utf-8 $conn->query("SET NAMES utf8"); if(isset($_REQUEST['a'])) { //get asset information $conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD); $sql = "SELECT asset_no, dept_id as dept, short_desc, `LOTO #` as loto FROM mfg_eng_common.machine WHERE asset_no ='".$_REQUEST['a']."'"; $result = $conn->query($sql); $row = $result->fetch(PDO::FETCH_ASSOC); //check to see if active work order exists in MWO system for current asset //status_id of 50 mean Approved/Closed $sql = "SELECT count(*) woCnt FROM mfg_eng_mwo.mwo WHERE asset_id ='".$_REQUEST['a']."' AND status_id != 50"; $result = $conn->query($sql); $woCnt = $result->fetch(PDO::FETCH_ASSOC); } else { header("Location: http://rworley-laptop.dayton-phoenix.com/dpg/mwo/forms/MWO.php"); } ?> <!DOCTYPE HTML> <html lang="en-US"> <head> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" /> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> <script type="text/javascript"> function getWOCnt() { var cntval = <?php echo $woCnt['woCnt'];?>; if(cntval > 0) { if (confirm(" There are already active work order(s) for asset <?php echo $_REQUEST['a']?>. \n To see active work orders:\n Click Cancel and then click 'Update Work Orders'. \n\n To enter a new work order for asset <?php echo $_REQUEST['a']?> \n Click OK .")) { window.open("../forms/MWO.php?a=<?php echo $_REQUEST['a']?>", "new"); /* $(function () { $("#newMWO").on('click', (function (event) { event.preventDefault(); var loadVars=(encodeURI("../forms/MWO.php?a=<?php echo $_REQUEST['a']?>")); var dialogName= $("#mwoForm").load(loadVars); $(dialogName).dialog({ autoOpen: false, resizable: true, modal: true, bigframe: true, height: 600, width: 1000, overflow: scroll, resizable: true, title: "MWO New Work Order" }); dialogName.dialog('open'); return false; })); }); */ } } else { window.open("../forms/MWO.php?a=<?php echo $_REQUEST['a']?>", "new"); /* $(function () { $("#newMWO").on('click', (function (event) { event.preventDefault(); var loadVars=(encodeURI("../forms/MWO.php?a=<?php echo $_REQUEST['a']?>")); var dialogName= $("#mwoForm").load(loadVars); $(dialogName).dialog({ autoOpen: false, resizable: true, modal: true, bigframe: true, height: 600, width: 1000, overflow: scroll, resizable: true, title: "MWO New Work Order" }); dialogName.dialog('open'); return false; })); }); */ } }; </script> </head> <body> <div data-role="page" data-theme="b" align="center"> <div data-theme="a" data-role="header"> <h1>Maintenance Work Orders</h1> <img alt="<?php echo $_REQUEST['a']?>" src="../../Machine Pictures/<?php echo $row['dept']?>/<?php echo $row['asset_no']?>.jpg" height="240" width="300"/> <b><br><?php echo $row['short_desc']?></b> </div><!-- /header --> <br> <div data-theme="c" data-content-theme="d" > <hr> <?php echo "PM Procedure" ?> <b>|</b> <?php echo "Loto Procedure" ?> </div> <div data-role="collapsible-set" data-theme="b" data-content-theme="d" > <ul data-role="listview" data-inset="true" align="center" data-filter="false" data-theme="b"> <li> <a id="newMWO" name="newMWO" data-role="button" data-inline="true" target="_blank" onclick=getWOCnt() > New Work Order </a> </li> </ul> <ul data-role="listview" data-inset="true" align="center" data-filter="false" data-theme="b"> <li> Update Work Order </li> </ul> <ul data-role="listview" data-inset="true" align="center" data-filter="false" data-theme="b"> <li> <a href="../../mwo/MWO_mobile.php?a=<?php echo $_REQUEST['a']?>" data-role="button" data-inline="true" data-rel="dialog" target="mwoSearch" data-transition="slidedown" > Search Work Orders </a> </li> </ul> </div> <?php if(!($_POST)) { echo " <a href='#popupBasic' data-rel='popup' data-role='button' data-inline='true'>Quick Search</a> <div data-role='popup' id='popupBasic' data-transition='flip' > <a href='#' data-rel='back' data-role='button' data-theme='a' data-icon='delete' data-iconpos='notext' class='ui-btn-right'>Close</a> <form action='#' method='POST'> <div data-theme='a' data-role='header'> <h2>Look Up MWO</h2> </div> <p> Problem<textarea name='search_prob' data-theme = 'a' data-content-theme = 'd' rows = '3' cols = '50' id = 'search_prob' /></textarea> </p> <p> Solution<textarea name='search_sol' data-theme = 'a' data-content-theme = 'd' rows = '3' cols = '50' id = 'search_sol' /></textarea> </p> <p id = 'submit-area'> <input type='submit' data-theme='b' value='Search' id = 'sub1'/> </p> </form> </div> "; } else { echo " <ul data-role='listview' data-inset='true' align='center' data-filter='false' data-theme='b'> <li> <a href=\"QS.php?a=".$_REQUEST['a']."\" data-role='button' data-inline='true' data-rel='dialog' data-transition='slidedown'> Qucick Search Results </a> </li> </ul>"; } ?> <div data-role="footer" data-theme="a"> <h4>Dayton-Phoenix Group, Inc.</h4> </div><!-- footer --> </div><!-- page --> </body> </html>
QS.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MWO Quick Search</title>
<link rel="stylesheet" href="../../jquerymobile.jqGrid/css/themes/default/jquery.mobile.css" />
<link rel="stylesheet" href="../../jquerymobile.jqGrid/css/themes/ui.jqgridmobile.css" />
<link rel="stylesheet" href="../../jquerymobile.jqGrid/css/themes/shCoreEclipse.css" />
<link rel="stylesheet" href="../../jquerymobile.jqGrid/css/themes/shThemeEclipse.css" />
<script src="../../jquerymobile.jqGrid/js/jquery.js" type="text/javascript"></script>
<script src="../../jquerymobile.jqGrid/js/jquerymobile.jqGrid.min.js" type="text/javascript"></script>
<script src="../../jquerymobile.jqGrid/js/jquery.mobile.js" type="text/javascript"></script>
<script src="../../jquerymobile.jqGrid/js/grid.locale-en.js" type="text/javascript"></script>
</head>
<body>
Paging, sorting and searching
</body>
</html>
quickSearch2.php
<!DOCTYPE html>
<html>
<body>
<div id="page" data-role="page" data-theme="b">
<div data-role="header" data-theme="b" style="margin-bottom: 10px">
<h1> MWO Quick Search Results</h1>
Home
</div>
<!-- HTML table Definition -->
<table id='grid'></table>
<div id='pager'></div>
<!-- Java Scruipt Code -->
<script type='text/javascript'>
var a = <?php echo json_encode($_REQUEST['a']); ?>;
var prob = <?php echo json_encode($_REQUEST['search_prob']); ?>;
jQuery('#grid').jqGrid({
"hoverrows":false,
"viewrecords":true,
//"jsonReader":{"repeatitems":false,"subgrid":{"repeatitems":false}},
"gridview":true,
"url":"../../mwo/mobile/quicksearch.php?a=" + a + "&search_prob=" + prob,
"loadonce": true,
"rowNum":10,
"height":200,
"autowidth":true,
"sortname":"mwo_id",
"rowList":[10,30,40],
"datatype":"json",
"colModel":[
{"name":"e", "index":"empty", "sorttype":"int", "hidden":true,"width":50,"editable":true},
{"name":"MWO #", "index":"mwo_id", "sorttype":"int", "key":true,"width":80,"editable":true},
{"name":"DPG #", "index":"asset_id", "sorttype":"string", "width":80, "editable":true},
{"name":"Assigned to", "index":"assigned_id", "sorttype":"string", "width":80, "editable":true},
{"name":"Entered", "index":"entered_time", "sorttype":"datetime", "width":80, "editable":true,"datefmt":"m/d/Y", "searchoptions":{sopt:['eq']}, "formatter":"date","formatoptions":{"srcformat":"Y-m-d H:i:s","newformat":"m/d/Y"}},
{"name":"Problem", "index":"long_desc", "sorttype":"string", "width":80, "editable":true},
{"name":"Solution", "index":"solution", "sorttype":"string", "width":80, "editable":true}
],
"pager":"#pager"
});
</script>
</div>
</body>
</html>
json data being used:
{"page":1,"total":2,"records":13,"rows":[{"mwo_id":"1302271211","cell":["","1302271211","38315","-1","2013-07-08 11:13:19","approved test",""]},{"mwo_id":"1302271213","cell":["","1302271213","38315","-1","2013-07-11 09:26:26","yo momma is so fattest","how fat is she? she's so fat she left the house in heels and came back in flip-flops"]},{"mwo_id":"1302271214","cell":["","1302271214","38315","-1","2013-07-12 12:13:55","july test",""]},{"mwo_id":"1302271215","cell":["","1302271215","38315","-1","2013-07-08 08:59:56","test","update2"]},{"mwo_id":"1302271216","cell":["","1302271216","38315","-1","2013-07-09 06:14:02","test",""]},{"mwo_id":"1302271217","cell":["","1302271217","38315","-1","2013-07-08 09:01:30","yep testing","no answer yet"]},{"mwo_id":"1302271218","cell":["","1302271218","38315","-1","2013-07-09 09:59:46","new test of email system",""]},{"mwo_id":"1302271219","cell":["","1302271219","38315","","2013-07-08 12:33:09","email new test",""]},{"mwo_id":"1302271221","cell":["","1302271221","38315","12","2013-07-11 13:20:55","ANOTHER TEST OF NEW ...WITH EMAIL","AND THE ANSWER IS ....."]},{"mwo_id":"1302271222","cell":["","1302271222","38315","","2013-07-11 09:29:58","test...add issue",""]},{"mwo_id":"1302271223","cell":["","1302271223","38315","","2013-07-11 13:11:15","testing",""]},{"mwo_id":"1302271224","cell":["","1302271224","38315","7","2013-07-11 13:27:32","test with auto assign","no solution its all good"]},{"mwo_id":"1302271226","cell":["","1302271226","38315","7","2013-07-12 12:05:02","Meeting test",""]}]}

Name being inserted, but file is not being uploaded [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I've an upload input field in a form. the problem that the name of the file is being inserted in the database but the file is not being uploaded to the server, and the same code is working on the same server in a different file in the same directory but in a different query. form is set to enctype="multipart/form-data",
here is the code where its not working
<!DOCTYPE html>
<html lang="en">
<head>
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/dbc.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php confirm_logged_in(); ?>
<?php find_selected_post(); ?>
<?php
$target = "../upload/";
$target = $target . basename( $_FILES['post_photo']['name']);
if (intval($_GET['cat']) == 0) {
redirect_to('cat_posts.php');
}
include_once("includes/form_functions.php");
if (isset($_POST['submit'])) {
$errors = array();
$required_fields = array('post_title', 'position', 'visible', 'post_content');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$fields_with_lengths = array('post_title' => 30);
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
$category_id = mysql_prep($_GET['cat']);
$post_title = trim(mysql_prep($_POST['post_title']));
$post_content = mysql_prep($_POST['post_content']);
$post_description = mysql_prep($_POST['post_description']);
$post_keywords = mysql_prep($_POST['post_keywords']);
$post_tags = mysql_prep($_POST['post_tags']);
$post_photo =($_FILES['post_photo']['name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
if (empty($errors)) {
$query = "INSERT INTO ss_posts (
post_title, post_content, post_description, post_keywords, post_tags, post_photo, position, visible, category_id
) VALUES (
'{$post_title}', '{$post_content}', '{$post_description}', '{$post_keywords}', '{$post_tags}', '{$post_photo}', {$position}, {$visible}, {$category_id}
)";
if ($result = mysql_query($query, $connection)) {
$message = "Successfully Created.";
$new_post_id = mysql_insert_id();
redirect_to("cat_posts.php?post={$new_post_id}");
} else {
$message = "The Post Could Not Be Created.";
$message .= "<br />" . mysql_error();
}
} else {
if (count($errors) == 1) {
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the form.";
}
}
}
?>
<?php
error_reporting(E_ALL);
echo "<pre>";
print_r($_FILES);
echo "</pre>";
echo "<br/>target: " . $target;
if (!move_uploaded_file($_FILES['post_photo']['tmp_name'], $target)) {
echo "<br/>Upload failed.";
} else {
echo "<br/>Upload done.";
}
?>
<meta charset="utf-8"/>
<title>New Post - Administration Panel</title>
<script src="js/ckeditor/ckeditor.js" type="text/javascript"></script>
<link rel="stylesheet" href="js/ckeditor/sample.css">
<link rel="stylesheet" href="css/layout.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/form.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/button.css" type="text/css" media="screen" /> <!--[if lt IE 9]>
<link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" />
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="js/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="js/hideshow.js" type="text/javascript"></script>
<script src="js/jquery.tablesorter.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.equalHeight.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".tablesorter").tablesorter();
}
);
$(document).ready(function() {
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
</script>
<script type="text/javascript">
$(function(){
$('.column').equalHeight();
});
</script>
</head>
<body>
<header id="header">
<hgroup>
<h1 class="site_title">Administration Panel</h1>
<h2 class="section_title">New Post</h2><div class="btn_view_site">
View Site</div>
</hgroup>
</header>
<!-- end of header bar -->
<section id="secondary_bar">
<div class="user">
<p>Hello, <?php echo $_SESSION['username']; ?> (Logout)</p>
</div>
<div class="breadcrumbs_container">
<article class="breadcrumbs">Administration Panel
<div class="breadcrumb_divider"></div>
<a class="current">New Post</a></article>
</div>
</section>
<!-- end of secondary bar -->
<aside id="sidebar" class="column" style="height:160%;">
<hr/>
<h3>Pages</h3>
<ul class="toggle">
<li class="icn_new_article">Add a New Page</li>
<li class="icn_edit_article">Edit/Delete a Page</li>
</ul>
<hr/>
<h3>Users</h3>
<ul class="toggle">
<li class="icn_add_user">Add New User</li>
<li class="icn_view_users">View Users</li>
</ul>
<hr/>
<h3>Blog</h3>
<ul class="toggle">
<li class="icn_categories">Create a Category</li>
<li class="icn_new_article">Create/Edit a Post</li>
<li class="icn_settings">Home Blog Settings</li>
<li class="icn_settings">Blog Settings</li>
</ul>
<hr/>
<h3>Settings</h3>
<ul class="toggle">
<li class="icn_settings">Settings</li>
<li class="icn_settings">Site Logo</li>
<li class="icn_jump_back">Logout</li>
</ul>
<footer>
<hr />
<p><strong>Copyright © 2013 Sky Define</strong></p>
<p>Powered by Sky Define</p>
</br>
</br>
</footer>
</aside><!-- end of sidebar -->
<section id="main" class="column">
<?php
move_uploaded_file($_FILES['post_photo']['tmp_name'], $target);
// output a list of the fields that had errors
if (!empty($errors)) {
echo "<p class=\"errors\">";
echo "Please review the following fields:<br />";
foreach($errors as $error) {
echo " - " . $error . "<br />";
}
echo "</p>";
}
?>
<article class="module width_full">
<header><h3>New Post</h3></header>
<div class="module_content">
<h2>Adding New Post</h2>
<?php if (!empty($message)) {echo "<p class=\"message\">" . $message . "</p>";} ?>
<?php if (!empty($errors)) { display_errors($errors); } ?>
<div class="mws-panel grid_4">
<div class="mws-panel-header">
</div>
<div class="mws-panel-body">
<form class="mws-form" enctype="multipart/form-data" action="new_post.php?cat=<?php echo $sel_category['id']; ?>" method="post">
<div class="mws-form-inline">
<?php $new_post = true; ?>
<?php if (!isset($new_post)) {$new_post = false;} ?>
<div class="mws-form-row">
<label>Post Name:</label>
<div class="mws-form-item large">
<input type="text" name="post_title" id="post_title" class="mws-textinput" placeholder="Post Name Goes Here." />
</div>
</div>
<div class="mws-form-row">
<label>Post Description:</label>
<div class="mws-form-item large">
<input type="text" name="post_description" id="post_description" class="mws-textinput" placeholder="Post Description Goes Here." />
</div>
</div>
<div class="mws-form-row">
<label>Post Keywords:</label>
<div class="mws-form-item large">
<input type="text" name="post_keywords" id="post_keywords" class="mws-textinput" placeholder="Post Keywords Goes Here, Separated By Commas!" />
</div>
</div>
<div class="mws-form-row">
<label>Post Content:</label>
<div class="mws-form-item large">
<textarea name="post_content" id="post_content" class="ckeditor" > </textarea>
</div>
</div>
<div class="mws-form-row">
<label>Post Tags:</label>
<div class="mws-form-item large">
<input type="text" name="post_tags" id="post_tags" class="mws-textinput" placeholder="Post Tags Goes Here, Separated By Commas!" />
</div>
</div>
<div class="mws-form-row">
<label>Edit Post Photo:</label>
<div class="mws-form-item large">
<input type="file" name="post_photo" id="post_photo" />
</div>
</div>
<div class="mws-form-row">
<label>Position:</label>
<div class="mws-form-item large">
<select name="position">
<?php
if (!$new_post) {
$post_set = get_posts_for_category($sel_post['category_id']);
$post_count = mysql_num_rows($post_set);
} else {
$post_set = get_posts_for_category($sel_category['id']);
$post_count = mysql_num_rows($post_set) + 1;
}
for ($count=1; $count <= $post_count; $count++) {
echo "<option value=\"{$count}\"";
if ($sel_post['position'] == $count) { echo " selected"; }
echo ">{$count}</option>";
}
?>
</select>
</div>
</div>
<div class="mws-form-row">
<label>Visible:</label>
<div class="mws-form-item large">
<input type="radio" name="visible" value="0"<?php
if ($sel_post['visible'] == 0) { echo " checked"; }
?> /> No
<input type="radio" name="visible" value="1"<?php
if ($sel_post['visible'] == 1) { echo " checked"; }
?> /> Yes
</div>
</div>
</form>
<div class="mws-button-row">
<input type="submit" name="submit" value="Add Post" class="mws-button green" />
<a class="mws-button red" href="index.php">Cancel</a>
</div>
</div>
</div>
</div>
</article>
<div class="clear"></div>
</div>
</article><!-- end of stats article -->
<div class="spacer"></div>
</section>
</body>
</html>
The way I would try to find the error:
make your errors visible:
<?php error_reporting(E_ALL); ?>
$target should be a full path.
Check your HTML form. Did you add the enctype attribute?
<form enctype="multipart/form-data" method="POST" action="script.php">
Is your Input correct?
<input type="file" name="post_photo"/>
What does the $_FILES array contents?
<?php echo print_r($_FILES); ?>
Edit
Please let us know the data these lines return:
<?php
error_reporting(E_ALL);
echo "<pre>";
print_r($_FILES);
echo "</pre>";
echo "<br/>target: " . $target;
if (!move_uploaded_file($_FILES['post_photo']['tmp_name'], $target)) {
echo "<br/>Upload failed.";
} else {
echo "<br/>Upload done."
}
?>
Edit 2 (Solution):
Your submit-button is outside the form-Tag. That's why. Fix it like this:
<form>
<input type="submit" name="submit" value="Add Post" class="mws-button green" />
</form>
Your $target should contain the root path
$target = $_SERVER['DOCUMENT_ROOT']"/upload/";
$target = $target . basename( $_FILES['post_photo']['name']);

Javascript Reload after Jquery call with Php

I have a problem I've been trying to solve for the past days. I have a Jquery that updates an HTML and creates new content inside a div tag. The thing is that the javascript does not apply on the generated code. In other words, I could take the exact output that the Php gives me, put it in the html code directly and it works, but if it comes from the php while the page is running it won't work, it doesn't display the images correctly in a slideshow jflow.
Here is the HTML header
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script src="js/jquery.robwalsh.randomImageOnload.js" type="text/javascript" charset="utf-8"></script>
<script src="js/application.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.flow.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("div#controller").jFlow({
slides: "#slides",
width: "785px",
height: "480px"
});
});
</script>
<script type="text/javascript">
/* SLIDESHOW AT HOMEPAGE */
function slideSwitch() {
var $active = $('#slideshow IMG.active');
if ( $active.length == 0 ) $active = $('#slideshow IMG:last');
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
$active.addClass('last-active');
$next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval( "slideSwitch()", 5000 );
});
</script>
<script type="text/javascript">
/* Function to show/hide the side menu for all images */
function showDIV(e)
{
var notEmpty = true;
var count = 0;
while(document.getElementById('subCat'+count) != null)
{
document.getElementById('subCat'+count).style.display = 'none';
count++;
}
document.getElementById(e).style.display = 'block';
}
/* MENU INTERACTION */
function showContent(cmd, id)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("contentMain").innerHTML=xmlhttp.responseText;
document.getElementById("controller").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getMain.php?cmd="+cmd+"&id="+id,true);
xmlhttp.send();
}
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-21909616-1']);
_gaq.push(['_setDomainName', '.karimtabar.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO 8859-1" />
<link rel="stylesheet" type"text/css" href="css/stylesheet.css" />
<link rel="shortcut icon" href="logo/icon.jpg">
<title>KARIM V TABAR PHOTOGRAPHY</title>
<meta name="description" content="Karim V Tabar: photographer, new media, film, design." />
</head>
<body style="width:100%;">
<div id="wholewrapper" >
<!-- HEADER // TOP PORTION OF SITE -->
<div id="logoheader">
<h5 class="logo">
KARIM VICTOR TABAR
</h5>
</div>
<div class="wrapper">
<div class="navcontainer">
<?php
$count = 0;
foreach (new DirectoryIterator('images/menuImages') as $fileInfo)
{
if($fileInfo->isDot()) continue;
echo "<h2 class='acc_trigger' onclick=\"showDIV('subCat".$count."'); showContent(1, '".$fileInfo->getFilename() ."');\"><a href='#'>".$fileInfo->getFilename() ."</a></h2><div class='acc_container' id='container".$count."'><div class='block' name='subCats' id='subCat".$count."'><ul>";
foreach (new DirectoryIterator('images/menuImages/'.$fileInfo) as $fileInfo2)
{
if($fileInfo2->isDot() || $fileInfo2 == "thumbnails") continue;
echo "<li>".$fileInfo2->getFilename() . "</li>";
}
echo "</ul></div></div>";$count++;
}
?>
<div id="navigationlinks">
<ul>
<li>BIO</li>
<li>CONTACT</li>
<li>BLOG</li></ul>
</div>
</div>
<!-- Images Thumbnails Categories -->
<div id="contentMain">
<div id="slideshow">
<img src="images/homepage/bb1.jpg" width = "750px" alt="" class="active" />
<img src="images/homepage/et1.jpg" width = "750px" alt="" />
<img src="images/homepage/gaga1.jpg" width = "750px" alt="" />
<img src="images/homepage/gaga2.jpg" width = "750px" alt="" />
<img src="images/homepage/hkartwalk.jpg" width = "750px" alt="" />
<img src="images/homepage/homepagegirl.jpg" width = "750px" alt="" />
<img src="images/homepage/rodeo2.jpg" width = "750px" alt="" />
<img src="images/homepage/rodeo5.jpg" width = "750px" alt="" />
<img src="images/homepage/silverwig_gaga.jpg" width = "750px" alt="" />
<img src="images/homepage/wavy1.jpg" width = "750px" alt="" />
<img src="images/homepage/Wenya.jpg" width = "750px" alt="" />
</div>
</div>
</body>
</html>
And Here is the Php code that generates the new HTML(getMain.php)
<?php
$cmd=$_GET["cmd"];
$id = $_GET["id"];
/* The Thumbnail Display */
if($cmd == 1)
{
echo "<div id='thumbnailcontentplaceholder'>";
echo "<div id='thumbnailcontent'>";
echo "<ul>";
$dir = "images/menuImages/".$id."/thumbnails";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) != false) {
if(is_dir($file)) continue;
echo "<li>";
echo "<a href='#' title='".$file."'><img src='".$dir."/".$file."' alt='' /></a>";
echo "<div id='thumnailtitle'>".substr($file, 0, strpos($file, "."))."</div>";
echo "</li>";
}
closedir($dh);
}
}
echo "</div></div>";
}
if($cmd == 2)
{
$dir = "images/menuImages/".$id;
$count = 1;
$nFiles = countFiles($dir);
echo "<div id='imageplaceholder'> \n";
/* No1 No2 No3 ... */
echo "<div id='controller' class='hidden'>\n";
for($i =1; $i < $nFiles; $i++)
{
echo "<span class='jFlowControl'>No ".$i."</span>\n";
}
echo "</div>";
echo "<div id='slides'>";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) != false) {
if(is_dir($file)) continue;
echo "<div><img src='".$dir."/".$file."'></div>\n";
}
closedir($dh);
}
}
echo "</div>\n";
echo '<div id="prevNext">
<a id="prev_275997_0" class="jFlowPrev" href="#" onfocus="this.blur()">Previous</a>
<span class="slide_slash">/</span>
<a id="next_275997_0" class="jFlowNext" href="#" onfocus="this.blur()">Next image</a> </div>';
echo '<div id="credits2">
BEIJING BLUE<br>
Photographed by: Karim V Tabar<br></div></div>';
}
function countFiles($dir)
{
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
if ($files)
$num_of_files = count($files) - 2; // we substract 2 because . and .. are included
else
die('there is an error');
return $num_of_files;
}
?>
Thanks
Real HTML that used to work was like this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script src="../../js/jquery.flow.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
//Set default open/close settings
$('.acc_container').hide(); //Hide/close all containers
$('.acc_trigger:first').addClass('active').next().show(); //Add "active" class to first trigger, then show/open the immediate next container$(document).ready(function(){
//On Click
$('.acc_trigger').click(function(){
('#open').click()
});
});
</script>
<script type="text/javascript">
$(function() {
$("div#controller").jFlow({
slides: "#slides",
width: "785px",
height: "480px"
});
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-21909616-1']);
_gaq.push(['_setDomainName', '.karimtabar.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type"text/css" href="../../css/stylesheet.css">
<link rel="shortcut icon" href="../../logo/icon.jpg">
<title>KARIM V TABAR PHOTOGRAPHY</title>
<meta name="description" content="Karim V Tabar: photographer, new media, film, design." />
</head>
<body style="width:100%;">
<div id="wholewrapper">
<!-- HEADER // TOP PORTION OF SITE -->
<div id="logoheader">
<h5 class="logo">
KARIM VICTOR TABAR
</h5>
</div>
<div class="wrapper">
<div class="navcontainer">
<h2 class="acc_trigger">EDITORIAL</h2>
<div class="acc_container">
<div class="block"> <ul> <li>BEIJING BLUE</li>
<li>GAGA</li>
<li>DOUBLE TROUBLE</li>
<li>EXTRATERRESTRIAL DREAMS</li>
<li>LIFE RUSH</li>
<li>RODEO GLAM</li>
<li>WANDERLUST</li>
<li>RUN AWAY ANGEL</li>
<li>RUSSIAN STANDARD</li>
<li>HOLLYWOOD HILLS</li></ul>
</div>
</div> <h2 class="acc_trigger">TRAVEL</h2>
<div class="acc_container">
<div class="block">
<ul>
<li>HONG KONG</li> </li>
<li>DUBAI, UAE</li>
<li>KYOTO, JAPAN</li>
<li>MIAMI, USA</li>
<li>L.A., USA</li></ul>
</div>
</div>
<h2 class="acc_trigger">ART</h2>
<div class="acc_container">
<div class="block">
<ul> <li>MIRROR ANGEL</li>
<li>ROUGE</li>
<li>VIOLET</li>
<li>NOIRE</li></ul>
</div>
</div> <h2 class="acc_trigger">VIDEO</h2>
<div class="acc_container">
<div class="block">
<ul>
<li>ZIGMAT - BETWEEN BULLETS VIDEO</li><li>ZIGMAT - BEHIND THE SCNES</li></ul>
</div>
</div>
<h2 class="acc_trigger">EXHIBITIONS</h2>
<div class="acc_container">
<div class="block">
<ul>
<li>2009 RESIDENT, MONTRÉAL, CANADA</li><li>2011 ART WALK, HONG KONG, CHINA</li>
</ul>
</div>
</div><!-- <h2 class="acc_trigger">PRESS</h2>
<div class="acc_container">
<div class="block">
<ul>
<li>NME</li>
<li>LIVE FAST MAG</li>
<li>GURU</li></ul>
</div>
</div>
--><div id="navigationlinks">
<ul>
<li>BIO</li>
<li>CONTACT</li>
<li>BLOG</li></ul>
</div> <!-- <div id="buyherelogo">
<img src="../../store/buyhere.png" width="150" border="0">
</div>
--></div>
<!--IMAGE // RIGHT PORTION -->
<div id="imageplaceholder">
<div id="controller" class="hidden">
<span class="jFlowControl">No 1</span>
<span class="jFlowControl">No 2</span>
<span class="jFlowControl">No 3</span>
<span class="jFlowControl">No 4</span>
<span class="jFlowControl">No 5</span>
<span class="jFlowControl">No 6</span>
<span class="jFlowControl">No 7</span>
</div>
<div id="slides">
<div><img src="../../images/fashion/beijingblue/bb1.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb2.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb3.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb4.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb5.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb6.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb7.jpg" width="785" height="480"></div>
</div>
<div id="prevNext">
<a id="prev_275997_0" class="jFlowPrev" href="#" onfocus="this.blur()">Previous</a>
<span class="slide_slash">/</span>
<a id="next_275997_0" class="jFlowNext" href="#" onfocus="this.blur()">Next image</a>
</div>
<div id="credits2">
BEIJING BLUE<br>
Photographed by: Karim V Tabar<br>
</div>
</div>
</div>
</div>
</body>
</html>
When you bind events, or call jQuery functions, the element needs to exist in the DOM for jQuery to find it.
Because you are populating your page after the script has executed, there's no element's to be selected (despite placing the selection in a document.ready callback.
If you did a console.log on $('div#controller') you'd see an empty jQuery object.
If you, instead, used the complete callback to register your jsFlow call, you should see things working as expected.
Is there a reason you're not using jQuery's normalized ajax functions?
You use <div id="contentMain"> in the code, but you call it on div#controller? Anyways, it wouldn't work even if you specified the correct selector, because as zzzzBov answered, when the page loads, your div is empty. You have to recall the jFlow function after you update the content:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("contentMain").innerHTML=xmlhttp.responseText;
$("div#contentMain").jFlow({
slides: "#slides",
width: "785px",
height: "480px"
});
}

Categories