The issue is that at form submission through ajax the page still reloads, even though the code has been written for it to not refresh the page, but only a certain div tag. It refreshes the div tag successfully.
As far as I can see (I have quintuple checked) the javascript form submission is written correctly as is the div refresh code.
There might be a problem in the php code where the form and the div that refreshes through ajax are present. The php file and the ajax javascript file are below...
Php file: The div gets refreshed by calling GET ajax=1. The form is called "addmonitor" and the div id is "monitor_form" - located around 2/3 down the bottom of the php code:
<?php
if (DIRECTORY_SEPARATOR=='/'){
define('EZMON_C', dirname(__FILE__));
}else{
define('EZMON_C', str_replace("\\", '/', dirname(__FILE__)));
}
require_once(EZMON_C.'/admin/local_config.php');
function mak_pwords($string, $saltkey, $pos=15) {
$stringA = sha1($string);
$salt = md5($saltkey);
$afterstr = substr($stringA, $pos);
$startbeginning = -(strlen($afterstr));
$beforestr = substr($stringA, 0, $startbeginning);
$hex = '/$E'; // fake ending
$salted = $beforestr . $salt . $afterstr . $hex;
return $salted;
}
//Path to location of local_config.php
error_reporting(0);
// resume the existing session, or establish a new one
session_start();
// Check Login
if(!isset($_SESSION['s_username']) && !isset($_SESSION['s_password']))
{
header("Location:index.php");
exit;
}
//$uid = isset($_GET['uid'])?intval($_GET['uid']):0;
// TODO: this is so wrong, but must remain for now. IMPORTANT!!! move this to index.php, where i assume login password checking is performed.
$uid = isset($_GET['uid'])?intval($_GET['uid']):0;
$_SESSION['uid']=$uid;
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
// Added by KTHSoft
if (isset($_GET['ajax'])){
$get_items = 'SELECT * FROM servers WHERE user_id=\''.mysql_real_escape_string($uid).'\'';
$get_items_res = mysql_query($get_items) or die(mysql_error( ));
$total_items = mysql_num_rows($get_items_res);
# Define the number of results per page
$max_results = 10;
/* Figure out the limit for the query based
on the current page number. */
$from = (($page * $max_results) - $max_results);
# get only the limited results
$get_limited_items = "SELECT * FROM servers WHERE user_id='".mysql_real_escape_string($uid)."' ORDER BY com_domain ASC LIMIT $from, $max_results";
$get_limited_items_res = mysql_query($get_limited_items) or die(mysql_error( ));
echo '<table><b>Monitors:</b></table>';
echo '<table>';
$turn = "275";
$cookies_defined = False; // Added by Predrag Bradaric (31. March 2011)
while ($items = mysql_fetch_array ($get_limited_items_res))
{
$domain = $items['domain'];
$com_domain = $items['com_domain'];
$port = $items['port'];
$last_time = $items['last_time'];
$last_date = $items['last_date'];
$last_status = $items['last_status'];
$active = $items['active'];
$sid = $items['id'];
if($last_status==1) {
$status = '<td width="10" align="left"><img src="images/rarrow.png" alt="Website Down" title="Website Down" style="margin-top: 2px;"></td>';
}elseif($last_status == 0){
if($active == 1){
if($last_time !=""){
$status = '<td width="10" align="left"><img src="images/garrow.png" alt="Website Up" title="Website Up" style="margin-top: 2px;"></td>';
}else{
$status = '<td width="10" align="left"><img src="images/pause.png" alt="Monitoring not started yet" title="Monitoring not started yet" style="margin-top: 2px;"></td>';
}
$last_updtt = $last_time;
$last_updtd = $last_date;
}
if($active==0){
$status = '<td width="10" align="left"><img src="images/pause.png" alt="Website Not Monitored" title="Website Not Monitored" style="margin-top: 2px;"></td>';
}
}else{
$status = '<td>Unknown</td>';
}
if($port==80){$port_type="HTTP";
}elseif($port==21){$port_type="FTP";
}elseif($port==143){$port_type="IMAP";
}elseif($port==25){$port_type="SMTP";
}elseif($port==5060){$port_type="SIP";
}elseif($port==110){$port_type="POP";
}elseif($port==443){$port_type="HTTPS";
}elseif($port==2082){$port_type="cPanel";
}elseif($port==2086){$port_type="WHM";
}elseif($port==3306){$port_type="MySQL";
}else{$port_type=$port;}
if($last_time==""){
$last_time="Monitoring not started yet";
}
echo '<tr>'.$status
?>
<!-- MODIFIED BY Predrag Bradaric (29. March 2011) -->
<?php
if (!(isset($_GET['donotrefresh']))) {
if (isset($_COOKIE["$com_domain$port"])) {
$cookies_defined = True;
}
?>
<script type="text/javascript">
if (dhtmlwindow.getCookie("<?php echo "$com_domain$port"; ?>")) {
var window_name = "<?php echo "$com_domain$port"; ?>";
<?php echo "$com_domain$port"; ?> = dhtmlwindow.open(window_name, dhtmlwindow.getCookie(window_name).split("~")[4], decodeURIComponent(dhtmlwindow.getCookie(window_name).split("~")[5]), dhtmlwindow.getCookie(window_name).split("~")[6], 'width='+dhtmlwindow.getCookie(window_name).split("~")[2]+',height='+dhtmlwindow.getCookie(window_name).split("~")[3]+',left='+dhtmlwindow.getCookie(window_name).split("~")[0]+',top='+dhtmlwindow.getCookie(window_name).split("~")[1]+',resize=0,scrolling=0', 'recal');
}
// alert(dhtmlwindow.getCookie("<?php echo "$com_domain$port"; ?>"))
</script>
<!-- END OF MODIFICATION (29. March 2011) -->
<?php } ?>
<td> <!--
<?php echo $domain; ?><?php echo ' ' . $port_type; ?> -->
<?php echo $domain; ?><?php echo ' ' . $port_type; ?>
</td>
<?php
# monitor buttons to pause, resume and delete
if ($active == 1)
{
?>
<td align="right" width="25" style="font-size: 11px; color: #666;">
<img src="images/control_pause.png" title="Pause monitor: <?php echo $domain; ?>" alt="Pause monitor: <?php echo $domain; ?>" height="16" width="16" border="0"></td>
<!--
<td align="right" width="25" style="font-size: 11px; color: #666;">
<img src="images/control_pause.png" title="Pause monitor: <?php echo $domain; ?>" alt="Pause monitor: <?php echo $domain; ?>" height="16" width="16" border="0"></td> -->
<?php
}
else if ($active == 0)
{
?>
<td align="right" width="25" style="font-size: 11px; color: #666;">
<img src="images/control_play_blue.png" title="Resume monitor: <?php echo $domain; ?>" alt="Resume monitor: <?php echo $domain; ?>" height="16" width="16" border="0"></td>
<!--
<td align="right" width="25" style="font-size: 11px; color: #666;">
<img src="images/control_play_blue.png" title="Resume monitor: <?php echo $domain; ?>" alt="Resume monitor: <?php echo $domain; ?>" height="16" width="16" border="0"></td> -->
<?php
}
?>
<td align="right" width="18" style="font-size: 11px; color: #666;">
<img src="images/delete.png" title="Delete monitor: <?php echo $domain; ?>" alt="Delete monitor: <?php echo $domain; ?>" height="16" width="16" border="0"></td>
<!--
<td align="right" width="18" style="font-size: 11px; color: #666;">
<img src="images/delete.png" title="Delete monitor: <?php echo $domain; ?>" alt="Delete monitor: <?php echo $domain; ?>" height="16" width="16" border="0"></td> -->
<?php
# set position of windows displaying the graphs
if ($turn == "275")
{
$turn = "730";
}
else if ($turn == "730")
{
$turn = "275";
}
}
echo "</table>";
// MODIFIED BY Predrag Bradaric (31. March 2011)
if (!($cookies_defined) && !(isset($_GET['donotrefresh']))) {
// init dhtml windows from database
// at this point $uid should be valid user id
include("dhtmlretrieve.php");
}
// END OF MODIFICATION (31. March 2011)
# begin page numbers output
# Figure out the total number of pages. Always round up using ceil()
$total_pages = ceil($total_items / $max_results);
# Build Page Number Hyperlinks
echo "<center><font size=\"2\" color=\"#666666\"face=\"Arial, Helvetica, sans-serif\">Pages of your monitors:<br /></font>";
if($page <= 7)
{
$from_linkedpage = 1;
$to_linkedpage = 15;
}
else
{
if($page > $total_pages - 7)
{
$from_linkedpage = $total_pages - 15;
$to_linkedpage = $total_pages;
}
else
{
$from_linkedpage = $page - 7; //15*floor($page / 15)+1;
$to_linkedpage = $page + 7; //$from_linkedpage + 14;
}
}
if ($to_linkedpage > $total_pages)
{
$to_linkedpage = $total_pages;
}
if ($from_linkedpage < 1)
{
$from_linkedpage = 1;
}
// Build Previous Link
if(($from_linkedpage > 1) || ($page > 1))
{
$prev = ($page - 1);
echo '<a onclick="goToPage(' . $prev . ')" href="#"><b>< Previous</b></a> ';
}
for($j = $from_linkedpage; $j <= $to_linkedpage; $j++)
{
if(($page) == $j)
{
echo "$j ";
}
else
{
echo '<a onclick="goToPage(' . $j . ')" href="#">'.$j.'</a> ';
}
}
// Build Next Link
if($page < $total_pages)
{
$next = ($page + 1);
echo ' <a onclick="goToPage(' . $next . ')" href="#"><b>Next ></b></a>';
}
echo "</font></center><br>";
?>
<script type='text/javascript'>
function goToPage(page){
var dataString = 'ajax=1&donotrefresh=1&page=' + page + '&uid=<?php echo $uid;?>';
$.ajax({
type: "GET",
url: "monpanel.php",
data: dataString,
success: function(html_data){
$('#list_monitors').html(html_data);
}
});
}
</script>
<?php
die();
}
// End added by KTHSoft
/* Temporary config.php replacement */
$uname_admin = $setting['uname_admin'];
$pword_admin = $setting['pword_admin'];
$allow_add = $setting['allow_add'];
$mon_int = $setting['mon_int'];
$max_fail = $setting['max_fail'];
$time_out = $setting['time_out'];
$mon_email = $setting['mon_email'];
$do_logging = $setting['do_logging'];
$fully_log = $setting['fully_log'];
$err_check = $setting['err_check'];
$email_override = $setting['email_override'];
$cfg_offset = $setting['cfg_offset'];
$pingIP_host = $setting['pingIP_host'];
$ping_delay = $setting['ping_delay'];
$num_pings = $setting['num_pings'];
$reliable_test_server = $setting['reliable_test_server'];
$reliable_test_server2 = $setting['reliable_test_server2'];
$date_format = $setting['date_format'];
$version = $setting['version'];
/* End Temporary config.php replacement */
error_reporting(0);
$style='';
$uid = isset($_GET['uid'])?intval($_GET['uid']):0;
$title=' - Viewing UserID:'.$uid.' Servers Status';
header("Cache-Control: must-revalidate");
$offset = 60 * 60 * 24 * -1;
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
header($ExpStr);
include("header.php");
$monthnow = date("m");
$yearnow = date("Y");
/*
# Delete Monitors
if (isset($_GET["act"]) && $_GET["act"] == "delete") {
$del_items="DELETE FROM servers WHERE id='$_GET[sid]' AND user_id='$_GET[uid]'";
mysql_query($del_items) or die(mysql_error( ));
#echo '<script>alert("Monitor Deleted Successfully!")</script>';
}
# Pause Monitors
if (isset($_GET["act"]) && $_GET["act"] == "pause") {
$pause_items="UPDATE servers SET active=0 WHERE id='$_GET[sid]' AND user_id='$_GET[uid]'";
mysql_query($pause_items) or die(mysql_error( ));
#echo '<script>alert("Monitor Paused Successfully!")</script>';
}
# Resume Monitors
if (isset($_GET["act"]) && $_GET["act"] == "resume") {
$resume_items="UPDATE servers SET active=1 WHERE id='$_GET[sid]' AND user_id='$_GET[uid]'";
mysql_query($resume_items) or die(mysql_error( ));
#echo '<script>alert("Monitor Paused Successfully!")</script>';
}
*/
?>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery.cookie.min.js"></script>
<link rel="stylesheet" href="windowfiles/dhtmlwindow.css" type="text/css" />
<script type="text/javascript" src="windowfiles/dhtmlwindow.js"></script>
<link rel="stylesheet" href="modalfiles/modal.css" type="text/css" />
<script type="text/javascript" src="modalfiles/modal.js"></script>
<script type="text/javascript" src="validate.js"></script>
<input type="hidden" id="hidUid" value="<?php echo (intval($uid)); ?>"/>
<?php
// Sanitise security addition
if (is_int(intval($uid))){$uid = intval($uid);}else{$uid = 0;}
if ($uid != '')
{
$date_array = getdate();
foreach ($date_array as $key => $val) {$key = $val;}
$mon=$date_array['mon'];
if($mon<10){$mon="0$mon";}
$day=$date_array['mday'];
if($day<10){$day="0$day";}
$year=$date_array['year'];
$hrs=$date_array['hours'];
if($hrs<10){$hrs="0$hrs";}
$min=$date_array['minutes'];
if($min<10){$min="0$min";}
$sec=$date_array['seconds'];
if($sec<10){$sec="0$sec";}
$time="$hrs:$min:$sec";
// date = month/day/year 10/05/2006
if ($setting['date_format'] == 'day/month/year'){
$day_mon_yr = "$day/$mon/$year";
$date = "$day-$mon-$year";
}
if ($setting['date_format'] == 'month/day/year'){
$day_mon_yr = "$mon/$day/$year";
$date = "$mon-$day-$year";
}
if ($setting['date_format'] == 'year/month/day'){
$day_mon_yr = "$year/$mon/$day";
$date = "$year-$mon-$day";
}
echo '<table align="left" valign="top" width="255" style="margin-top: 0px;">';
if(isset($_SESSION['s_username']))
{
echo '<tr><td width="10"> </td><td style="border: 1px solid #666666; background: #fff; padding: 12px;">';
// loop through the monitors the user has and display them in the menu
$get_items = "SELECT * FROM servers WHERE user_id='$uid'";
$get_items_res = mysql_query($get_items) or die(mysql_error( ));
if(isset($_SESSION['s_username']))
{
?>
<script type='text/javascript'>
var dataString = 'ajax=1&page=' + <?php echo $page?> + '&uid=<?php echo $uid;?>';
$.ajax({
type: "GET",
url: "monpanel.php",
data: dataString,
success: function(html_data){
$('#list_monitors').html(html_data);
}
});
</script>
<?php
echo '<div id="list_monitors">';
echo "</div>";
// chaeck if the user logged in is a paid customer
#$get_paid = "SELECT paid FROM servers WHERE user_id='$uid' LIMIT 1";
#$get_paid_res = mysql_query($get_paid) or die(mysql_error( ));
while ($item_paid = mysql_fetch_array ($get_items_res))
{
$paid_array = $item_paid['paid'];
$paid = $paid_array[0];
}
if ($paid == "1")
{
?>
<div id="monitor_form">
<fieldset border="0">
<table align="left">
<form name="addmonitor" action=""> <!-- action="user_add.php" method="POST" -->
<tr>
<td colspan="2"><font color="#666666"><strong>Add new monitor:</strong></font></td>
</tr>
<input type="hidden" name="cemail" id="cemail" value="<?=$_SESSION['s_username']?>" />
<tr>
<td><label for="domain" id="domain_label" style="text-align: left;">Website URL/IP<br>
<font size="1" color="red">without http://www.</font></label></td>
<td valign="top"><input type="text" size="13" name="domain" id="domain" class="text-input" /></td>
</tr>
<tr>
<td><label class="error" for="domain" id="domain_error">Field is required.</label></td>
</tr>
<tr>
<td><label for="com_domain" id="com_domain_label" style="text-align: left;">Monitor Name</label></td>
<td valign="top"><input type="text" size="13" name="com_domain" id="com_domain" class="text-input" /></td>
</tr>
<tr>
<td><label class="error" for="com_domain" id="com_domain_error">Field is required.</label></td>
</tr>
<tr>
<td><label for="port" id="port_label" style="text-align: left;">Port</label></td>
<td valign="top"><select name="port" id="port" class="select-input">
<option value="80" SELECTED>HTTP: 80</option>
<option value="443">HTTPS: 443</option>
<option value="21">FTP: 21</option>
<option value="5060">SIP: 5060</option>
<option value="80">TCP: 80</option>
<option value="5060">UDP: 5060</option>
<option value="143">IMAP: 143</option>
<option value="25">SMTP: 25</option>
<option value="110">POP3: 110</option>
</select></td>
</tr>
<tr>
<input type="hidden" name="active" id="active" value="1" />
<input type="hidden" name="uid" id="uid" value="<?php echo $uid;?>" />
</tr>
<tr>
<td><label for="main" id="main_label" style="text-align: left;">Main<br>
<font size="1" color="red">only one per URL/IP</font></label></td>
<td valign="top"><select name="main" id="main" class="select-input">
<option value="0">No</option>
<option value="1">Yes</option>
</select></td>
</tr>
<tr>
<td><input type="submit" value="Add monitor" name="addserver" class="button" id="addserver_btn" /></td> <!-- name="addserver" -->
</tr>
</form>
</table>
</fieldset>
</div>
<?php
}
else if ($paid == "0")
{
?>
<div id="free">
<fieldset border="0">
<table align="left">
<form name="free" action=""> <!-- action="user_add.php" method="POST" -->
<tr>
<td colspan="2"><font color="#666666"><strong>Add new monitor:</strong></font></td>
</tr>
<tr>
<td><label for="free" id="free" style="text-align: left;">Website URL/IP<br>
<font size="1" color="red">without http://www.</font></label></td>
<td valign="top"><input type="text" size="13" name="free" id="free" class="text-input" /></td>
</tr>
<tr>
<td><label for="free1" id="free1" style="text-align: left;">Monitor Name</label></td>
<td valign="top"><input type="text" size="13" name="free1" id="free1" class="text-input" /></td>
</tr>
<tr>
<td><label for="free2" id="free2" style="text-align: left;">Port</label></td>
<td valign="top"><select name="free2" id="free2" class="select-input">
<option value="80" SELECTED>HTTP: 80</option>
<option value="443">HTTPS: 443</option>
<option value="21">FTP: 21</option>
<option value="5060">SIP: 5060</option>
<option value="80">TCP: 80</option>
<option value="5060">UDP: 5060</option>
<option value="143">IMAP: 143</option>
<option value="25">SMTP: 25</option>
<option value="110">POP3: 110</option>
</select></td>
</tr>
<tr>
<td><label for="free3" id="free3" style="text-align: left;">Main<br>
<font size="1" color="red">only one per URL/IP</font></label></td>
<td valign="top"><select name="free3" id="free3" class="select-input">
<option value="0">No</option>
<option value="1">Yes</option>
</select></td>
</tr>
<tr>
<td><input type="submit" value="Add monitor" name="free4" class="button" id="free4"
onClick="pay=dhtmlmodal.open('pay', 'div', 'paydiv', 'Paid Account', 'width=425px,height=267px,center=1,resize=0,scrolling=0'); return false" /></td> <!-- name="addserver" -->
</tr>
</form>
</table>
</fieldset>
</div>
<div id="paydiv" style="display:none">
<center>
<h4>To monitor more websites subscribe to our advanced service:</h4>
1) You get to set up monitors for an <b>unlimited number of websites</b><br>2) Unlimited alert emails<br>3) Unlimited alert SMS messages<br>4) and much more for only $5 per month...<br><br>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GDTCMF9N56TKG">
<input type="image" src="https://www.paypal.com/en_AU/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_AU/i/scr/pixel.gif" width="1" height="1">
</form>
<br><br>
</center>
</div>
<?php
}
echo '<br><table><b>Account:</b></table>';
echo '<table>';
?>
<tr><td><img src="images/user.png" title="Edit Profile" alt="Edit Profile">
Edit Profile<br>
<img src="images/lock.png" title="Change Password" alt="Change Password">
Change Password<br>
<img src="images/monitor_go.png" title="Logout" alt="Logout"> Logout</tr></td></table>
</table>
<?php
}
}
}
else
{
echo '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
echo '<center><strong>Sorry, You have accessed this page improperly and your access has been logged.</strong></center>';
}
include_once('footer.php');
end;
?>
and the javascript file (only the relevant function):
// Exibit no.1
$(function() {
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var domain = $("input#domain").val();
if (domain == "") {
$("label#domain_error").show();
$("input#domain").focus();
return false;
}
var com_domain = $("input#com_domain").val();
if (com_domain == "") {
$("label#com_domain_error").show();
$("input#com_domain").focus();
return false;
}
var cemail = $("input#cemail").val();
var port = $("select#port").val();
var active = $("input#active").val();
var uid = $("input#uid").val();
var main = $("select#main").val();
var dataString = 'cemail='+ cemail + '&domain=' + domain + '&com_domain=' + com_domain + '&active=' + active + '&main=' + main + '&port=' + port;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "user_add.php",
data: dataString,
success: function() {
$('#monitor_form').append("<div id='message'></div>");
$('#monitor_form form')[0].reset();
$('#message').html("<img id='checkmark' src='images/tick.png' /><b> Monitor sucessfully added!</b>")
.hide()
.fadeIn(500, function() {
$('#message').append("");
});
setTimeout("$('#message').hide().remove();", 6000);
var dataString2 = 'ajax=1&uid=' + uid;
$.ajax({
async: false,
type: "GET",
dataType: "html",
url: "monpanel.php",
data: dataString2,
success: function(html_data){
$('#list_monitors',top.document).html(html_data);
}
});
//document.onkeydown = showDown;
}
});
return false;
});
});
function showDown(evt) {
event = (evt)? evt : ((event)? event : null);
if (evt) {
if (event.keyCode == 8 && (event.srcElement.type!= "text" && event.srcElement.type!= "textarea" && event.srcElement.type!= "password")) {
// When backspace is pressed but not in form element
cancelKey(evt);
}
else if (event.keyCode == 116) {
// When F5 is pressed
cancelKey(evt);
}
else if (event.keyCode == 122) {
// When F11 is pressed
cancelKey(evt);
}
else if (event.ctrlKey && (event.keyCode == 78 || event.keyCode == 82)) {
// When ctrl is pressed with R or N
cancelKey(evt);
}
else if (event.altKey && event.keyCode==37 ) {
// stop Alt left cursor
return false;
}
}
}
function cancelKey(evt) {
if (evt.preventDefault) {
evt.preventDefault();
return false;
}
else {
evt.keyCode = 0;
evt.returnValue = false;
}
}
Thank you for any insight!
Do not forget to prevent the default handler:
<input type="submit" value="Send" onclick="myAjaxFunction(); return false" />
Does $(".button") have it's href set to #? If so, that'll refresh the page. I suggest using something like:
$(".button").click(function(e){
e.preventDefault();
Related
I'm using keypress via this OOP function below to update my sites shopping cart and quantity value. Sometimes it works, but most of the time when I press the enter key it doesn't a) update the cart nor b) update the qty value. I think it's refreshing the page, which could be the issue.
I took a look at the request header value by inspecting the qty element and that doesn't update when enter key pressed, if that helps.
function initBinds() {
if ($('.remove_basket').length > 0) {
$('.remove_basket').bind('click', removeFromBasket);
}
if ($('.update_basket').length > 0) {
$('.update_basket').bind('click', updateBasket);
}
if ($('.fld_qty').length > 0) {
$('.fld_qty').bind('keypress', function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
updateBasket();
}
});
}
}
And here's the updateBasket function
function updateBasket() {
$('#frm_basket :input').each(function() {
var sid = $(this).attr('id').split('-');
var val = $(this).val();
$.ajax({
type: 'POST',
url: '/mod/basket_qty.php',
data: ({ id: sid[1], qty: val }),
success: function() {
refreshSmallBasket();
refreshBigBasket();
},
error: function() {
alert('An error has occurred');
}
});
});
}
And, this is the page...
Note, you can see on line 41 the class of fld_qty is used for the initiBinds keypress function if statement.
<?php
$session = Session::getSession('basket');
$objBasket = new Basket();
$out = array();
if (!empty($session)) {
$objCatalogue = new Catalogue();
foreach ($session as $key => $value) {
$out[$key] = $objCatalogue->getProduct($key);
}
}
require_once('_header.php'); ?>
<div id="cat_prod"><h1>- BASKET -</h1></div>
<?php
if (!empty($out)) { ?>
<div id="big_basket">
<form action="" method="post" id="frm_basket">
<table cellpadding="0" cellspacing="0" border="0" class="tbl_repeat">
<tbody id="basket_table">
<tr style="background-color: #f2f3ee;">
<th class="ta_left">Item</th>
<th class="ta_r">Qty</th>
<th class="ta_r col_15">Price</th>
<th class="ta_r col_15"></th>
</tr>
<?php foreach ($out as $item) { ?>
<tr>
<td class="ta_left_name"><?php echo Helper::encodeHTML($item['name']); ?></td>
<td class="ta_left_qty"><input type="text" name="qty-<?php echo $item['id']; ?>"
id="qty-<?php echo $item['id']; ?>" class="fld_qty"
value="<?php echo $session[$item['id']]['qty']; ?>" /></td>
<td class="ta_r">£<?php echo number_format($objBasket->itemTotal($item['price'], $session[$item['id']]['qty']), 2); ?></td>
<td class="ta_r"> <?php echo Basket::removeButton($item['id']); ?></td>
</tr>
<?php } ?>
<?php if ($objBasket->_vat_rate != 0) { ?>
<tr style="border-bottom: dashed 1px #aaa">
<td class="ta_left" colspan="2">Sub-total :</td>
<td class="ta_r bt_td">£<?php echo number_format($objBasket->_sub_total, 2); ?></td>
<td class="ta_r bt_td"> </td>
</tr>
<tr style="border-bottom: dashed 1px #aaa">
<td class="ta_left" colspan="2">VAT (<?php $objBasket->_vat_rate; ?>%) :</td>
<td class="ta_r bt_td">£<?php echo number_format($objBasket->_vat, 2); ?></td>
<td class="ta_r bt_td"> </td>
</tr>
<?php } ?>
<tr>
<td class="ta_right" colspan="2"><strong>Total :</strong></td>
<td class="ta_r bt_td">£<?php echo number_format($objBasket->_total, 2); ?></td>
<td class="ta_r bt_td"> </td>
</tr>
</tbody>
</table>
<div class="dev br_td"> </div>
<div class="dev br_td"> </div>
<div class="sbm sbm_blue fl_r">
Checkout
</div>
<div class="sbm sbm_blue fl_l update_basket">
<span class="btn">Update</span>
</div>
</form>
</div>
<?php } else { ?>
<br />
<br />
<p><em>Your basket is currently empty.</em></p>
<?php } ?>
<?php require_once('_footer.php'); ?>
I have looked through some statckflow pages regarding this and have tried keydown and just using e.which and e.keyCode || e.which instead, but they all render the same issue of not working 100% of the time when you press enter key.
I understand some browsers may not support this, so is there a better approach for this operation? I have tested Firefox, Chrome and Safari (all latest).
Thanks for the help, appreciated! :)
Edit;
Here's the mod/basket_qty.php also...
<?php
require_once('../inc/autoload.php');
if (isset($_POST['qty']) && isset($_POST['id'])) {
$out = array();
$id = $_POST['id'];
$val = $_POST['qty'];
$objCatalogue = new Catalogue();
$product = $objCatalogue->getProduct($id);
if (!empty($product)) {
switch($val) {
case 0:
Session::removeItem($id);
break;
default:
Session::setItem($id, $val);
}
}
}
Looks like I needed to add e.preventDefault(); in the initBinds function for if (code == 13) { as pointed out by cmorrissey. It seems to be working fine with this. Thanks!!
Hi i am retrieving data from database using pagination which i am able to retrieve but i am facing problem that in my pagination next and last button is not working
here is my code
** index.php**
<script type="text/javascript">
function searchboxfun(numRecords, pageNum ) {
$.ajax({
type: "GET",
url: "usersearchboxresult.php?search=" + document.getElementById("UserSearchBox").value,
data: "show="+numRecords+"&pagenum="+pageNum,
cache: false,
beforeSend: function () {
$('#content').html('<img src="loader.gif" alt="" width="24" height="24" style=" padding-left:469px;">');
},
success: function(html) {
$("#RightPaneContainerDiv").html( html );
}
});
return false;
}
function changeDisplayRowCount(numRecords) {
searchboxfun(numRecords, 1);
}
$( document ).ready(function() {
searchboxfun(10, 1);
});
</script>
<form name="myForm" id="Myform" action="#" onsubmit="return searchboxfun(); ">
<input type="text" id="UserSearchBox" name="UserSearchBox" style="width: 95%; margin-top: 15px; margin-left: 2%;" placeholder="Search Box"/>
<div style="float: right; margin-right: 2%; margin-top: 0px;">
<input type="submit" name="Search" value="Search" id="search" onclick='searchboxfun();'>
</div>
</form>
usersearchboxresult.php
<?php
session_start();
?>
<head>
<style>
.hidden { display: none; }
</style>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script language="javascript" src="users.js" type="text/javascript"></script>
<script src="jquery.js"></script>
</head>
<?php
require_once("configure.php");
// Very important to set the page number first.
if (!(isset($_GET['pagenum']))) {
$pagenum = 1;
} else {
$pagenum = $_GET['pagenum'];
}
//Number of results displayed per page by default its 10.
$page_limit = ($_GET["show"] <> "" && is_numeric($_GET["show"]) ) ? $_GET["show"] : 10;
// Get the total number of rows in the table
//$sql = "SELECT * FROM tbl_pagination WHERE 1" ;
$search=$_GET['search'];
$eid=$_SESSION['eid'];
$sql="select * from clientreg where eid=$eid and (mobile like '%$search%' or fname like '%$search%' or service like '%$search%')";
//$select_table = "";
$cnt = mysql_num_rows( mysql_query($sql))or die("There is no record in Database!");
//Calculate the last page based on total number of rows and rows per page.
$last = ceil($cnt/$page_limit);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1) {
$pagenum = 1;
} elseif ($pagenum > $last) {
$pagenum = $last;
}
$lower_limit = ($pagenum - 1) * $page_limit;
$sql2 = $sql . " limit ". ($lower_limit)." , ". ($page_limit). " ";
$rs = mysql_query($sql2);
?>
<form name="frmUser" method="post" action="">
<div style="width:98%; margin-left:20px;">
<table border="0" cellpadding="10" cellspacing="1" width="100%" class="tblListForm">
<?php
$j=0;
$countleadmodified=array();
$countResult = 0;
while ( $row = mysql_fetch_array($rs) ) {
<tr>
<td><input type="checkbox" name="users[]" class="users" value="<?php echo $row["id"]; ?>" ></td>
<td>✰</td>
<td><?php echo $_SESSION['user'];?></td>
<td><?php echo $row["fname"];?></td>
<td><?php echo $row["lname"];?></td>
<td><?php echo $row["mobile"];?></td>
</tr>
<?php
$j++;
}
?>
</table>
</div>
</form>
<div id="paging">
<div class="height30"></div>
<table width="50%" border="0" cellspacing="0" cellpadding="2" align="center">
<tr>
<td valign="top" align="left">
<label> Rows Limit:
<select name="show" onChange="changeDisplayRowCount(this.value);">
<option value="10" <?php if ($_GET["show"] == 10 || $_GET["show"] == "" ) { echo ' selected="selected"'; } ?> >10</option>
<option value="20" <?php if ($_GET["show"] == 20) { echo ' selected="selected"'; } ?> >20</option>
<option value="30" <?php if ($_GET["show"] == 30) { echo ' selected="selected"'; } ?> >30</option>
</select>
</label>
</td>
<td valign="top" align="center" >
<?php
if ( ($pagenum-1) > 0) {
?>
First
Previous
<?php
}
//Show page links
for($i=1; $i<=$last; $i++) {
$j=1;
if ($i == $j) {
?>
<!--<a href="javascript:void(0);" class="selected" ><?php echo $i ?></a>-->
<?php
} else {
?>
<a href="javascript:void(0);" class="hidden" onclick="displayRecords('<?php echo $page_limit; ?>', '<?php echo $i; ?>');" ><?php echo $i ?></a>
<?php
}
$j++;}
if ( ($pagenum+1) <= $last) {
?>
Next
<?php } if ( ($pagenum) != $last) { ?>
<a href="javascript:void(0);" onclick="displayRecords('<?php echo $page_limit; ?>', '<?php echo $last; ?>');" class="links" >Last</a>
<?php
}
?>
</td>
<td align="right" valign="top">
Page <?php echo $pagenum; ?> of <?php echo $last; ?>
</td>
</tr>
</table>
</div>
here i this code i am able to retrive data from data base but any pagination is not working
where i am wrong how can i achieve my goal
Any help will be appreciated
On a page I have 8500 Employees shown in table data in the form of <tr> and <td>.
The Name of the Employees shown with a checkbox in front of each name of employee.
When I click on checkboxes the I insert the employees data (Employee Name and Employee Id) session.
Everything is working fine but the problem is when I click on check All checkbox then all the employees checkboxes are selected then there is a button named as "View Selected". On the click of this button I want to all the selected employees. When user click on this button a new child window will be opened with selected employee data in the form table row and data.
I am doing this but using session which I have created on the click of employees checkboxes.
Everything is working on Mozilla Firefox but when I check this of Google Chrome then it is not working and I am getting the browser message KillPages or Wait. The loader image of Chrome is shown but data is not loading.
My new child window page code is this where I am reading the session and running the for-each loop to print the data in the form of table data.
<?php require_once("../../includes/global.php");
$sessionName = rq('sessionName');
$employees = $session->read($sessionName);
?>
<script type="text/javascript" src="<?php echo SITEURL_PAGE; ?
>configuration/js/attendancePolicy.js"></script>
<div style="width: 100%;">
<?php if(strpos($sessionName, 'location') !== false) {?>
<h3 style="padding-left:10px;">View <?php echo LOCATION_DISPLAY_NAME?>s</h3>
<?php } else {?>
<h3 style="padding-left:10px;">View <?php echo
us(substr(str_replace('ot_','',$sessionName), 0, -3))?></h3>
<?php }?>
<?php
$totalEmployees = $session->check($sessionName) ? (int)count($session->read($sessionName)) : 0;
?>
<form id="updateEmployeesForm" name="updateEmployeesForm" method="post" action="saveAttendancePolicy.php">
<input type="hidden" name="hidAction" value="addNewPolicy_step3" />
<input type="hidden" name="sessionName" id="sessionName" value="<?php echo $sessionName?>" />
<?php
$styleTab = '';
$style='';
if($totalEmployees > 30){
$styleTab = 'border-bottom: none;';
$style = 'overflow:auto; height: 230px !important; border-bottom: 4px solid #2C90D3;';
}
//for over time policy only
$functionSuffix = '';
if($sessionName == 'ot_locations_cb' || $sessionName == 'ot_divisions_cb' || $sessionName == 'ot_departments_cb' || $sessionName == 'ot_employees_cb') {
$functionSuffix = 'overTimePolicy';
}
$where = rq('where');
$employeeLoadPage = ($sessionName == 'ot_employees_cb')?'otpolicy_ajax':'';
if(stripos($sessionName, 'employee') > -1) {
$js = "closeClildWindow('', 'employeeDiv', 'yes','".$employeeLoadPage."');";
} else if(stripos($sessionName, 'location') > -1) {
$js = "searchPolicySpecificNew('', 'locations', 'locationDiv', {'session':'yes'},'".$functionSuffix."'); updateChildPolicyNew('".$sessionName."', 'yes','".$functionSuffix."');";
} else if(stripos($sessionName, 'division') > -1) {
$js = "searchPolicySpecificNew('', 'divisions', 'divisionDiv', {'session':'yes'},'".$functionSuffix."'); updateChildDepartmentPolicyNew('".$sessionName."', 'locations_cb', 'yes','".$functionSuffix."');";
} else if(stripos($sessionName, 'department') > -1) {
$js = "searchPolicySpecificNew('', 'departments', 'departmentDiv', {'session':'yes'},'".$functionSuffix."'); updateChildjobTitlePolicy('".$sessionName."', 'divisions_cb', 'locations_cb', '','".$functionSuffix."');";
}
if($where == 'viewEmp') {
if($sessionName == 'ot_employees_cb') {
$js="getSelectedEmployeesNew('OT');";
} else {
$js="getSelectedEmployeesNew();";
}
}
?>
<div class="totalRecord" style="float:right; width:99%;text-align:right; margin-top: 5px;">
<label>Total Record(s) :<?php echo $totalEmployees ?></label>
</div>
<div style="margin: 0 2% 0 2%; width: 96%;" class="div_row">
<table cellpadding="0" border="0" cellspacing="0" width="100%" class="bdrtable" style="border-bottom: 0px;">
<thead>
<tr>
<th align="left" scope="col" colspan="5"> <input type="checkbox" name="viewCheckAllName" id="viewCheckAllName" <?php if($totalEmployees > 0) {?> checked="checked"<?php }?> class="class_parent_pop" onClick="sessionCheckBox('class_parent_pop', '<?php echo $sessionName?>_pop', 'parent', this);" />
Check All </th>
</tr>
</thead>
</table>
</div>
<div style="margin-bottom: 2%; margin-left: 2%; margin-right: 2%; width:96%;<?php echo $style;?>" class="div_row">
<table cellpadding="0" border="0" cellspacing="0" width="100%" class="bdrtable" style="<?php echo $styleTab?>">
<?php if($totalEmployees > 0) { ?>
<tr>
<?php $i=1;
foreach($employees as $key=>$employeeArr) {
?>
<td align="left" width="33%"><?php echo $i; ?> </td>
<?php
if($i%3 == 0 && $i != $totalEmployees) {
echo '</tr><tr>';
}
$i++;
}
if($totalEmployees%3 != 0) {
for ($x=($totalEmployees%3); $x < 3; $x++) {
echo '<td align="left" width="33%"> </td>';
}
}
?>
</tr>
<?php }else{ ?>
<tr>
<td colspan="3" align="center"><?php echo "No Data Found"; ?></td>
</tr>
<?php }?>
</table>
</div>
<div class="clear"></div>
<div class="div_row" style="text-align: right; width: 96%; margin:0 2%;">
<?php if($totalEmployees > 0) {?>
<input type="button" name="updateEmp" id="updateEmp" value="Update" class="submit" onClick="sessionCheckBoxPopupUpdate('<?php echo $sessionName?>_pop', '<?php echo $sessionName?>');<?php echo $js; ?>" />
<?php } ?>
<input type="button" name="cancel" id="cancel" value="Cancel" class="submit" onClick="javascript:window.close();" />
</div>
</form>
It may not be the foreach loop that is slow, 8500 is good number of data to load, you might want to page the results.
Why don't you try the same query using phpmyadmin and see the time taken.
previously i have posted one post about the cart page call shopcart.php but it seems that no one really can answer it. whenever i input new quantity and click change quantity button, it seems that the new amount cannot be got and the button has no action, (i really have tried really really hard to find the solution for three wks , uptil now still really cannot find a solution of where the problem is) hope everyone can give me a warm hand to find the problem for me or hints to me
<?php
error_reporting(0);
session_start();
header('Content-type: text/html; charset=utf-8');
include_once('../../xajax_core/xajax.inc.php'); // 引用 xajax
$xajax = new xajax(); // 建立 xajax 物件
// 註冊回應函式
$chaObj=$xajax->registerFunction('change_quantity');
$chaObj->useSingleQuote();
$chaObj->addParameter(XAJAX_FORM_VALUES,'form1');
$xajax->processRequest(); // 處理回應
$xajax->printJavascript();
//---------------------- 自訂函式區 ---------------------
// 負責更改商品數量的回應函式
function change_quantity($form) {
$objResponse = new xajaxResponse(); // 建立回應物件
// 表單中的 Checkbox 屬性為 p_id, 若有勾選, 其值才會傳入
// 所以檢查表單欄位中有 'p_id' 資料, 表示使用者有勾選產品
// 此時才做後續處理
if(isset($form['p_id'])) {
// 逐筆處理每一個被勾選的產品
foreach($form['p_id'] as $p_id) {
// 根據產品的訂購數量決定處理方式
if($form['qua'][$p_id]=='0') {
// 若訂購數量被設為 0, 則將此產品從購物車中移除
unset($_SESSION['cart'][$p_id]);
if(count($_SESSION['cart'])==0) { // 若購物車變成空的
$objResponse-> // 則關閉視窗
script('alert("cart has no items");window.close();');
unset($_SESSION['cart']);
}
else { // 若購物車中還有其它商品
// 將被刪除的產品從網頁中移除
$objResponse->remove($p_id);
// 更新購物車中的金額總計
$objResponse->assign('total','innerHTML',gettotal());
}
}
else if ($form['qua'][$p_id]>0) {
// 若設為大於 0 的值, 則將之設為購物車中的新數量
$_SESSION['cart'][$p_id]['quantity'] = $form['qua'][$p_id];
// 因已修改數量, 所以要更新購物車中的小計及總計金額
$objResponse->assign('sub[' . $p_id . ']', 'innerHTML',
$_SESSION['cart'][$p_id]['quantity'] *
$_SESSION['cart'][$p_id]['price']);
$objResponse->assign('total','innerHTML',gettotal());
}
else {
// 若被設為負值, 則將之回復原本的值
$objResponse->assign('qua[' . $pid . ']', 'innerHTML',
$_SESSION[$pid]['quantity']);
}
}
}
return $objResponse; // 傳回回應物件
} // 回應函式 change_quantity() 結束
// 計算總金額的函式
function getTotal() {
$total = 0;
foreach($_SESSION['cart'] as $p_id => $item)
$total += ($item['quantity'] * $item['price']);
return $total;
}
//---------------------- 購物車 HTML ---------------------
// 目前購物車中有商品, 程式才取出購物車內產品並顯示於網頁
if( !isset($_SESSION['cart']) ) { // 使用者尚未購物
echo "<script>alert(\"you haven't chosen any products\");" .
"window.close();</script>";
exit();
}
?>
<title>購物車內容</title>
<!-- -------------------- 用戶端 JavaScript ------------------ -->
<script type="text/javascript">
// 勾選或取消產品清單中所有產品 checkbox 的函式
function select_all(formName, elementName, selectAllName) {
elem = document.forms[formName].elements[elementName];
if(!elem) // 若找不到元素
return;
else if(elem.length!= null) // 若網頁列出多個產品 (elem 是陣列)
for(var i = 0; i < elem.length; i++)
elem[i].checked =
document.forms[formName].elements[selectAllName].checked;
else
elem.checked =
document.forms[formName].elements[selectAllName].checked;
}
// 將勾選的產品之訂購數量設為0, 再產生非同步要求
function settozero(formName, elementName) {
elem = document.forms[formName].elements[elementName];
if(!elem) // 若找不到元素
return;
else if(elem.length!= null) { // 若網頁列出多個產品 (elem 是陣列)
for(var i = 0; i < elem.length; i++)
if(elem[i].checked) {
var qua =
document.getElementById("qua[" + elem[i].value + "]");
var subtotal = document.getElementById("sub[" + elem[i].value + "]");
qua.value = 0; // 將數量設為 0
subtotal.value = 0;
}
}
else {
var qua = document.getElementById("qua[" + elem.value + "]");
var subtotal = document.getElementById("sub[" + elem.value + "]");
qua.value = 0; // 將數量設為 0
subtotal.value = 0;
}
var total_value = document.getElementById("total");
total_value.value = 0;
<?php $chaObj->printScript(); // 輸出呼叫回應函式的程式碼 ?>
}
</script>
<?php $xajax->printJavaScript('/'); ?>
<!-- ------------------- 購物車表單及表頭 ------------------- -->
<link rel="StyleSheet" type="text/css" href="../module.css" />
<form name="form1" id="form1" method="post" action="checkout.php">
<table width="800" border="0" align="center"
cellspacing="0" cellpadding="2"
style="text-align:center;border:1px solid silver">
<tr><th colspan="7">cart</th></tr>
<tr style="background-color:silver;color:white">
<td height="23" width="80">all
<!----- 呼叫函式選取或取消全部的 checkbox ----->
<input type="checkbox" name="all"
onClick="select_all('form1','p_id[]',this.name);">
</td>
<td height="23" width="460">product name</td>
<td height="23" width="60">unit price</td>
<td width="10" height="23"></td>
<td height="23" width="60">quantity</td>
<td width="10" height="23"></td>
<td width="70" height="23">subtotal</td>
</tr>
<!-- -------------------- 輸出購物車內容 -------------------- -->
<?php
// 呈現購物車表格內容
$total = 0;
foreach($_SESSION['cart'] as $p_id => $item) {
// 將此列的 id 屬性設為 $p_id, 以方便移除產品
echo "<tr id='$p_id'>\n";
echo "<td width='80' height='21'>" .
"<input type='checkbox' name='p_id[]' value='" .
$p_id . "'></td>\n";
echo "<td>" . $item['name'] . "</td>\n";
echo "<td width='60' >" . $item['price'] . "</td>\n";
echo "<td width='10' style='border-width:0'>×</td>\n";
echo "<td width='60'>" .
"<input type='text' name='qua[$p_id]' id='qua[$p_id]'
value='" . $item['quantity'] . "' size='3'></td>";
echo "<td width='10' style='border-width:0'>=</td>\n";
echo "<td width='70' align='right'>" ."<input type='text' size='6' id='sub[$p_id]' value='".($item['quantity'] * $item['price'])."' disabled>"."</td></tr>\n";
}
?>
<tr>
<td align="right" colspan="6">total:</td>
<td align="right" style="border-top:1px solid silver;width:70">
<input type="text" name="total" value="<?php echo gettotal(); // display total amount ?>" id="total">
</td>
</tr>
</table>
<!-- -------------------- cart button -------------------- -->
<table width="800" border="0" align="center">
<tr>
<td height="23" align="center">
<input type="button" name="DEL" value="remove products"
onClick="settozero('form1','p_id[]')">
</td>
<td height="23" align="center">
<input type="button" name="UPD" value="change quantity"
onClick="xajax_change_quantity(xajax.getFormValues('form1'))">
</td>
<td height="23" align="right">
<input type="button" name="CONT" value="continue shopping"
onClick="window.close();">
</td>
<td height="23" align="right">
<input type="button" name="CONT" value="checkout"
onClick="location.href='checkout.php';">
</td>
</tr>
</table>
</form>
isn't "innerHTML"... because tag id="total" is element form input,
correct is "value"
$objResponse->assign('total','innerHTML',gettotal());
correct...
$objResponse->assign('total','value',gettotal());
I have a form which contain an autocomplete from database and then when submitted by user it send the results to pdf and sending it to email.. but when I test it for one line it success but when add more lines the pdf give me the word "array" heres the codes.
the index.php
<?php require("login3.php"); ?>
<?php
if (!empty($_POST)) {
// Used for later to determine result
$success = $error = false;
// Object syntax looks better and is easier to use than arrays to me
$post = new stdClass;
// Usually there would be much more validation and filtering, but this
// will work for now.
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
// Check for blank fields
if (empty($post->itemCode) OR empty($post->itemDesc) OR empty($post->itemQty) OR empty($post->itemPrice) OR empty($post->itemAgent))
$error = true;
else {
// Get this directory, to include other files from
$dir = dirname(__FILE__);
// Get the contents of the pdf into a variable for later
ob_start();
require_once($dir.'/pdf.php');
$pdf_html = ob_get_contents();
ob_end_clean();
// Load the dompdf files
require_once($dir.'/dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF(); // Create new instance of dompdf
$dompdf->load_html($pdf_html); // Load the html
$dompdf->render(); // Parse the html, convert to PDF
$pdf_content = $dompdf->output(); // Put contents of pdf into variable for later
// Get the contents of the HTML email into a variable for later
ob_start();
require_once($dir.'/html.php');
$html_message = ob_get_contents();
ob_end_clean();
// Load the SwiftMailer files
require_once($dir.'/swift/swift_required.php');
$mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance of SwiftMailer
$message = Swift_Message::newInstance()
->setSubject('New Order') // Message subject
->setTo(array('hussammoz#aol.com', 'hussammoz#gmail.com' => 'Orange Pharmacy Store')) // Array of people to send to
->setFrom(array('no-reply#net.tutsplus.com' => 'Orange Pharmacy Order System')) // From:
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
- >attach(Swift_Attachment::newInstance($pdf_content, 'nettuts.pdf', 'application/pdf')); // Attach the generated PDF from earlier
// Send the email, and show user message
if ($mailer->send($message))
$success = true;
else
$error = true;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Orange Pharmacy Order System</title>
<style type="text/css" title="currentStyle">
#import "css/layout-styles.css";
#import "css/themes/smoothness/jquery-ui-1.8.4.custom.css";
</style>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<!-- jQuery libs -->
<script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.14.custom.min.js"></script>
<!-- Our jQuery Script to make everything work -->
<script type="text/javascript" src="js/jq-ac-script.js"></script>
</head>
<body>
<h1 align="center"><img src=418694_259331167468533_385322251_n.jpg></h1>
<div id="container">
<div class="panel">
<div class="title-large">
<div class="theme"></div>
</div>
<p>
<h1 align="center"><b>Branch : <FONT COLOR="ORANGE"><?php echo($_SESSION["username"]); ?> <h5 align="left"><font color="black">Date : </font></b><script type="text/javascript">
function GetClock(){
d = new Date();
nday = d.getDay();
nmonth = d.getMonth();
ndate = d.getDate();
nyear = d.getYear();
nhour = d.getHours();
nmin = d.getMinutes();
nsec = d.getSeconds();
if(nyear<1000) nyear=nyear+1900;
if(nhour == 0) {ap = " AM";nhour = 12;}
else if(nhour <= 11) {ap = " AM";}
else if(nhour == 12) {ap = " PM";}
else if(nhour >= 13) {ap = " PM";nhour -= 12;}
if(nmin <= 9) {nmin = "0" +nmin;}
if(nsec <= 9) {nsec = "0" +nsec;}
document.getElementById('clockbox').innerHTML=""+(nmonth+1)+"/"+ndate+"/"+nyear+" "+nhour+":"+nmin+":"+nsec+ap+"";
setTimeout("GetClock()", 1000);
}
window.onload=GetClock;
</script>
<?php if ($success) { ?>
<div class="message success">
<h4>Congratulations! It worked! Now check your email.</h4>
</div>
<?php } elseif ($error) { ?>
<div class="message error">
<h4>Sorry, an error occurred. Try again!</h4>
</div>
<?php } ?>
<div id="clockbox"></div></font></h5></h1>
<div class="content inpad">
<div id="messageBox" style="margin-left:15px; padding-left:20px; padding-bottom:5px; border:1px #ccc solid; display:none;"></div>
<form method="post" action="#" id="itemsForm">
<table id="itemsTable" class="general-table">
<thead>
<tr>
<th></th>
<th>Item Code</th>
<th>Item Description</th>
<th>Item Qty</th>
<th>Item Price</th>
<th>Item Agent</th>
</tr>
</thead>
<tbody>
<tr class="item-row">
<td></td>
<td><input name="itemCode" value="" class="tInput" id="itemCode" readonly="readonly" /> </td>
<td><input name="itemDesc" value="" class="tInput" id="itemDesc" tabindex="1"/></td>
<td><input name="itemQty" value="" class="tInput" id="itemQty" tabindex="2"/></td>
<td><input name="itemPrice" value="" class="tInput" id="itemPrice" readonly="readonly" /> </td>
<td><input name="itemAgent" value="" class="tInput" id="itemAgent" readonly="readonly" /></td>
</tr>
</tbody>
</table>
<span> <img src="images/icon-plus.png" alt="Add" title="Add Row" /> Add Item</span>
</div>
<input type="submit" value="submit">
</form>
</div>
</div>
</body>
</html>
and the output html code is
<html>
<head>
<br><br>
<h1 align="center"><img src=http://orangepharmacy.hostzi.com/418694_259331167468533_385322251_n.jpg></h1>
<style type="text/css" title="currentStyle">
#import "http://orangepharmacy.hostzi.com/css/layout-styles.css";
#import "http://orangepharmacy.hostzi.com/css/themes/smoothness/jquery-ui- 1.8.4.custom.css";
</style>
</head>
<body>
<br><br>
<h1 align="center"><b>Items Order <br> Branch : <FONT COLOR="ORANGE">
<?php echo($_SESSION["username"]); ?></h1>
<br><br>
<table id="itemsTable" class="general-table">
<thead>
<tr>
<th></th>
<th>Item Code</th>
<th>Item Description</th>
<th>Item Qty</th>
<th>Item Price</th>
<th>Item Agent</th>
</tr>
</thead>
<tbody>
<tr class="item-row">
<td></td>
<td><?php echo $post->itemCode; ?></td>
<td><?php echo $post->itemDesc; ?></td>
<td><?php echo $post->itemQty; ?></td>
<td><?php echo $post->itemPrice; ?></td>
<td><?php echo $post->itemAgent; ?></td>
</tr>
</tbody>
</table>
<br><br><l><p><b><i><h2 align="left">Prepared by : ............................ </h2><h2 align="right"> Signeture : .................................<h2></b></i></p>
</body>
</html>
the js code for add new line:
$(document).ready(function(){
// Use the .autocomplete() method to compile the list based on input from user
$('#itemDesc').autocomplete({
source: 'data/item-data.php',
minLength: 1,
select: function(event, ui) {
var $itemrow = $(this).closest('tr');
// Populate the input fields from the returned values
$itemrow.find('#itemCode').val(ui.item.itemCode);
$itemrow.find('#itemDesc').val(ui.item.itemDesc);
$itemrow.find('#itemPrice').val(ui.item.itemPrice);
$itemrow.find('#itemAgent').val(ui.item.itemAgent);
// Give focus to the next input field to recieve input from user
$('#itemQty').focus();
return false;
}
// Format the list menu output of the autocomplete
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.itemDesc + "</a>" )
.appendTo( ul );
};
// Get the table object to use for adding a row at the end of the table
var $itemsTable = $('#itemsTable');
// Create an Array to for the table row. ** Just to make things a bit easier to read.
var rowTemp = [
'<tr class="item-row">',
'<td><a id="deleteRow"><img src="images/icon-minus.png" alt="Remove Item" title="Remove Item"></a></td>',
'<td><input name="itemCode" class="tInput" value="" id="itemCode" readonly="readonly" /> </td>',
'<td><input name="itemDesc" class="tInput" value="" id="itemDesc" /></td>',
'<td><input name="itemQty" class="tInput" value="" id="itemQty" /></td>',
'<td><input name="itemPrice" class="tInput" value="" id="itemPrice" readonly="readonly" /></td>',
'<td><input name="itemAgent" class="tInput" value="" id="itemAgent" readonly="readonly" /></td>',
'</tr>'
].join('');
// Add row to list and allow user to use autocomplete to find items.
$("#addRow").bind('click',function(){
var $row = $(rowTemp);
// save reference to inputs within row
var $itemCode = $row.find('#itemCode');
var $itemDesc = $row.find('#itemDesc');
var $itemPrice = $row.find('#itemPrice');
var $itemQty = $row.find('#itemQty');
var $itemAgent = $row.find('#itemAgent');
if ( $('#itemDesc:last').val() !== '' ) {
// apply autocomplete widget to newly created row
$row.find('#itemDesc').autocomplete({
source: 'data/item-data.php',
minLength: 1,
select: function(event, ui) {
$itemCode.val(ui.item.itemCode);
$itemDesc.val(ui.item.itemDesc);
$itemPrice.val(ui.item.itemPrice);
$itemAgent.val(ui.item.itemAgent);
// Give focus to the next input field to recieve input from user
$itemQty.focus();
return false;
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.itemDesc + "</a>" )
.appendTo( ul );
};
// Add row after the first row in table
$('.item-row:last', $itemsTable).after($row);
$($itemDesc).focus();
} // End if last itemCode input is empty
return false;
});
$('#itemDesc').focus(function(){
window.onbeforeunload = function(){ return "You haven't saved your Order. Are you sure you want to leave this page without saving first?"; };
});
}); // End DOM
// Remove row when clicked
$("#deleteRow").live('click',function(){
$(this).parents('.item-row').remove();
// Hide delete Icon if we only have one row in the list.
if ($(".item-row").length < 2) $("#deleteRow").hide();
});
the problem is in
<td><?php echo $post->itemCode; ?></td>
<td><?php echo $post->itemDesc; ?></td>
<td><?php echo $post->itemQty; ?></td>
<td><?php echo $post->itemPrice; ?></td>
<td><?php echo $post->itemAgent; ?></td>
when passing one row it read the data but when passing more than one row it return the name "array"!
I try to do this but it give me : Invalid argument supplied for foreach()
<td><?php foreach ($post->itemCode as $code) {
echo $code;
}
?>
</td>
<td><?php foreach ($post->itemDesc as $desc) {
echo $desc;
}
?></td>
<td><?php foreach ($post->itemQty as $qty) {
echo $qty;
}
?></td>
<td><?php foreach ($post->itemPrice as $price) {
echo $price;
}
?></td>
<td><?php foreach ($post->itemAgent as $agent) {
echo $agent;
}
?></td>
You can't echo an array - you have to iterate over it and echo each value, eg
foreach ($post->itemCode as $thing) {
echo $thing;
}
If you're not sure about the structure of your array, you can always just print_r($post->itemCode) etc., and that will show you what's in it.
If you want to access the first member of the array, try
$itemCode = $post->itemCode; echo $itemCode[0];