How to submit form without moving to next page in PHP - php

The Problem
I am trying to submit a form in php but due to the nature of what i want i need the page to not go onto the next one i just want it to submit the data and refresh the current page or whatever, at current it submits the data and goes onto page 2 which i dont want i just need it to submit the data and stay on the current page, if thats possible!
The Code
//page 1 code
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form method="post" action="jacob_dailey.php">
<select name="baby_status">
<option value="playing">Playing</option>
<option value="awake">Awake</option>
<option value="sleeping">Sleeping</option>
</select>
<br />
<input type="submit" value="Submit"/>
</form>
</center>
//page 2 code
<?php
if (isset($_POST['baby_status'])) {
$baby = $_POST['baby_status'];
setcookie("baby_status", $baby, time() + 31556926, '/'); // Data will Store For 1 Year
header('Location: ' . $_SERVER['PHP_SELF']);
}
$status = $_COOKIE['baby_status'];
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
echo '</center>';
?>
Page 2 code shouldnt be as important but i just need it so when i click submit on page 1 it updates the information on page 2 but doesnt take me to page 2.
Cheers!

Your form can submit onto itself. Just in the action="xyz" either leave it (the whole action=... attribute) out entirely or else name the page that also contains the form there between quotes.
Then when you load the page you check the $_POST or $_GET array (depending on the method) to see if the submit button was pushed or if someone just navigated to the page. (You'll want to give you submit button a name="foo".)

action="jacob_dailey.php" in your form takes you to that page, you either paste your php code to main page and replace action with just "" or you will search AJAX and learn how to it with that

You can use jQuery.ajax(). Example here:
http://www.formget.com/form-submission-using-ajax-php-and-javascript/
This example uses a database, but you can use a php file to return values and read them from the response in javascript. Do not put any action to the form but enable a click event handler on the submit button to enable the function.
Also my example here: http://dev.ossipesonen.fi/alkoholilaskuri/
A very simple form where you insert values, pass them onto PHP with $_POST and then calculates the right amounts and sums, and you print them in the response.

Solution: Update Status Without Page Reload Using XHR and Filesystem Storage
If you want someone on another computer to see the update, then you'll need to store that information on the server. You could store the information in a database, but for this small bit of information I'm using the filesystem.
page1.php
<?php
// get baby status if available
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
// prepare to update select list
list($pl_check, $pl_check, $pl_check) = array('', '', '');
switch ( $status ) {
case 'playing': $pl_check = ' selected '; break;
case 'awake': $aw_check = ' selected '; break;
case 'sleeping': $sl_check = ' selected '; break;
}
?>
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form id="baby_form" method="post" action="update_baby.php">
<select id="baby_status" name="baby_status">
<option value="playing" <?php echo $pl_check ?>>Playing</option>
<option value="awake" <?php echo $aw_check ?>>Awake</option>
<option value="sleeping"<?php echo $sl_check ?>>Sleeping</option>
</select><br />
<input type="submit" value="Submit"/>
</form>
See Baby Status
</center>
<script>
// XHR/PHP/Filesystem method
function update_baby () {
var baby_status = document.getElementById('baby_status');
var status=encodeURIComponent(baby_status.options[baby_status.selectedIndex].value)
var parameters = 'baby_status=' + status
// set up XHR object
var xhr = new XMLHttpRequest()
xhr.open('POST', 'update_baby.php', true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
// handle response
xhr.onload = function () {
console.log(this.responseText)
alert(this.responseText)
}
xhr.send(parameters)
}
// hook up baby status function to form submit
document.getElementById('baby_form').addEventListener('submit', function(evt){
evt.preventDefault()
update_baby()
})
</script>
page2.php
<?php
// execute baby update code and get current status
include 'update_baby.php';
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
?>
<br>
Update Baby Status
</center>
update_baby.php
<?php
if (isset($_POST['baby_status'])) {
$status = $_POST['baby_status'];
// prepare php script text for baby status file
$status_write = <<<EOT
<?php
\$status = '$status';
?>
EOT;
// write status to baby_status.php
if ( $baby_status_file = fopen('baby_status.php', 'w') ) {
fwrite($baby_status_file, $status_write);
fclose($baby_status_file);
}
echo 'Baby status updated.';
}
else {
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
}
?>
Note: To use this option the directory these files are in must be writeable by the web server.

Related

Write and Read Checkbox status to/of file with php

I am trying to save the status of my checkbox whether it is true or false (checked/unchecked) to a file. I managed to write the checkbox value to a file but I have no idea if this is even the right way to do it and I also don't know how to load it again.
I want that my checkbox status of the last time is "remembered" by reloading the page.
Using local storage isn't a option for me sadly.....
here my code:
<form action="database.php" method="post">
<input type="hidden" name="check2" value="0" />
<input type="checkbox" name="check2" value="1" />
<input type="submit" value="senden" />
</form>
<?php
$handle = fopen("saver.json", "a");
$fh = fopen( 'saver.json', 'w' );
fclose($fh);
foreach($_POST as $value) {
fwrite ($handle, $value);
}
fclose($handle);
?>
so this first deletes the old saved value and then writes a 1 or a 0 in the file.
Am I on a good way or do I think too simple?
All help is highly apprecciated !
Thanks a lot
Try this solution, all checkbox status are preserved after submit, reload and even restart your browser:
<?php
// Use SESSION to store checkbox status data. SESSION seems to have a lifetime, that will erase itself if exceed.
// If you need preserve status after browser closed (), you might need to consider storing them into a file.
session_start();
$sessionTgt = NULL;
// You probaby won't need this, but if you have corrupted session
// , use "localhost://my/url/thisScript.php?reset=1" to reset/erase this session key ("saveCheckBox").
if ($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET["reset"]) && $_GET["reset"] === "1" ) {
unset($_SESSION["saveCheckBox"]);
echo("Ok, have just reset \$_SESSION[\"saveCheckBox\"]:");
exit();
}
// Reset this session key ("saveCheckBox") if it was not set.
if (!isset($_SESSION["saveCheckBox"])) {
$_SESSION["saveCheckBox"] = [
// "0" means server tell client no redirect. "1" means redirect immediately.
"ifRedirect" => "0",
// Store checkbox checked status. Example data will look like this:
// [
// "ckBox1" => "checked",
// "ckBox4" => "checked"
// ]
// , it means checkbox "ckBox1" and "ckBox4" are checked, others are not.
"checkBoxData" => [],
];
}
// Passing "reference", not value, to variable $sessionTgt.
$sessionTgt = &$_SESSION["saveCheckBox"];
// Print html form, by some condition. if some of the checkbox have "checked" status
// , then append the string "checked" inside their html <input> tag
// , so the input box will displayed as "checked".
function printFormAndCheckStatus ($checkStatus = NULL) {
echo(
'<form action="" method="post">' .
'<input type="checkbox" name="ckBox1" value="checked" ' . printCheckedMaybe("ckBox1", $checkStatus) . ' />' .
'<input type="checkbox" name="ckBox2" value="checked" ' . printCheckedMaybe("ckBox2", $checkStatus) . ' />' .
'<input type="checkbox" name="ckBox3" value="checked" ' . printCheckedMaybe("ckBox3", $checkStatus) . ' />' .
'<input type="checkbox" name="ckBox4" value="checked" ' . printCheckedMaybe("ckBox4", $checkStatus) . ' />' .
'<input type="submit" value="Submit" />' .
'</form>'
);
}
function printCheckedMaybe ($nameAttribute, $checkStatus) {
if (isset($checkStatus[$nameAttribute])) {
return "checked";
} else {
return "";
}
}
// POST "bouncing" logic. Notice the sequence is like this:
// -> Client get new page (client)
// -> Client user checked checkbox and post (client)
// -> Server save post data to SESSION (server)
// -> Server ask client for redirect (server)
// -> Client redirect immediately without doing anything (client)
// -> Server give back modified form content, that some input box has "checked" string
// appended inside the tag (client).
// The reason using double request instead of one, is to PREVENT POST DATA GET POSTED TWICE, which confuse server.
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$sessionTgt["ifRedirect"] = "1";
$sessionTgt["checkBoxData"] = [];
if (isset($_POST)) {
foreach ($_POST as $name => $value) {
$sessionTgt["checkBoxData"][$name] = $value;
}
}
header("Refresh:0");
// When client get this response header pattern/content, client (browser) know he need to
// refresh the page immediately (request the same url again).
} else {
if ($sessionTgt["ifRedirect"] !== "1") {
if (isset($sessionTgt["checkBoxData"])) {
printFormAndCheckStatus($sessionTgt["checkBoxData"]);
} else {
printFormAndCheckStatus();
}
} else {
// Just after redirect.
$sessionTgt["ifRedirect"] = "0";
printFormAndCheckStatus($sessionTgt["checkBoxData"]);
}
}
Does this solve your problem? This solution save your checkbox status inside server SESSION, but SESSION seems to have a lifetime, that will erase itself if exceed. (maybe I'm wrong). If you need long term storing you can write it into a file or database.

Unable to execute statement in php only when user selects yes in dialog box

Hi am trying to insert data into mysql only when user enters yes in confirm dialog but the data always inserted into mysql even if the user enters no.Here is my code..
<?php if (mysqli_num_rows($data_query) >= 1) { ?>
<script>
var txt;
var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it')
if (r == true) {
<?php
$query="INSERT INTO video_data(date) " ;
$query .= "VALUES('{$date}')";
$create_video_query=mysqli_query($connection,$query);
if (!$create_video_query) {
die("failed".mysqli_error());
} else {
$success = "Video added succesfully";
}
?>
}
</script>
<?php } ?>
Test your code without the php.
you are missing a semicolon after "Click OK to Add & Cancel to Cancel it')"
Make sure you really have "if(r==true)" and not "if(r=true)"
I tested the following code (php is removed) and it works:
<html>
<body>
<script>
var txt;
var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it');
if(r==true){
alert('Clicked OK: Run insert sql');
} else {
alert('Clicked Cancel: Do nothing');
}
</script>
</body>
</html>
You can not mix server-side (PHP) and client-side (JavaScript) together to interact in real time together. You have to use AJAX or you have to submit a form (either one built in the html or built by javascript). Here is just a basic example:
<?php
# Checks to see if the form has been submitted
if(isset($_POST['add'])) {
$query="INSERT INTO video_data(date) " ;
$query .= "VALUES('{$date}')";
$create_video_query=mysqli_query($connection,$query);
if(!$create_video_query) {
die("failed".mysqli_error());
}
else {
$success = "Video added succesfully";
}
}
?>
<?php
# I don't know what this is based on (the query) so I don't know if it's required.
# I just left it
if(mysqli_num_rows($data_query) >= 1) { ?>
<script>
var txt;
var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it');
if(r !== false){
// Assumes there is a form to submit and submits it
form.submit();
}
</script>
<?php } ?>

Handling PHP POST variable from other php file and managing $_SERVER["PHP_SELF"]

I stucked at a problem I can't figure out why isn't is working.
I am handling POST variable from another php file:
$temp_variable = $_POST['activity'];
After my code process $temp_variable, I try to make a button (still in the same php file where I handled $_POST['activity'])
echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">';
echo '<input type="submit" value="OK" name="process_more"/>';
echo '</form>';
Then I try to catch OK button press, to start another activity:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$query = "DELETE FROM table1 WHERE id = 5";
mysqli_query($conn,$query)
}
My problem is that the "Delete FROM" part of the code executes immediately, before the user press the "OK" button.
What can be the problem ?
Check something more specific to your form.
if(isset($_POST['process_more'])){
if ($_POST['process_more'] == 'OK') {
// execute the delete
}
}
$_SERVER["REQUEST_METHOD"] could equal 'POST' from a different form submission..

How can I assign session id of php in a jQuery file?

I have a main file
index.php
in which I include four other files like
header_get_started.php,
content_main.php,
right_sec_home.php,
footer.php.
Here is my code
"index.php"
<script src="js/ajax.js"></script>
<?php include_once('header_getstarted.php'); ?>
<?php include_once('content_main.php'); ?>
<?php include_once('right_sect_home.php'); ?>
<?php include_once('footer.php'); ?>
"header_getstarted.php"
<span class="select_input">
<?php
$sqlCmd = "some query";
echo combo('cmb_command','custom-class1 custom-class2','cmd_name','cmd_id','0',$sqlCmd,'sendpostmtu()' $width="style='width:250px;cursor:pointer;'")
?>
<input type="submit" name="" class="sub_bg" value="" onclick="get_request_by_command($('#cmb_command').val());">
</span>
In header_get_started.php
When select any command from select box, I want to assign it's id to $_SESSION['id'].
Onclick of selection box I have an ajax request which can refresh the main content (content_main.php). Also I want that selected id in another page in right_sec_home.php to refresh it's content.
How can I assign the php session id in JS file for 2nd page?
My JS file is
function get_request_by_command (commandId) {
var cmdTitle=$('#cmb_command :selected').text();
if(cmdTitle=="") {
cmdTitle='ABC';
}
$("#main_wrap").hide();
if(cmdTitle=='--Select--'){
$("#cmdTitle").html("");
}else{
$("#cmdTitle").html(cmdTitle);
}
$("#cmbs_cmd").val(commandId);
document.getElementById('request_list').innerHTML='<img src="images/loader.gif" />';
var strURL="request_by_command_tbl.php?id="+commandId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var ret = req.responseText;
$("#requestTitle").html("<span id='cmdTitle'>"+cmdTitle+"</span>);
$('#request_list').html('');
$('#request_list').html(ret);
$('#main').show();
$("#searchDiv").show();
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
With using this jQuery function, I have created an ajax request, and send the id to the "request_by_command_tbl.php" file.
In "request_by_command_tbl.php" file i assigned,
$_SESSION['id'] = $_REQUEST['id'];
Also I want this $_SESSION['id'] in right_sec_home.php at same instant.
So is their any way to assign php $_SESSION['id'] in the jQuery script file before sending ajax request.
My other files
"content_main.php"
<div id="request_list"> </div>
<div> </div>
<div id="add_space"></div>
Right section home file in which i need session id
"right_sec_home.php"
<?php
function getRequestByMonth($month, $year, $id){
$que ="SELECT distinct(MS.date) FROM commands AS MC , ranks AS MR ,steady_tours AS MST, preferred_tours AS MPT, registration AS MMS where date_format(rm_date, '%c-%Y') = '".$month."-".$year."'
AND MMS.cmd_id ='".$_SESSION['id']."'
order by MMS.date";
$res = mysql_query($que);
while($rows[]=mysql_fetch_array($res)){}
foreach ($rows as $res):
if($res['date'] == "") continue;
$dt = date("Y-n-j", strtotime($res['date']));
$return[getDateB($dt)] = $res['date'];
endforeach;
return $return;
}
I hope that this is clear enough.
Any ideas?
Please help.
there is no way for you to access the session information with jquery ..
explanation
sessions are files stored on the server --> where is java script is only a client side language ..
there is always a work around .. but i guess you should explain more about what exactly you want to achieve
<?php $sessionId = session_id(); ?>
<input id="session_id" name="session_id" type="hidden" value="<?php echo $sessionId; ?>" />
Get the value of the hidden field using jquery.
You can use some hidden fields or script variables inside the php file.
example :
<script>
var id = <?php echo $_SESSION['id']; ?>;
</script>
varible id can be accessible using the javascript or jquery

displaying records from a php file via jquery;

Ok I have this code
a script in my head.
function checkForm(e) {
if (e.keyCode == 13) {
$('#de').hide()
$.post('search.php', { name : search.searchinput.value() }, function(output) {
$('#searchpage').html(output).show();
});
}
}
and this is the html part:
<form name="search" id="searchbox">
<input name="searchinput" value="search item here..." type="text" id="inputbox" onkeydown="checkForm(event);" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><input id="submit" value="" OnClick="checkForm(event);" type="submit"/>
</form>
<div id="searchpage"></div>
and this the php file where the script will pass the data into.
<?
$name= $_POST['name'];
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
?>
here is the sceneraio, a user put a whatever text on the textbox name:'searchinput' and so whenever the user pressed the enter key the function checkForm(e) will execute and pass the data from the input field name:'searchinput' into the php file and then that php file will process the data into the mysql and see if the data that the script has pass into the php file is match to the mysql records and then if ever it match then the php file will pass that data back into the script and then the script will output the data to the #searchpage div.
Problem:
"all are not working" and the onclick function on the go button are not working"
please help, im stuck on this. thank you in advance.
First of all, there is a website called Jsfiddle. Paste your codes in the website and then paste the URL here. It makes your post a lot more readable.
Now, here if you are using jQuery, then why are you relying on onkeydown and onclick events? Its better to use jQuery's live function.
I have changed your code. Have a look at here. You can use live function for other events like onclick,onfocus,onblur,etc. It makes your HTML code much more cleaner and readable.
Consider using load instead of post (And remove the form tag or change input to textarea or else hitting enter will submit your form)
$('#inputbox').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13')
{
$('div#searchpage').load('search.php',{name: $(this).val()});
}
});
you have to stop the form from submitting the data, use something like
onsubmit="return (checkForm(e))"
and double check for syntax errors, for example you have missed a Semicolon at this line
$('#de').hide()

Categories