Link to home
Start Free TrialLog in
Avatar of Geektank
GeektankFlag for Afghanistan

asked on

JavaScript form onload looping

I need a script to load to submit a form on a php page only once.

I've tried all which ways however the page gets caught in a loop.
Avatar of leakim971
leakim971
Flag of Guadeloupe image

set a cookie the first time and before submit check if the cookie exist
you may check with the server if the cookie exist also :
https://www.experts-exchange.com/questions/28102799/Check-if-cookie-exists-set-cookie-if-not.html
Avatar of Geektank

ASKER

Is this the only way?
Or you can add a hidden form field on the second return of the HTML--i.e. first time page sent:  no hidden field; second time page sent:  hidden field.

You could also set a flag in the Session the first time the page is sent. Then, if the user sends it a second time, you check the session:  if the flag is there, then don't process the submission.
if you put the same code in the same page and loop over and over it will execute the same way until you save somewhere an information.
you can store :
- a cookie,
- session variable (similar to a cookie server side)
- localstorage (html5)
- url variable : http://www.yourdomaine.com/index.php?done=1 (or use a # instead ?)

storing in a javascript variable is a non sense as you're reloading the page (back to my first sentence)
Can we see some code.
Ok see below...

 
<?php include('header.php'); ?>

	<input type="text" name="user_id" id="user_id" value="<?php
// if you need the user's information, just put them into the $_SESSION variable and output them here
echo "". $_SESSION['user_id'] . "";
?>">

	<link rel="stylesheet" type="text/css" href="tables/media/css/jquery.dataTables.css">
	<link rel="stylesheet" type="text/css" href="tables/resources/syntax/shCore.css">
	<link rel="stylesheet" type="text/css" href="tables/media/css/dataTables.tableTools.css">
	<link rel="stylesheet" type="text/css" href="tables/media/css/dataTables.colVis.css">
	<link rel="stylesheet" type="text/css" href="tables/resources/demo.css">


	<style type="text/css" class="init">

	th, td { white-space: nowrap; }
	div.dataTables_wrapper {
		width: 1000px;
		margin: 0 auto;
	}

	</style>

<div class="container">

<body class="dt-example">

<div class="visible-xs visible-sm visible-md"><br></div>
	<button class="btn btn-primary" id="btn1">Get Scores</button>
	

<?php


if( $_SERVER['REQUEST_METHOD'] == 'POST') {

	if(isset($_POST['id'])){
			$id = $_POST['id'];
						$con=mysqli_connect("NOT SHOWING YOU THAT");
			// Check connection
			if (mysqli_connect_errno())
			  {
			  echo "Failed to connect to MySQL: " . mysqli_connect_error();
			  }

echo "<hr><div class='clear'></div>";
echo "<h3>HISTORY</h3>";

			$result = mysqli_query($con,"
SELECT  b.contract_pk, b.contract_name, c.subcontractor_name, `score_pk`, `score_date`, 
REPLACE(REPLACE(score_pk,100,'N/R'), 90,'N/A') as score_pk,
REPLACE(REPLACE(score_date,100,'N/R'), 90,'N/A') as score_date,
REPLACE(REPLACE(score_timelydelivery,100,'N/R'), 90,'N/A') as score_timelydelivery,
REPLACE(REPLACE(score_GoodAttitudeDisplayed,100,'N/R'), 90,'N/A') as score_GoodAttitudeDisplayed,
REPLACE(REPLACE(score_ProgrammePerformance,100,'N/R'), 90,'N/A') as score_ProgrammePerformance,
REPLACE(REPLACE(score_FinishedProduct,100,'N/R'), 90,'N/A') as score_FinishedProduct,
REPLACE(REPLACE(score_TidyWorkingArea,100,'N/R'), 90,'N/A') as score_TidyWorkingArea,
REPLACE(REPLACE(score_MaterialsProtected,100,'N/R'), 90,'N/A') as score_MaterialsProtected,
REPLACE(REPLACE(score_RiskAssessments,100,'N/R'), 90,'N/A') as score_RiskAssessments,
REPLACE(REPLACE(score_GoodHousekeeping,100,'N/R'), 90,'N/A') as score_GoodHousekeeping,
REPLACE(REPLACE(score_SigningIn,100,'N/R'), 90,'N/A') as score_SigningIn,
REPLACE(REPLACE(score_PPE,100,'N/R'), 90,'N/A') as score_PPE,
REPLACE(REPLACE(score_FuelStorageUse,100,'N/R'), 90,'N/A') as score_FuelStorageUse,
REPLACE(REPLACE(score_WasteManagement,100,'N/R'), 90,'N/A') as score_WasteManagement,
REPLACE(REPLACE(score_PollutionPrevention,100,'N/R'), 90,'N/A') as score_PollutionPrevention,
REPLACE(REPLACE(score_contract_fk,100,'N/R'), 90,'N/A') as score_contract_fk,
REPLACE(REPLACE(score_subcontractor_fk,100,'N/R'), 90,'N/A') as score_subcontractor_fk,
REPLACE(REPLACE(score_presenceofsupervisor,100,'N/R'), 90,'N/A') as score_presenceofsupervisor,
REPLACE(REPLACE(score_comments,100,'N/R'), 90,'N/A') as score_comments,
`score_contract_fk`, `score_subcontractor_fk`, `score_comments`, `score_user_id_fk` , d.user_id, d.user_name,
 
 
            Round(( case when `score_timelydelivery` in ( 100, 90 ) then 0 else `score_timelydelivery` end
            + case when `score_GoodAttitudeDisplayed` in ( 100, 90 ) then 0 else `score_GoodAttitudeDisplayed` end
                        + case when `score_ProgrammePerformance` in ( 100, 90 ) then 0 else `score_ProgrammePerformance` end
                        + case when `score_FinishedProduct` in ( 100, 90 ) then 0 else `score_FinishedProduct` end
                        + case when `score_TidyWorkingArea` in ( 100, 90 ) then 0 else `score_TidyWorkingArea` end
                        + case when `score_MaterialsProtected` in ( 100, 90 ) then 0 else `score_MaterialsProtected` end
                        + case when `score_RiskAssessments` in ( 100, 90 ) then 0 else `score_RiskAssessments` end
                        + case when `score_GoodHousekeeping` in ( 100, 90 ) then 0 else `score_GoodHousekeeping` end
                        + case when `score_SigningIn` in ( 100, 90 ) then 0 else `score_SigningIn` end
                        + case when `score_PPE` in ( 100, 90 ) then 0 else `score_PPE` end
                        + case when `score_FuelStorageUse` in ( 100, 90 ) then 0 else `score_FuelStorageUse` end
                        + case when `score_WasteManagement` in ( 100, 90 ) then 0 else `score_WasteManagement` end
						+ case when `score_presenceofsupervisor` in ( 100, 90 ) then 0 else `score_presenceofsupervisor` end						
                        + case when `score_PollutionPrevention` in ( 100, 90 ) then 0 else `score_PollutionPrevention` end )
 
/
 
( case when `score_timelydelivery` in ( 100, 90 ) then 0 else 1 end
+ case when `score_GoodAttitudeDisplayed` in ( 100, 90 ) then 0 else 1 end
+ case when `score_ProgrammePerformance` in ( 100, 90 ) then 0 else 1 end
+ case when `score_FinishedProduct` in ( 100, 90 ) then 0 else 1 end
+ case when `score_TidyWorkingArea` in ( 100, 90 ) then 0 else 1 end
+ case when `score_MaterialsProtected` in ( 100, 90 ) then 0 else 1 end
+ case when `score_RiskAssessments` in ( 100, 90 ) then 0 else 1 end
+ case when `score_GoodHousekeeping` in ( 100, 90 ) then 0 else 1 end
+ case when `score_SigningIn` in ( 100, 90 ) then 0 else 1 end
+ case when `score_PPE` in ( 100, 90 ) then 0 else 1 end
+ case when `score_FuelStorageUse` in ( 100, 90 ) then 0 else 1 end
+ case when `score_WasteManagement` in ( 100, 90 ) then 0 else 1 end
+ case when `score_presenceofsupervisor` in ( 100, 90 ) then 0 else 1 end
+ case when `score_PollutionPrevention` in ( 100, 90 ) then 0 else 1 end ),1) as `average`
  from scores 
 

INNER JOIN users d ON score_user_id_fk = user_id 
INNER JOIN contracts b ON score_contract_fk = contract_pk
INNER JOIN subcontractor c ON score_subcontractor_fk = subcontractor_pk
			WHERE user_id=$id ORDER BY `score_date` DESC");

			echo "<table id='example' class='display' cellspacing='0' width='100%'>
				<thead>
					<tr>
			<th>Date</th>
			<th>Contract Name</th>
			<th>Project Manager</th>
			<th>Subcontractors Name</th>
			<th>Timely delivery</th>
			<th>Good Attitude Displayed</th>
			<th>Programme Performance</th>
			<th>Presence of supervisor</th>
			<th>Finished Product</th>
			<th>Tidy Working Area</th>
			<th>Materials Protected</th>
			<th>Risk Assessments</th>
			<th>Good Housekeeping</th>
			<th>Signing In</th>
			<th>PPE</th>
			<th>Fuel Storage Use</th>
			<th>Waste Management</th>
			<th>Pollution Prevention</th>
			<th>Project Managers Comments</th>
			<th>Average</th>
					</tr>
				</thead><tbody>";

while($row = mysqli_fetch_array($result))
			  { ?>
					<tr>
			 <td><?=$row['score_date']?></td>
			 <td><?=$row['contract_name']?></td>
			 <td><?=$row['user_name']?></td>
			 <td><?=$row['subcontractor_name']?></td>
			 <td><?=$row['score_timelydelivery']?></td>
			 <td><?=$row['score_GoodAttitudeDisplayed']?></td>
			 <td><?=$row['score_ProgrammePerformance']?></td>
			 <td><?=$row['score_presenceofsupervisor']?></td>
			 <td><?=$row['score_FinishedProduct']?></td>
			 <td><?=$row['score_TidyWorkingArea']?></td>
			 <td><?=$row['score_MaterialsProtected']?></td>
			 <td><?=$row['score_RiskAssessments']?></td>
			 <td><?=$row['score_GoodHousekeeping']?></td>
			 <td><?=$row['score_SigningIn']?></td>
			 <td><?=$row['score_PPE']?></td>
			 <td><?=$row['score_FuelStorageUse']?></td>
			 <td><?=$row['score_WasteManagement']?></td>
			 <td><?=$row['score_PollutionPrevention']?></td>
			 <td><?=$row['score_comments']?></td>
			 <td><?=$row['average']?></td>

					</tr>
			  <?php }
mysqli_close($con);
	}
}
?>
	</tbody></table>


</div>
</body>


<script type="text/javascript" language="javascript" src="tables/media/js/jquery.js"></script>

<script type="text/javascript" language="javascript" src="tables/media/js/jquery.dataTables.js"></script>

<script type="text/javascript" language="javascript" src="tables/media/js/dataTables.tableTools.js"></script>

<script type="text/javascript" language="javascript" src="tables/resources/syntax/shCore.js"></script>

<script type="text/javascript" language="javascript" src="tables/media/js/dataTables.colVis.js"></script>

<script type="text/javascript" language="javascript" src="tables/resources/demo.js"></script>

<script type="text/javascript">
		$('#btn1').click(function(){
				var value = $( "#user_id" ).val();
				var form = $('<form action="my_history.php" method="post">' +
		'<input type="hidden" name="id" value="' +  value + '" />' +
		'</form>');
		$('body').append(form);
		$(form).submit();
			  });

</script>

	<script type="text/javascript" language="javascript" class="init">
 
$(document).ready(function() {
	var table = $('#example').DataTable( {
		"scrollX": true,
		"dom": 'T<"clear">lfrtip',
		"tableTools": {
			"sSwfPath": "tables/swf/copy_csv_xls_pdf.swf",
			"aButtons": [
				"copy",
				"csv",
				"xls",
				"print"
			]
		}
	} );
var colvis = new $.fn.dataTable.ColVis( table );
$( colvis.button() ).insertAfter('div.info');

} );

		 
	</script>

<?php include('footer.php'); ?>

Open in new window

Just interested to know why you are coding it like that - why not have the button simply submit a form - why the need to create the form dynamically and then submitting it?

Why not simply AJAX the request and add it to the page?

Also try moving the $('#btn1').click() code inside the $(document).ready() block.

Personally though I would make the btn1 Click function make an AJAX call back to a script on the server with the user ID and then simply append the results wherever you need them.
Why not simply AJAX the request and add it to the page?

can you provide an example of this i'm open to solutions.
Here is a basic outline. On click an AJAX call is made back to the getscores.php script which is basically everything from line 33 to 169.
All you need to do is chop these lines out into getscores.php - with appropriate includes to make it work - and replace the code with an empty div
<div id="scores"></div>
The AJAX call will return the HTML which will then be loaded into the div.
$(function() {
   $('#btn1').click(function(){
       $.ajax({
           url: 'getscores.php',
           type: 'POST',
           data: {id: $( "#user_id" ).val()},
           success: function(response) {
               $('#scores').html(response);
           }
       });
   });
});

Open in new window

I don't want the user to click submit, I just want the data to load straight away Julian.
" I just want the data to load straight away"

You mean when the page loads? If not then based on what event?

If on page load then why not just render it into the page - and if so what is the button Get Scores meant to be for?
I'm going to scrap the get scores button... The user should see the data when the page loads Julian
I am not sure I understand the problem here.

Why not simply have the code from line 33 run directly instead of checking for $_POST?

i.e.
<div class="visible-xs visible-sm visible-md"><br></div>
	<button class="btn btn-primary" id="btn1">Get Scores</button>
	

<?php

// TAKE OUT THE FOLLOWING 3 LINES AND THEIR CORRESPONDING
// CLOSING BRACES 

//if( $_SERVER['REQUEST_METHOD'] == 'POST') {

//	if(isset($_POST['id'])){
//			$id = $_POST['id'];
                        // CHANGE ABOVE TO THE LINE SHOWN BELOW
			$id = $_SESSION['user_id'];
						$con=mysqli_connect("NOT SHOWING YOU THAT");
			// Check connection
			if (mysqli_connect_errno())
			  {
			  echo "Failed to connect to MySQL: " . mysqli_connect_error();
			  }

echo "<hr><div class='clear'></div>";
echo "<h3>HISTORY</h3>";
... 
// REST OF CODE UP UNTIL LINE 165 - COMMENT OUT CLOSING BRACES LINE 166 AND 167
//       }
//} 

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Member_2_248744
Member_2_248744
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the review of my code It's all sorted now.
Can you give us more information on what you did to solve your problem?