how to prevent php code to run when loading a page - php

Good day,
Although I'm an old programmer, I'm new to php, so I need help.
Context
1. I have a submit form with an update button.
2. I have php code to insert records in a MySQL database.
Problem
1. When I first start the page, the php code runs.
2. When I refresh the page, the php code runs again.
Code
<!-- Button definition -->
<input id="submit" type="submit" class="button" name="submit" value="submit" onclick="Update_MySQL()" />
<!-- Function to be executed by the onclick -->
<script>
<?php
function Update_MySQL() {
if(isset($_POST['submit']))
{
$sql = "MYSQL UPDATE STRING" ;
$MY_CONNECTION->query($sql) ;
}
}
?>
</script>
What I know
1. PHP runs on server and javascript on the browser (client)
2. PHP delivers data to the server when the page is launched or refreshed
Can anyone help me on this?
Many Thanks

You can't prevent this when using the native html <form action="form.php"> way, but there is a way around. After progressing your form, you can redirect using header() to another page (or even the same) with a GET-Redirection-Code (see wikipedia).
if (isset($_POST['field'])) {
// progress data
header('HTTP/1.1 303 See Other');
header('Location: '.$_SERVER['PHP_SELF']);
exit;
}
Another completely different but also working approach is to use javascript to submit your form data.

Related

HTML form triggers php code in file, how do i get back to html?

I am collecting data in a form which calls on a php file to put the data into mysql. It works fine, but after the data gets into the database, the browser just shows a blank page and in the browser input bar is the line
http://nameofmyste.net/mfb1.php
It is as though the HTML sent me to the php code where runs fine on the server then it just gets stuck, and stays there. How do I "get back" to my html script?
The call form action command looks like:
<form class="form-horizontal" role="form" action="mfb1.php" method="post" >
The php code exists in the file mfb1.php and works fine and just terminates with the standard closing "?> " at the end.
Thanks for your help.
Sorry for the delay in getting back to the question, and very sorry for my incorrect use of the forum, I am new and learning...
I have done some work since the original question and have created a very simple AJAX example that should work fine, but it doesn't. Here is the HTML file with the js function localform. It uses a synchronous AJAX call (3rd parameter set to "false") to invoke my php code, which is below as well.
It runs fine, I see the phrase "we made it" which replaces the "replace here" text on the html page, just like it is supposed to. But, within half a second, the "we made it" goes away and the "replace here" text shows up again.
It is as though the html code were running again form the top. The address in the browser bar, after the submit now reads
http://bruwptest.netne.net/Test%20Files/ajaxtester.html?
The question mark at the end is new.
Here is the code:
ajaxtester.php:
<?php
echo "we made it";
?>
ajaxtester.html:
<!DOCTYPE HTML>
<html>
<body>
<h1>AJAX Tester</h1>
<p>Echo here from the server: <span id="text">replace here</span></p>
<form onclick="localform()">
<button type="submit" >Submit</button>
</form>
<script>
function localform() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "ajaxtester.php",false);
xhttp.send();
document.getElementById("text").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
My question is why the html page is refreshing and overwriting the "we made it" that I just wrote there from the php?
It is as though the HTML sent me to the php code
Well, yes. That's what you specified:
<form class="form-horizontal" role="form" action="mfb1.php" method="post" >
<!-- right here ----^ -->
then it just gets stuck
Well, what does mfb1.php do? What output does it generate? If it doesn't render any HTML to the browser, then no HTML is rendered to the browser.
Or if there's an error and error reporting isn't turned on, there may be no valid output to render to the browser. Turn on error reporting during debugging, check your logs, etc.
You can, within that script, output any HTML that you like. Anything outside of <?php ?> tags is just sent directly to the client, so put any HTML that you want there.
Alternatively, at the logical completion of the script you could also redirect the user to another page:
header('Location: somePage.html');
This would return a response to the user's browser indicating that it should make a new request for somePage.html.
You have to send to client a redirect location to your original HTML page; at the end of your php script, write:
header( "Location: YourHtmlFileUrlHere" );
exit;
The exit command is not mandatory, if the command is at the end of script.
Please note: The header command fails if before in page there are ANY OUTPUT

Example of JS / jQuery to submit a form handled by PHP

I have PHP code like this: (for signing out - located in a php page together with other php handlers for different functions and this file is included in pages like index.php or other relevant pages.)
if(isset($_POST['signout'])) { // logout button
// Clear and destroy sessions and redirect user to home page url.
$_SESSION = array();
session_destroy();
// redirect to homepage (eg: localhost)
header('Location: http://localhost/index.php');
}
I normally use a <form action="index.php" method="post"> where the function is currently included and <input type="submit" name="signout"> for such things but this time i would like to use an anchor tag like:
<a href="" >Sign Out</a> for signing out.
Would anyone be kind enough to show an example code that will trigger a submit that will be handled by the given PHP code above.
Either a jQuery or Javascript solution would do. I would just like to see a complete example on how this works.
There's good reason for using a POST for submitting authentication tokens which usually commences or alters the session state - but these don't really apply to the problem of closing the session - why not just just trigger this via a GET?
But if you really must do a POST, and you really must do it via a a href (rather than styling a submit button) and you really must do it via javascript (which will break if the client has javascript disabled) then...
<script>
function sendForm(formId)
{
if (document.getElementById(formId).onsubmit())
document.getElementById(formId).submit();
}
<script>
<form id='logout'>
<input type='hidden' name='signout' value='1'>
</form>
logout

Strategies for a multi-page form?

I've been trying to make a multi-page poll with jQuery Mobile that is supposed to interact with my MySQL database through Ajax/PHP and have been having issues with it for a while now. It seems I have some problems submitting the form as a result of having it split into several pages. One requirements I need is that the page can not have a page reload.
In my first attempts I tried to divide the pages up into the following:
<div id="page1" data-role="page">
This however failed so many times no matter how I tried to code it. I can not get the submit button to work and I think it could be caused by the fact that I have split the form into several div "pages". I've also tried to make next/submit buttons rather than "Next, next, next ... submit" so that I can store the temporary data in the session, unsuccessfully.
I reworked my whole strategy into a code that hides the question divs that are not active. By this I mean I have one div with data-role set to page, and within it I have several divs with data-roles of content that are hidden/shown by clicking through the form with the next button. I managed to make a small sample form this way that submits the whole form and gets printed out perfectly with some PHP code. However I have yet to successfully validate this version. I can only get my script to validate the last page, and even then it requires ALL checkboxes to be checked, which is pointless. When I tried to implement this version into my real project I could not get it to submit to the .php script at all, but that might just be some syntax error that I will keep looking for.
So, have anyone done anything similar? I'm looking for potential other strategies to solve this issue, or perhaps someone has a theory as to why my aforementioned attemps have failed. Seems Ajax form submits are hard to get working within jQuery Mobile?
Also in case someone can spot a flaw in this I've attached this code that I use for submission, is there an easy way to make this into a function? Or is that pointless?
$(document).ready(function()
{
$("#submit").click(function()
{
var data_string = $('#form').serialize();
$.ajax(
{
type:'POST',
url:'add.php',
data:data_string,
success:function(response)
{
$("#answers").html(response);
}
});
})
});
I also use this function during window.onload to generate the poll with a lengthy .php script. Basically it generates the questions as , every other question variety has only name="answers[question_id]".
function getQuestions(id)
{
var xmlhttp = getHttpRequestObj();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","poll2.php",true);
xmlhttp.send();
}
The form looks like this:
<form id="form">
<div data-role="content" id="form'.$page.'" class="section">
<fieldset data-role="controlgroup" data-type="vertical" data-mini="true" id="'.$question_id.'">
<input type="checkbox" name="answers['.$question_id.']['.$alt_id.']" id="'.$question_id.'_'.$alt_id.'" value="'.$alt_id.'"/>
<label for="'.$question_id.'_'.$alt_id.'">'.$alt_desc.'</label>
</fieldset>
<input type="button" name="next" value="Next" id="next" onClick="toggleVisibility(\'form'.($page+1).'\')" class="next-btn"/>
</div>
The last page has this code instead of the next button:
</div><input type="button" id="submit" value="Submit" class="submit-btn"/></form>
In my opinion, hiding the other options and open one by one is a better way (also called multi step form).
For validation, you can do it in client side with javascript or use ajax which triggers on appropriate event (you don't need to submit it for validation) and validates in server side.
You are in right track. The issue i see here is how you'l do the validation but that'l depend upon how your form is structured.

returning from a form submit call to a .php file

I have a questionnaire in a form. In the end of it the submit button is pressed that is supposed to call a .php file that inserts data into a database through its action information and afterwards show the last page that contains something like "thank you for participating etc." via the onsubmit info.
problem is that the last page is shown before the .php file is shown which means it is visible only for like half a second and then the php script is carried out which ends up showing a blank page.
The php script works it inserts data into the questionnaire correctly so there should be no mistakes syntax-wise.
any ideas if I have to exit the cript or something and return to the .html file or what could be wrong?
on your opening form tag add action="submit.php"
then once it goes to that page when the submit button is hit add this to the bottom of that php page:
header("Location: successfull.html");
IT sounds like what youre doing is showing the message with Javascript via the onsubmit event - this happens before the request is even set to the server and the php script. Youd either need to do an ajax form submission and then display the message when the request completes or make the php script redirect to the success message page when it is done.
But this is all just speculation without seeing any code... you should post some :-)
Why not submit the form to process.php then process it:
if(isset($_POST)){
$name = $_POST['name'];
// etc etc
// if all error checks pass, then echo out - thanks for taking part in our survey!
}
What you're doing is submitting it, and it seems you're getting javascript to say 'thank you' but it is being submitted before this thank you message can be displayed - no harm in echoing this out on your .php page!!
Update
You mention about redirecting to a page afterwards, but this can be done by:
header("Location: where/to/go.php");
exit;
But you can't do this with the above (echoing out a success) since it will redirect straight away.
The way I deal with this is putting the html contents into the php file.
<?php
if (!isset($_POST["submit"])) { // if page is not submitted to itself echo the form
?>
<html>
<head>
<title>survey</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
...... (your form) ......
<input type="submit" value="submit" name="submit"><br />
</form><br />
</body>
</html>
<?
}
else {
$db = new PDO('...');
$db->exec(...);
echo "Thank you!";
}
?>
A few ways you could accomplish that.
You could make the php file it submits send out the data for the "thank you for participating" page (if you're fine with simply going to another page).
Alternatively, if you want to stay on the same page but just show the "thank you" notification, I would use JavaScript to disable the default action (e.preventDefault(); in the event handler) for the "submit" button on the forum, then also use JavaScript to use AJAX to submit the data.
An example (using JQuery), which won't change your page and perform the submit in the background, and display the "thank you" when done, on the current page.
$("a#confirmSubmit").click(function(e) {
e.preventDefault(); // Prevents the submit button from changing pages
data = {
Name: $("input#Name").attr("value")
// Add other data here also
};
$.post("/page/to/submit/to.php", data, function(d) {
//Write the code here to show the "thank you" notification.
//It will show upon completion here.
});
});
If you want to check for errors with inserting into the DB, you could check the value of the data of the AJAX call, to conditionally show the error. You can then return the user to the exact same form they were already on, with all the data still there, and show them an error message.

Easiest way to give Javascript alert after PHP header() redirect

I have a page where users submit a form, and it goes to a separate PHP script. After the script is done, it header() redirects the user back to the page they were on. Now what I want to do is if there is an error or certain conditions in the script, redirect the user to the same page but display a Javascript alert once they get there as a warning message. I could append some variables to the URL and check for that with $_GET but I figure there is probably an easier way... perhaps with some POST data, or something like that?
Thanks
You can do this all on the server side by using the session:
"Show form" php script creates the form and returns it to the user.
User fills it out and submits it to another php script "receive script" which receives the form data, and notices an error, missing data, etc.
The "receive script" stores the error msg in the session (as item err) and redirects to the 'show form' script.
The "show form" script (same as in step 1) actually does more than create the form. It also:
looks in the session to see if it has an item 'err', an error msg. In step 1 there wasn't. But now there is. So the php script creates the form, along with a div that shows the error msg to the user.
Resets the session's 'err' item to nil.
The php script could also include javascript in the page which would make the error msg disappear after a while or be shown as a popup, etc.
ps. The above flow is how rails handles forms and redisplay of the form.
Update: Thanks to #zod for pointing out that I wasn't clearing the err item in the session.
If an error is encountered, store the error state to a $_SESSION array and then redirect the browser to the original page. Have a script on the original page to check if an error state is set. If yes, trigger a javascript alert or whatever handling you want to have.
And at the common footer template (or at the footer of original page), check and clear the errors array, so it doesn't persist when the user moves to other pages or reloads the current page.
Example:
processor.php
<?php
if($something == $iswrong){
$_SESSION['errors']['error5301'] = 1;
session_write_close();
header("Location: http://www.example.com/originalpage.php");
exit;
} ?>
originalpage.php
<!-- Header -->
<?php
if(isset($_SESSION['errors']['error5301']) && $_SESSION['errors']['error5301'] == 1){ ?>
<script type="text/javascript">
alert('Something is not correct!');
</script>
<?php } ?>
<!-- Some page content -->
....
.....
..
......
<!-- Footer -->
<?php
if(isset($_SESSION['errors'])){
unset($_SESSION['errors']);
} ?>
Hope that helps.
first page
<script>
onsubmitfunction()
{
document.getElementByid('errorid').value=1;
}
</script>
<form name='' id='' onsubmit="javascript:onsubmitfunction();">
<input type='hidden' id='errorid' value=''>
</form>
In destination.php
<?php
if($_POST['error']==1)
{
?>
<script language='javascript'>
alert('Errrrrorrrr');
</script>
<?
}
?>
This is enough for your question.
As per my understanding

Categories