how to go on particular modal after form submit in php? - php

i have form within modal after submitting form it goes on .php page. so i want to prevent this from doing this.
rather it should stay on the same modal.
below is my php code.
please let me know how to add ID of modal into header so that form will directly go onto that modal only.
<?php
include 'db.php';
if (isset($_REQUEST['insert']))
{
$contractno = $_REQUEST['contractno'];
$doctype = $_REQUEST['doctype'];
$contractdate = $_REQUEST['contractdate'];
$validupto = $_REQUEST['validupto'];
$Remark = $_REQUEST['Remark'];
$sql = mysqli_query($conn,"INSERT INTO `contract`(`projectId`, `contractNo`, `documentType`, `contractDate`, `action`, `contractValueBase`, `validUpto`, `remark`) VALUES ('".$contractno."','".$validupto."''".$doctype."''".$contractdate."''".$validupto."')");
if ($sql>0)
{
header('Location: contracts.php');
echo 'data added successfully';
}
}
?>

You need to use ajax if you want to stay on the same page, Follow the below post:
jQuery Ajax POST example with PHP
OR
If its ok to reload then use "get" method in url so that u can send the id through it and you can catch it on the page using $_GET["id"]
header('Location: contracts.php?modal_id=1'); //sending modal id via header

Related

redirect to a page with php and and also submit POST data

I want to redirect to a page after executing a php function and also submit a html form with the methode POST, at once.
I found many solutions with GET but I want to handle this with POST.
You can use cUrl to send POST data you want, then make the redirect.
Look on the net for: "php curl".
Make your form action point to the php document where you want to execute your function and then in the end place this header("location: your_location_file.php");
Step one - submit form to functions.php
Step two - do what ever you need to do with the submited data
Step three - Redirect
Example:
<form method="post" action="functions.php">
...
</form>
functions.php
<?php
...
all your code
...
header("location: your_location_file.php");
?>
Javascript can help if you don't want to rely on curl. Had this laying around. Pass in $_POST or an array of the data you want posted. Add error/parameter checking.
function http_post_redirect($url='', $data=array(), $doc=true) {
$data = json_encode($data);
if($doc) { echo "<html><head></head><body>"; }
echo "
<script type='text/javascript'>
var data = eval('(' + '$data' + ')');
var jsForm = document.createElement('form');
jsForm.method = 'post';
jsForm.action = '$url';
for (var name in data) {
var jsInput = document.createElement('input');
jsInput.setAttribute('type', 'hidden');
jsInput.setAttribute('name', name);
jsInput.setAttribute('value', data[name]);
jsForm.appendChild(jsInput);
}
document.body.appendChild(jsForm);
jsForm.submit();
</script>";
if($doc) { echo "</body></html>"; }
exit;
}
You could use a session to hold the POST data.
I am currently using code like below. On my first page load, the $_POST data is checked. If it contains certain values already in the database, then it redirects to a page for those values.
// This could be part of the same script as below, or a different script.
session_start();
if($_POST['my_value'] && valueExistsInMyDb($_POST['my_value']) ) { // check my db to see if this is an existing value
$id = getIdOfMyValue($_POST['my_value']); // e.g. '4'
$_SESSION['POST'] = $_POST; // take ALL post data and save it in the session variable
header("location: your.php?myvalue=" . $id); // redirect to bookmarkable target page where $_GET variable matches what was posted.
exit(); // ensure no other code is executed in this script after header is issued.
}
Then your other file (or maybe even the same file) could do this:
// your.php?myvalue=4
if(isset($_SESSION) && array_key_exists('POST',$_SESSION)) {
$_POST = $_SESSION['POST']; // creates or overwrites your $_POST array with data from the session. The rest of your script won't be able to tell that it's not a real $_POST, which may or may not be what you want.
unset($_SESSION['POST']); // you probably want to remove the data from the session.
}
// now your myvalue=4 is stored in GET, and you can handle the rest of the POST data as you like
I don't know if that is the best solution, but so far it seems to be working for me so far. I only just wrote the code a few days ago and haven't tested all aspects yet.
Another option is to use HTML5 to change the address bar. No redirect needed. But the downside is that only "modern Webkit browsers" can use it, apparently.

CodeIgniter and modal forms(populating)

Usually with PHP and editing you click on a link that goes to a separate PHP page that has the "ID" of the entry you want to edit, you get the ID and populate your form base on this.
I would like to know how to do this if I am using a modal form? How do I get the ID get the records associated with it then populate the modal form.
sort of like this
//dropdown behavior for resp task and sub_task
$('#r_task_id').change(function() {
var selected_task_id = $('#r_task_id').val();
$.post("Assignment/populateSubTaskDropDown", { 'selected_task_id' : selected_task_id },//$_POST['selected_task_id']
function(data){
$('#r_sub_task_id').empty();
$.each(data, function(val, text) {
$('#r_sub_task_id').append(
$('<option></option>').val(val).html(text)
);
});}, "json");
});//task
PHP code is:
$this->session->set_userdata('selected_sub_task_id', $this->input->post('selected_sub_task_id'));
$json_resp_user = $this->assignmentModel->getResponsibleUsers($this->session->userdata('selected_sub_task_id'));
$json = array();
$json[0] = "-Select-";
if( count($json_resp_user) >= 1 ){ //if there is more in the result than the -Select-
foreach($json_resp_user as $detail){
//$json[$detail->user_id] = $detail->first_name." ".$detail->middle_name." ".$detail->last_name;
$json[$detail->user_id] = $detail->first_name." ".$detail->last_name;
}
}
echo json_encode($json);
but for the whole form not just a dropdown.
When you open the modal window set the id of the record in a public javascript variable, and on submit of the modal form pass the id parameter through url.
Another way is to have a hidden variable inside the form in the modal window and set it with the while opening the modal window. So it will be get passed the update form on the modal window is submitted.
<script>
id ='' //Set this when opening the modal window
function appendId(myform)
{
myform.action = myform.action + "/" + id;
return true;
}
</script>
<div id='modalWindow'>
<form onsubmit='return appendId(this)'>
//other elements
</form>
</div>
I had a quick read of $.post() of jQuery and apparently that was what I meant =p
the part on your script with
id ='' //Set this when opening the modal window
was where I was stuck on how to read that.
http://api.jquery.com/jQuery.post/
sorry if I wasn't clear but thank you for taking the time and trouble to answer me.

php redirect using a form

I looked over stack for an answer with no success. Im looking to make a form with radio buttons. Depending on the radio buttons that are checked, pressing the submit button will direct you to a different page. Right now im using php with the get option. However the best im able to do is make dynamic pages based of the get info. Any help would be great
Thanks
In your PHP you could check $_GET['radio_option'] and based on the value redirect to other pages using header function, something like this:
switch($_GET['radio_option']) {
case 'val1':
header('location: page1.php');
exit;
case 'val2':
header('location: page2.php');
exit;
case 'val3':
header('location: page3.php');
exit;
}
//here handle everything else - although normally you shouldn't get here
The other alternative would be to use javascript to set the action attribute of the form before it is submitted. For example:
$(document).ready(function() {
$("input:radio[name=your_radio_naem]").click(function() {
var value = $(this).val();
var target = "main.php";
if(value == 'val1')
target = "page1.php";
else if(value == 'val2')
target = "page2.php";
else if(value == 'val3')
target = "page3.php";
$('#myform').attr('action', target);
});
});
Another way would be to set each radio button with a value of the redirect page.
$page=$_GET['radio_buttons'];
header('location: $page');

How to pass the value from my form to another form?

Hello i cannot seem to pass the value from my form to another form .
To explain this i have 3 forms:
alldeals.php
stardealdesc.php
form.php
what i have have done is pass the values from alldeals.php to stardealdesc.php and it work fine. however in stardealdesc.php i have a button that when click will popup a form (form.php)
i wan to make use the values that is parse from alldeals.php to stardealdesc.php to be also parse to formp.php .
This is the pop up codes:
function Popup() {
window.open( 'form.php', "myWindow",
"status = 1, height = 500, width = 500, resizable = 0" )
}
<form>
<input type="button" onClick="Popup()" value="Buy">
</form>
And this is the statement to get the values from alldeals.php
$cmeter = $_REQUEST['cmeter'];
which work fine but i want to take this value and display it in form.php
I believe you mean PASS not PARSE,
You need to store the saved form inputs into the session
session_start();
$_SESSION['form1_values'] = $_POST; // Submitted from form 1
$_SESSION['form2_values'] = $_POST; // Submitted from form 2
$_SESSION['form3_values'] = $_POST; // Submitted from form 3
Then you can refer to those values from any PHP script at any time until the session is cleared
not sure about security terms, but if you want to pass the details on form.php that is displaying in pop window, then use that in url like form.php?username=somename

Prevent resubmit form after click "back" button

I have 2 pages :
page1.php :
- has a form with text box and a "submit" button. Eg : <form name="frm_register" action="page1.php" method="post">
- php and mysql code to store the value of textbox to database. Javascript will redirect the page to php2.php after the value is submitted to database. Eg :
$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query, $connection);
echo '<script language="javascript">window.location="page2.php";</script>';
page2.php
- mysql retrieve the data from database and display on this page.
Problem : When I press "back" button, the browser will pop up a warning message saying that the form will be resubmit. How to prevent resubmit the form when click "back" button? Is it I need to clear the cache of page1.php? How to do it with php or javascript or ajax?
Update 1 : Thanks for the answer of replacing javascript window.location="page2.php" to php header('Location: home2.php');. It fix 80% of problem. The rest of 20% problem show below :
if (strtotime($_SESSION['servertime']) < time()-3){ //10800 = 3 hours 3600 = 1 hour
if (($username != "") AND ($username != $_SESSION[username])){
$_SESSION['servertime'] = $servertime;
$_SESSION['username'] = $username;
$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query20, $connection);
header('Location: page2.php');
exit;
} else {
echo "same name"; //problem here
}
}else{
echo "submit multiple data too fast"; //problem here too.
}
}
The problem happen when do the following steps :
1) User submit data successfully, jump to page2.php view records.
2) User click "back" button, jump back to page1.php.
3) User submit data fail, stay on page1.php. (because too fast or same name)
4) User submit data successful, jump to page2.php view records.
5) User click "back" button, but browser shows warning message "form will be resubmited".
The problem is because of Step 3. Step 3 didn't run header('Location: page2.php');, didn't jump to page2.php. So it cause Step 5 show the warning message. How to fix this problem?
Update 2 : I have figured out the solution to fix the 20% problem, it works perfectly. I use session['error123'] to decide whether or not want to display the error message "same name". I kill session['error123'] if success submit data to database or if success jump to page2.php. I also use header('Location: page1.php'); to redirect to own page (same page) to make the page forget about form submission previously. Example of codes :
if ($_SESSION['error123'] == "toofast"){
echo $_SESSION['error123'] ;
}elseif ($_SESSION['error123'] == "samename"){
echo $_SESSION['error123'] ;
}
if (strtotime($_SESSION['servertime']) < time()-3){ //10800 = 3 hours 3600 = 1 hour
if (($username != "") AND ($username != $_SESSION['username'])){
$_SESSION['username'] = $username;
$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query20, $connection);
$_SESSION['error123'] = "aa";
header('Location: http://localhost/plekz/page2.php');
exit;
} else {
$_SESSION['error123'] = "samename";
header('Location: http://localhost/plekz/page1.php');
exit;
}
}else{
$_SESSION['error123'] = "toofast";
header('Location: http://localhost/plekz/page1.php');
exit;
}
}
}
Note : You need to buffer the output by <?php ob_start();?> because $_SESSION cannot put before header(). Buffer will stop all output including session, let header() send the output first.
Rather than
echo '<script language="javascript">window.location="page2.php";</script>';
you should use the header() function to redirect your user after the submission.
So in psuedo code,
click submit on page.php action page1.php
page1.php submits data to database calls
header('Location: http://example.com/page2.php');
This should prevent your clicking back problem
You can prevent the re-submission by implementing the Post-Redirect-Get (PRG Pattern).
Could be just a one-line if you've got the http_redirect function:
http_redirect("page2.php");
Instead of your javascript echo.
If not, that are two lines:
header("Location: http://example.com/page2.php");
exit;
Replace example.com with site's your hostname.
Related: Back button re-submit form data ($_POST); I am confused about PHP Post/Redirect/Get
One way is to submit the Formdata via Ajax to a remote Script and if the Query returns success you can jump the a "Thank You" Page.
So the User can hit the Back Button and the "Reload" Request doesn't pop up.
Hope the Idea helps you
Can you do it via an Ajax call instead? No action on the form, and the submit will call a the Ajax function. The Ajax call will execute the query, and provide a response (you can just echo a result), and you can then provide dynamic feedback based on the result. You'd never leave the page.
<form id="thisForm">
...form input fields...
<input type="button" onclick="return submitForm('thisForm')"/>
</form>
function submitForm(formId) {
$.ajax( {
type: "post",
url: 'page2.php',
data: $('#' + formId + ' input').serialize(),
... any other Ajax parameters...,
success: function(data) {
}
});
return false;
}
Add this code in the page that is showing as offline when the user clicks the back button:
<?php
session_start();
header_remove("Expires");
header_remove("Cache-Control");
header_remove("Pragma");
header_remove("Last-Modified");
?>
Create a Session like shown here
You should use session and validate the user from every page and you will amaze how SESSION works! AMAZING!

Categories