Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

JavaScript form onload looping

Posted on 2014-10-07
16
467 Views
Last Modified: 2014-10-12
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.
0
Comment
Question by:Geektank
  • 6
  • 6
  • 2
  • +2
16 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 40365671
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 :
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28102799.html
0
 

Author Comment

by:Geektank
ID: 40365703
Is this the only way?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40365736
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.
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 82

Expert Comment

by:leakim971
ID: 40365763
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)
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 40365764
Can we see some code.
0
 

Author Comment

by:Geektank
ID: 40365779
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

0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 40365824
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.
0
 

Author Comment

by:Geektank
ID: 40365830
Why not simply AJAX the request and add it to the page?

can you provide an example of this i'm open to solutions.
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 40365863
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

0
 

Author Comment

by:Geektank
ID: 40365941
I don't want the user to click submit, I just want the data to load straight away Julian.
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 40365964
" 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?
0
 

Author Comment

by:Geektank
ID: 40365975
I'm going to scrap the get scores button... The user should see the data when the page loads Julian
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 40366122
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

0
 
LVL 34

Accepted Solution

by:
Slick812 earned 500 total points
ID: 40366239
greetings Geektank, , I looked at your code and the comments here, I will tell you that you have NOT set up your page to do any functioning for the user to see meaniful info to advance to a FORM submission, , , OR any way to "accept any data input" from your automatic form submission.
You also have many many HTML errors like the <div> tag before the <body> tag.
It looks like you have copy an pasted some code from several sources that may not be useful together? ?

in your javascript you have this line -
     var value = $( "#user_id" ).val();

I search and searched your code but could NOT find any input with this ID -
     id="user_id"
so this seems to submit an empty or blank ID value in the hidden with the form submit here - $(form).submit();

IF you do PHP code and have a form Submit, at the end of of the PHP code you have some PROVISION to Change the page from what was submitted the first time BEFORE the page was submitted, which you do NOT do here start at line 164 -
     <?php }
         mysqli_close($con);
        }
      }
    ?>

you MUST add code to this to CHANGE the PAGE here -
     <?php }
         mysqli_close($con);
        }
// ADD CODE HERE to GET out of LOOP
      }
    ?>

you can simply just NOT have this code for javascrit-
<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>
you could also change that code to SUBMIT to another page , NOT THIS ONE

you do not seem to have an idea of what you need to do to get results for the progression of your data input (as form submission) and the Resultant output for the datatable <table>.

Also since the user ID is already in the $_SESSION['user_id'], your form submit with the user ID is a useless function, and should not be here.

Please consider letting us help you to do a restructuring of your page and the PHP to get some sort of usefull result.
What is the purpose of the page and the PHP, to get you to a place that you have usefull out put to your user? ?
0
 

Author Closing Comment

by:Geektank
ID: 40375945
Thanks for the review of my code It's all sorted now.
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 40376421
Can you give us more information on what you did to solve your problem?
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question