Jump to content

Dynamic div ID's


ohno

Recommended Posts

Please go gentle as I'm no coder (& finding someone to do these small things seems next to impossible). I have this JS code which is updating a div :-

 

<script> 
$(document).ready(function(){
setInterval(function(){
	  $("#order-no").load(window.location.href + " #order-no" );
	  $("#date").load(window.location.href + " #date" );
	  $("#ip").load(window.location.href + " #ip" );
	  $("#country").load(window.location.href + " #country" );
	  $("#payment-type").load(window.location.href + " #payment-type" );	
      $("#progress").load(window.location.href + " #progress" );
	  $("#delivery-options").load(window.location.href + " #delivery-options" );
	  $("#cart-locked").load(window.location.href + " #cart-locked" );
	  $("#total-price").load(window.location.href + " #total-price" );
	  
}, 3000);
});
</script>

 & in my PHP each div has an ID, eg :-

 

<div id="order-no">'.$row['orderno'].'</div>

All working fine. However the PHP page in question can have multiple orders on it so each div needs to be unique. I can do that easily on the PHP side, eg :-

 

<div id="'.$row['orderno'].'-order-no">'.$row['orderno'].'</div>

 

So now the order no div becomes the "order ID-order-no".

 

But how to I then get this info into the JS? I found some info elsewhere which seems to suggest it's possible but it's well over the top of my head :(

 

Any help would be MUCH appreciated. Thanks

Link to comment
Share on other sites

So in the PHP we would have <div id=123order-no</div><div id=456order-no</div><div id=789-orderno</div> etc, I'm not understanding what would be required in the JS, sorry. The example looks along the lines of what I need but I've no idea how to tie it in with the existing JS, any help would be much appreciated!

 

Link to comment
Share on other sites

Hmm.

<script> 
$(document).ready(function(){
setInterval(function(){
	  $("#order-no").load(window.location.href + " #order-no" );
	  $("#date").load(window.location.href + " #date" );
	  $("#ip").load(window.location.href + " #ip" );
	  $("#country").load(window.location.href + " #country" );
	  $("#payment-type").load(window.location.href + " #payment-type" );	
      $("#progress").load(window.location.href + " #progress" );
	  $("#delivery-options").load(window.location.href + " #delivery-options" );
	  $("#cart-locked").load(window.location.href + " #cart-locked" );
	  $("#total-price").load(window.location.href + " #total-price" );
	  
}, 3000);
});
</script>

What you're doing here is requesting the page you're currently on from the server 9 times every 3 seconds. What's worse, you get the entire page every single time, and then jQuery will disregard everything except for whatever tiny portion of it you wanted to keep. The whole process is incredibly wasteful.

If you're going to do this, do it right: use AJAX and JSON to get (1) all of the data (2) at the same time (3) without tons of wasted bytes. You make/update your PHP script so that it is capable of returning a JSON object with the order number, date, IP, blah blah blah, keeping in mind that you only need to return data that may actually change. Then use your setInterval to get that data, pull out the bits of it, and update the elements on the page.

 

For those elements, please don't construct complicated IDs that force you to do starts-with/ends-with-type matching. It's just so much of a hassle.

Put a particular ID on a container element, then use classes or data attributes on the individual elements inside it.

<div id="order-123">
	<span data-field="order-no">...</span>
$("#order-" + ordernumber).find("[data-field]").each(function() {
	var field = $(this).attr("data-field");
	$(this).text(orderdata[field]);
});

 

Link to comment
Share on other sites

I found this guide :-

https://kodesmart.com/kode/working-with-json-jquery-php-and-mysql/

I made some test files, test.php :-

 

<?php
session_start();
include_once("configio.php");



	//MSG
	$sql = "SELECT * FROM carts  LIMIT 20";
				$result = $mysqli->query($sql);
	//Add all records to an array
	$rows = array();
	while($row = $result->fetch_array()){
		$rows[] = $row;
	}
	//Return result to jTable
	$qryResult = array();
	$qryResult['logs'] = $rows;
	echo json_encode($qryResult);

	
?>

& test2.php :-

 

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
<title>Test Page</title>
<script> 
$(document).ready(function(){
	var formhtml =  "logreq=1";
	var postURL= "test.php";
	$.ajax({
		type: "POST",
		url: postURL,
		data: formhtml,
		success: function(html){
			var output= "<table><tbody><thead><th>cartid</th><th>orderno</th><th>Date</th><th>Browser</th></thead>";
			var logsData = $.parseJSON(html);
			for (var i in logsData.logs){
				output+="<tr><td>" + logsData.logs[i].cartid + "</td><td>" + logsData.logs[i].orderno + "</td><td>" + logsData.logs[i].datestarted+ "</td><td>" + logsData.logs[i].browser+"</td></tr>";
			}
			$("#log_container").html(output);
		},
		error: function (html) {
			alert("Oops...Something went terribly wrong");
		}
	});
});
</script>
</head>
<body>
	<div id="log_container">

	</div>
</body>
</html>

 

Which gives me a screen that looks like the example.

But I haven't got a clue how this would be implemented in my scenario!

Screenshot_2020-03-10 Test Page.png

Link to comment
Share on other sites

What are you actually trying to accomplish?  Your original code makes it look like you're essentially just trying to refresh the current page, but doing it in pieces instead of all at once.  Is there a reason you want to do it that way rather than just reload the page on a timer, such as:

jQuery(function(){
	//Reload the page in 3 seconds
	setTimeout(function(){
		location.reload();
	}, 3000);
});

You need to explain what your end-goal is better so that you can receive a real solution to whatever the problem is.

 

Link to comment
Share on other sites

Hi, yes, the page consists of a table where a user can run another script, eg, to change the carts shipping option. If the whole page refreshes the scripts do not always run. Hence I just wanted to update certain elements that report on the carts progress in the checkout flow. Hope this makes sense?

 

Screenshot_2020-03-10 BT to RJ45 COM.png

Edited by ohno
Link to comment
Share on other sites

With my original code :-

$(document).ready(function(){
setInterval(function(){
      $("#progress").load(window.location.href + " #progress" );
    
      
}, 3000);
});
</script>

I can get the first part to work , so after the refresh the page updates but obviously it is finding all divs that contain "progress" & then displaying it again (hope this makes sense, I've confused myself big time here!). What I think I need is this :-

$("#progress-ID123").load(window.location.href + " #progress-ID123" ); < Is it even possible to link these two parts together via the ID123 part? If yes what code is required?!

So in the PHP each div contains "progress" with a unique ID tagged on so progressID123 in my example.  I then want a script that will refresh each of those divs every 10 seconds. I know the post above says do this properly but if there is just a simple way (NOT a whole page refresh though) that will do at the moment.

 

If anyone can help it would be great. Thanks

 

 

Screenshot_2020-03-11 BT to RJ45 COM.png

Link to comment
Share on other sites

On 3/10/2020 at 3:49 PM, ohno said:

Hope this makes sense?

Not really.  I still don't see any reason why what you're trying to do would be any different that just reloading the entire page.

In any event, if you do want to update just some areas the proper way, as mentioned, is to have your PHP generate the data as a JSON structure and then have your javascript take that and update all the relevant fields.  Using .load with fragment identifiers is extremely wasteful and will put a lot of unnecessary burden on your server, potentially leading to issues.

You already posted an example of using JSON, so it seems you have figured at least part of it out.  What you'd do is just update your success: handler function to do what you need once the json data is received, for example to update the order number you might do:

success: function(data){
	$('#order-no').text(data.orderNo);
}

In your PHP code, make sure you output an appropriate content type before the json.  Then it will be parsed automatically by jQuery and provided to your callback rather than you having to parse it yourself.

header('Content-type: application/json');
echo json_encode($qryResult);
exit;

 

Link to comment
Share on other sites

Maybe this will help, this is the orders.php file.

 

"All"(!) I wish to do is update the table fields Order Number, Payment Type, Current Progress, Viewing Delivery Options?, Cart Locked & Total. As I said if I refresh the whole page the scripts that  send email etc stop working during a refresh, & as I wanted this to update quickly (so every few seconds) it basically breaks the page.

 

<?php
session_start();
include_once("configio.php");
include_once("top.php");
// **** Country detection via IP code start ****
include_once("../../ip_files/countries.php");

function iptocountry($ip) {
    $numbers = preg_split( "/\./", $ip);
    include("../../ip_files/".$numbers[0].".php");
    $code=($numbers[0] * 16777216) + ($numbers[1] * 65536) + ($numbers[2] * 256) + ($numbers[3]);
    foreach($ranges as $key => $value){
        if($key<=$code){
            if($ranges[$key][0]>=$code){$two_letter_country_code=$ranges[$key][1];break;}
            }
    }
    if ($two_letter_country_code==""){$two_letter_country_code="UNKNOWN";}
    return $two_letter_country_code;
}
// **** Country detection via IP code end ****
if ( (!isset($_SESSION['aloggedin'])) || ($_SESSION['aloggedin'] != 1) )
	{
		include_once("login.php");
	}
else
	{
		echo '
		<h1>Orders Area - '.$companyname.' Shopping Cart System</h1>
		
		<table width="500" border="0">
  <tr>
    <td><form method="post" action="s_findorder.php" target="_blank">
			Order ID<br />
			<input type="text" name="orderno" />
			<input type="submit" name="submit" value="Search" />
		</form></td>
    <td><form method="post" action="findorderresults.php" target="_blank">
			IP Address or E-mail Address<br />
			<input type="text" name="searchterm" />
			<input type="submit" name="submit" value="Search" />
		</form></td>
  </tr>
</table>
		';
		$sql = "SELECT COUNT(cartid) FROM carts";
		$result = $mysqli->query($sql);
		while ( $row = @$result->fetch_array(MYSQLI_BOTH) )
			{
				$numorders = $row[0];
			}
		if ( $numorders == 0 )
			{
				echo "There are no orders in the system.";
			}
		else
			{
				$sql = "SELECT orderno, datestarted, ipaddress, progress, locked, deloptions, total, cartid, invoiced, invoiceid, email, deliveryoption, trackingno, card FROM carts WHERE archived='0' ORDER BY cartid DESC";
				$result = $mysqli->query($sql);
				echo '	
				
				
				<table border="1">
				
					<tr align="center">
						<td class="tableheader">Order<br />Number</td>
						<td class="tableheader">Date &amp; Time Started</td>
						<td class="tableheader">IP Address</td>
						<td class="tableheader">Country</td>
						<td class="tableheader">Email Address</td>
						<td class="tableheader">Save</td>
						<td class="tableheader">Payment Type</td>
						<td class="tableheader">Current Progress</td>
						<td class="tableheader">Viewing Delivery Options?</td>
						<td class="tableheader">Cart Locked</td>											
						<td class="tableheader">Total</td>
						<td class="tableheader">Archive</td>
						<td class="tableheader">More...</td>
						<td class="tableheader">E-mail<br />Info</td>
						<td class="tableheader">Confirm<br />PP</td>
						<td class="tableheader">Confirm<br />Card</td>
						<td class="tableheader">Confirm<br />Bank</td>
						<td class="tableheader">Clear<br />Confirm</td>
						<td class="tableheader">Create<br />Invoice</td>
					</tr>
				';
				while ( $row = @$result->fetch_array(MYSQLI_BOTH) )
					{
						// **** Country detection via IP code start ****
						$two_letter_country_code=iptocountry($row['ipaddress']);
						$three_letter_country_code=$countries[ $two_letter_country_code][0];
						$country_name=$countries[$two_letter_country_code][1];	
						// To display flag
						$file_to_check="../../flags/$two_letter_country_code.gif";
						if (file_exists($file_to_check)){
						$flag = "<img src=$file_to_check width=30 height=15><br>";
						}else{
						$flag = "<img src=../../flags/noflag.gif width=30 height=15><br>";
						}
						//End flag
						// **** Country detection via IP code end ****
						$year = substr($row['datestarted'], 0, 4);
						$month = substr($row['datestarted'], 5, 2);
						$day = substr($row['datestarted'], 8, 2);
						$hour = substr($row['datestarted'], 11, 2);
						$min = substr($row['datestarted'], 14, 2);
						$sec = substr($row['datestarted'], 17, 2);
						
						$rowbackground = '';
						if ( $row['deliveryoption'] != '0' )
							{
								$rowbackground = ' style="background-color: #00FFFF;"';
							}
						
						$date = $day.'/'.$month.'/'.$year.' '.$hour.':'.$min.':'.$sec;
						echo '
						<tr align="center"'.$rowbackground.'>
							<td>'.$row['orderno'].'</td>
							<td>'.$date.'</td>
							<td>'.$row['ipaddress'].'</td>
							<td>'.$flag.''.$country_name.'</td>
							<form method="post" action="s_updateorderemail.php"><td><input type="text" name="email" value="'.$row['email'].'" /></td><td><input type="submit" name="submit" value="Save" /></td><input type="hidden" name="cartid" value="'.$row['cartid'].'" /></form>
							<td align="center">
							<div class="payment-type" id="'.$row['cartid'].'">
							
							
						';
						if ( $row['card'] == '31' )
							{
								echo '<img src="https://www.site.com/images/visa.png" height="47" width="75" alt="Paid via Visa Card" />';
							}
						elseif ( $row['card'] == '32' )
							{
								echo '<img src="https://www.site.com/images/mastercard.png" height="47" width="75" alt="Paid via MasterCard" />';
							}
						elseif ( $row['card'] == '33' )
							{
								echo '<img src="https://www.site.com/images/amex.gif" height="47" width="74" alt="Paid via Amex Card" />';
							}
						elseif ( $row['card'] == '34' )
							{
								echo '<img src="https://www.site.com/images/maestro.png" height="47" width="75" alt="Paid via Maestro Card" />';
							}
						elseif ( $row['card'] == '35' )
							{
								echo '<img src="https://www.site.com/images/solo.gif" height="47" width="77" alt="Paid via Solo Card" />';
							}
						elseif ( $row['card'] == '36' )
							{
								echo '<img src="https://www.site.com/images/discover.gif" height="47" width="74" alt="Paid via Discover Card" />';
							}
						elseif ( $row['progress'] == '1' )
							{
								echo '<img src="https://www.site.com/images/pp.gif" height="26" width="100" alt="Paid via PayPal" />';
							}
						elseif ( $row['progress'] == '2' )
							{
								echo '<img src="https://www.site.com/images/pp.gif" height="26" width="100" alt="Paid via PayPal" />';
							}
						elseif ( $row['progress'] == '6' )
							{
								echo '<img src="https://www.site.com/images/pp.gif" height="26" width="100" alt="Paid via PayPal" />';
							}
						elseif ( $row['progress'] == '38' )
							{
								echo '<img src="https://www.site.com/images/banktransferinvoice.png" height="46" width="70" alt="Paid via Bank Transfer" />';
							}	
						elseif ( ($row['card'] == '0' ) && ($row['progress'] == '14' || $row['progress'] == '21' || $row['progress'] == '23' || $row['progress'] == '25') )
							{
								echo '<img src="https://www.site.com/images/paidbycard.gif" height="43" width="43" alt="Paid via Card" />';
							}
						else
							{
								echo '';
							}
						echo'
						</div>
						<td align="center">
						<div id="progress">
						';
						if ( $row['progress'] == '1' )
							{
								echo 'PayPal Failed';
							}
						elseif ( $row['progress'] == '2' )
							{
								echo 'PayPal Success';
							}
						elseif ( $row['progress'] == '3' && $row['locked'] == '0')
							{
								echo 'Delivery Options';
							}
						elseif ( $row['progress'] == '3' && $row['locked'] == '1')
							{
								echo 'Delivery Options-Locked';
							}	
						elseif ( $row['progress'] == '4' )
							{
								echo 'Checkout Selected';
							}
						elseif ( $row['progress'] == '5' )
							{
								echo 'Payment Gateway';
							}
						elseif ( $row['progress'] == '6' )
							{
								echo 'Sent to PayPal';
							}
						elseif ( $row['progress'] == '7' )
							{
								echo 'Sent to GoogleCheckout';
							}
						elseif ( $row['progress'] == '8' )
							{
								echo 'Nochex Success';
							}
						elseif ( $row['progress'] == '9' )
							{
								echo 'Nochex Failed';
							}
						elseif ( $row['progress'] == '10' )
							{
								echo 'Sent to Nochex';
							}
						elseif ( $row['progress'] == '11' )
							{
								echo 'Sent to PP Pro';
							}
						elseif ( $row['progress'] == '12' )
							{
								echo 'Processing PP Pro';
							}
						elseif ( $row['progress'] == '13' )
							{
								echo 'PP Pro Failure';
							}
						elseif ( $row['progress'] == '14' )
							{
								echo 'PP Pro Success';
							}
						elseif ( $row['progress'] == '15' )
							{
								echo '3Ds iframe Page';
							}
						elseif ( $row['progress'] == '16' )
							{
								echo 'Sent to Pro Hosted';
							}
						elseif ( $row['progress'] == '17' )
							{
								echo 'iFrame Address Page';
							}
						elseif ( $row['progress'] == '18' )
							{
								echo 'PP Pro Card Selection';
							}
						elseif ( $row['progress'] == '19' )
							{
								echo 'iFrame Payment Page';
							}
						elseif ( $row['progress'] == '20' )
							{
								echo 'PP Pro 3Ds Page';
							}
						elseif ( $row['progress'] == '21' )
							{
								echo 'Pro Hosted Success';
							}
						elseif ( $row['progress'] == '22' )
							{
								echo 'Pro Hosted Failed';
							}
						elseif ( $row['progress'] == '23' )
							{
								echo 'PP iFrame Success';
							}
						elseif ( $row['progress'] == '24' )
							{
								echo 'PP iFrame Failed';
							}
						elseif ( $row['progress'] == '25' )
							{
								echo 'PP Pro Success';
							}
						elseif ( $row['progress'] == '26' )
							{
								echo 'PP Pro Failed';
							}
						elseif ( $row['progress'] == '27' )
							{
								echo 'PP Pro Address Page';
							}
						elseif ( $row['progress'] == '31' )
							{
								echo 'PP Pro Address Page - Visa';
							}
						elseif ( $row['progress'] == '32' )
							{
								echo 'PP Pro Address Page - MasterCard';
							}
						elseif ( $row['progress'] == '33' )
							{
								echo 'PP Pro Address Page - Amex';
							}
						elseif ( $row['progress'] == '34' )
							{
								echo 'PP Pro Address Page - Maestro';
							}
						elseif ( $row['progress'] == '35' )
							{
								echo 'PP Pro Address Page - Solo';
							}
						elseif ( $row['progress'] == '36' )
							{
								echo 'PP Pro Address Page - Discover';
							}
						elseif ( $row['progress'] == '37' )
							{
								echo 'Cart Unlocked';
							}
						elseif ( $row['progress'] == '38' )
							{
								echo 'BANK TRANSFER';
							}
						else
							{
								echo 'Active';
							}
						echo'
							</td>
							<td align="center">
						';
						if ( $row['deloptions'] == '1' ) 
						{	
						echo '<img src="images/invoicesent.png" alt="Viewing Del Options" border="none" />
						<td align="center">
						';
						}
						else
						{	
						echo '<img src="images/invoicenotsent.png" alt="Not Viewing Del Options" border="none" />
						<td align="center">
						';
						}	
						if ( $row['locked'] == '1' ) 
						{	
						echo '<a href="s_unlockcart.php?id='.$row['cartid'].'"><img src="images/invoicesent.png" alt="Cart Locked" border="none" />
						';
						}
						else
						{	
						echo '<img src="images/invoicenotsent.png" alt="Cart Not Locked" border="none" />
						';
						}		
						echo'
							</td>							
							<td><div id="total-price">&pound;'.$row['total'].'</td>							
							<td><a href="s_archiveorder.php?id='.$row['cartid'].'"><img src="images/archive.png" alt="Archive Order Info" border="none" /></a></td>
							';
								echo'
							<td><a href="';
								echo "javascript: window.open('order.php?id=".$row['cartid']."','','status=yes, width=700,height=800,scrollbars=1'); void('');";
								echo '"><img src="images/more_button.gif" alt="More Order Info" border="none" /></a></td>
							<td align="center"><a href="s_emailorderinfo.php?id='.$row['cartid'].'"><img src="images/email.gif" alt="E-mail Order Info" border="none" /></a></td>
							<td align="center"><a href="s_confirmpp.php?id='.$row['cartid'].'"><img src="images/paypal.gif" alt="Confirm PayPal Payment" border="none" /></a></td>
							<td align="center"><a href="s_confirmpppp.php?id='.$row['cartid'].'"><img src="images/cards.gif" alt="Confirm Pay Pal Pro Payment" border="none" /></a></td>
							<td align="center"><a href="s_confirmbk.php?id='.$row['cartid'].'"><img src="images/banktransfersmall.png" alt="Confirm Bank Payment" border="none" /></a></td>
							<td align="center"><a href="s_clearconfirm.php?id='.$row['cartid'].'"><img src="images/removeconfirmpayment.png" alt="Remove Confirm Payment" border="none" /></a></td>
							<td align="center"><a href="s_createinvoice.php?id='.$row['cartid'].'"><img src="images/invoice.gif" alt="Create Invoice" border="none" /></a></td>
						</tr>
								';
							}
				echo '
				</table>	
								';
			}
	}
include_once("bottomio.php");
?>

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.