This question already has answers here:
PHP Redirect with POST data
(13 answers)
Closed 5 years ago.
I'm fairly new to PHP. I have a form that a user is filling in with various details (start date, end date, etc), called purchaseLicence.php. When it is submitted, the form action reloads itself to use PHP to validate the data.
If validation is passed, I want it to navigate to purchaseLicence2.php using the post method, as though the form had originally posted directly to purchaseLicence2.php.
I don't mind involving Javascript to do this, and I'm guess that it would need to be involved as it will end up looking at a different form to the one it would otherwise expect to be on.
This is my current purchaseLicence.php, the problem I get is that both purchaseLicence2.php and purchaseLicence.php are rendered after the form has been posted, and the browser is still pointing to purchaseLicence.php, rather that purchaseLicence2.php.
<?php
include_once('php/strings.php');
include_once('php/sprocs.php');
include_once('php/dates.php');
$encounteredValidationError = false;
$navigateAway=false ;
if (isset($_POST['process']))
{
if ($_POST['process'] == 1)
{
// if here, form has been posted
$ProductCode = $_POST['ProductCode'];
$StartDate = $_POST['StartDate'];
$EndDate = $_POST['EndDateHidden'];
// standardise the date formats to ISO8601
$StartDate = date("Y-m-d", strtotime($StartDate));
$EndDate = date("Y-m-d", strtotime($EndDate));
echo "<descriptive>" . PHP_EOL;
echo "ProductCode:" . $ProductCode . "<br/>" . PHP_EOL;
echo "StartDate:" . $StartDate . "<br/>" . PHP_EOL;
echo "EndDate:" . $EndDate . "<br/>" . PHP_EOL;
echo "</descriptive>" . PHP_EOL;
// validation to happen here
if (!$encounteredValidationError)
{
// so we're happy with the values. The form has just reloaded, so we need to put these back from $_POST into the input fields, so
// that we can call NavigateToPurchaseLicence2(), which will get them out of the input fields and post them to purchaseLicence2.php
// What a faff!
$data = array('ProductCode'=>$ProductCode, 'StartDate'=>$StartDate, 'EndDate'=>$EndDate);
$options = array(
'http'=>array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents('purchaseLicence2.php', false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
}
else
{
// hilite errors in the form here, how? form is not yet loaded
}
}
}
?>
</head>
<body>
<form method="post" action="purchaseLicence.php" id="form1">
<input type="hidden" name="process" value="1">
<table border=0 width=800px align=left style="margin: 0px auto;">
<tr> <!-- Product > -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Product</descriptive></td>
<td width="500px" bgcolor="lightgray">
<?php
// creates a dropdown of products
OutputSelectFromSQL("SELECT * FROM Product ORDER BY Description", "ProductCode", "ProductCode", "Description", "");
?>
</td>
</tr>
<tr> <!-- Licence Period -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Licence Period</descriptive></td>
<td width="500px" bgcolor="lightgray"><descriptive>1 year</descriptive></td>
</tr>
<tr> <!-- Start Date -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Start/End Dates</descriptive></td>
<td width="500px" bgcolor="lightgray">
<input type="date" style="font-family:verdana;font-size:12px;" name="StartDate" id="StartDate" onchange="updateEndDate(this.value);"></input>
<descriptive> to <a id="EndDate"></a></descriptive>
<input type="hidden" name="EndDateHidden" id="EndDateHidden"></input> <!-- this is used so we can post the end date to $_POST -->
</td>
</tr>
<tr> <!-- Next > -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive></descriptive></td>
<td width="500px" bgcolor="lightgray" align="right"><input type="submit" value="Next"></input></td>
</tr>
</table>
</form>
</body>
A simple example for a standard pattern to follow would be really useful.
I suggest you use $_SESSION to hold state between your forms, below is a very crude example, with 1 field on the first form which if good (numeric) , the entire form state is set into the session, then redirects to the second form to fill out additional fields. Very simple but you get the idea.
dataentry1.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// define form state
$form = [
'value' => $_POST,
'error' => []
];
// validate a_field
if (empty($form['value']['a_field'])) {
$form['error']['a_field'] = 'a_field is a required field!';
} elseif (!is_numeric($form['value']['a_field'])) {
$form['error']['a_field'] = 'a_field should be a number!';
}
// all good
if (empty($form['error'])) {
$_SESSION['form'] = $form;
exit(header('Location: dataentry2.php'));
}
}
?>
<?= (!empty($form['error']['global']) ? $form['error']['global'] : null) ?>
<form action="/dataentry1.php" method="post">
<lable>a_field:</lable>
<input type="text" name="a_field" value="<?= (isset($form['value']['a_field']) ? htmlentities($form['value']['a_field']) : null) ?>">
<?= (!empty($form['error']['a_field']) ? '<br>'.$form['error']['a_field'] : null) ?>
<br>
<input type="submit" value="Submit">
</form>
dataentry2.php - requires the previous form to be filled out.
<?php
session_start();
// set form into scope from session
if (!empty($_SESSION['form'])) {
$form = $_SESSION['form'];
} else {
$_SESSION['form']['error']['global'] = 'You must fill out dataentry1 form first';
exit(header('Location: dataentry1.php'));
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// define form state
$form = [
'value' => array_merge($form['value'], $_POST),
'error' => []
];
// validate a_field
if (empty($form['value']['b_field'])) {
$form['error']['b_field'] = 'b_field is a required field!';
} elseif (!is_numeric($form['value']['b_field'])) {
$form['error']['b_field'] = 'b_field should be a number!';
}
// all good
if (empty($form['error'])) {
exit('Do something cool!');
}
}
?>
<form action="/dataentry2.php" method="post">
<lable>a_field:</lable>
<input type="text" name="a_field" value="<?= (isset($form['value']['a_field']) ? htmlentities($form['value']['a_field']) : null) ?>" readonly="readonly">
<?= (!empty($form['error']['a_field']) ? '<br>'.$form['error']['a_field'] : null) ?>
<lable>b_field:</lable>
<input type="text" name="b_field" value="<?= (isset($form['value']['b_field']) ? htmlentities($form['value']['b_field']) : null) ?>">
<?= (!empty($form['error']['b_field']) ? '<br>'.$form['error']['b_field'] : null) ?>
<br>
<input type="submit" value="Submit">
</form>
Related
EDIT
I have implemented the changes suggested and I still cant get this to work:
Form Page Follows (login.php)
<?php
$mac=$_POST['mac'];
$ip=$_POST['ip'];
$username=$_POST['username'];
$linklogin=$_POST['link-login'];
$linkorig=$_POST['link-orig'];
$error=$_POST['error'];
$chapid=$_POST['chap-id'];
$chapchallenge=$_POST['chap-challenge'];
$linkloginonly=$_POST['link-login-only'];
$linkorigesc=$_POST['link-orig-esc'];
$macesc=$_POST['mac-esc'];
if (isset($_POST['postcode'])) {
$postcode = $_POST['postcode'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
?>
**SOME HTML HERE**
<script src="jquery-3.2.1.min.js"></script>
<script>
var js-postcode = document.login.getElementsByName("postcode").value;
var js-email = document.login.getElementsByName("email").value;
var formdata = {postcode:js-postcode,email:js-email};
$("button").click(function(){
$.ajax(
{
type: "POST",
url: "database.php", //Should probably echo true or false depending if it could do it
data : formdata,
success: function(feed) {
if (feed!="true") {
// DO STUFF
} else {
console.log(feed);
// WARNING THAT IT WASN'T DONE
}
}}}
</script>
</head>
<body>
<table width="100%" style="margin-top: 10%;">
<tr>
<td align="center" valign="middle">
<table width="240" height="240" style="border: 1px solid #cccccc; padding: 0px;" cellpadding="0" cellspacing="0">
<tr>
<td align="center" valign="bottom" height="175" colspan="2">
<!-- removed $(if chap-id) $(endif) around OnSubmit -->
<form name="login" action="<?php echo $linkloginonly; ?>" method="post" onSubmit="return doLogin()" >
<input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
<input type="hidden" name="popup" value="true" />
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php echo $username; ?>"/></td>
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><button><input type="submit" value="OK" /></button></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
document.login.username.focus();
//-->
</script>
</body>
</html>
and called file database.php is as follows:
<?php
if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {
$postcode = $_POST['postcode'];
$email = $_POST['email'];
$connect= new mysqli_connect('xx','xx','xx','xx');
if ($conn->connect_errno) {
echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(postcode,email)"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
//NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.
if (!$sql->bind_param("ss", $postcode, $email)) {
echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
}
if (!$sql->execute()) {
echo "Execute failed: (" . $sql->errno . ") " . $sql->error;
}
} else {
echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.
}
?>
Still I get nothing fed through from the form to the database. Even if I swap the variables for strings I get nothing through to the database however if I run database.php separately it works. Surely Im close to getting this working now .. any help appreciated and thanks so much for the assistance provided so far.
*************************** ORIGINAL QUESTION FOLLOWS *******************
I have a simple form as follows:
<form name="login" action="somethingelse.php" method="post" onSubmit="return doLogin()" >
<input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
<input type="hidden" name="popup" value="true" />
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php e$
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><button><input type="submit" value="OK" /></button></td>
</tr>
</table>
</form>
Because I need to use the form action to do something else, I need to use jQuery on the click of the button to send data to a database. Specifically the postcode and email address taken from the form. The part of the code relating to the jQuery is shown below:
<script language="JavaScript" >
$(document).ready(function(){
$("button").click(function(){
mysqli_query();
});
});
</script>
The called function mysqli_query is declared via an include statement and therefore lives in a different file. The function called is shown below:
mysqli_query( $connect, "INSERT INTO visitors(postcode,email) VALUES(postcode,email)");
I have been going round in circles for days with this. I know Im close to making it work but cant quite cross the finish line. Could somebody please point out what I'm doing wrong here?
WARNING: Never ever trust user input, always sanitize the input first AND use prepared statements otherwise, you're leaving youself vulnerable to SQL INJECTION ATTACKS
You're mixing up, Javascript is a clientside language, and mysqli is a PHP based function on the serverside of things.
What you should be doing is an ajax call with the values to a different PHP file that will make the database connection and insert the data.
var dataString = "postcode="+ postcode+"&email="+email;
$.ajax({
type: "POST",
url: "file_that_does_the_work.php", //Should probably echo true or false depending if it could do it
data: dataString,
success: function(feed) {
if (feed=="true") {
// DO STUFF
} else {
console.log(feed);
// WARNING THAT IT WASN'T DONE
}
}
file_that_does_the_work.php
<?
include("config.php"); // your thing that configures the connection
$postcode = sanitizationfunction($_POST["postcode"]);
$email = sanitizationfunction($_POST["email"]);
$query = $connection->prepare('INSERT INTO visitors(postcode,email) VALUES(?,?)');
$query->bindParam(1, $postcode);
$query->bindParam(2, $email);
if ($query->execute()) {
echo "true";
} else {
echo "false";
}
?>
form.php
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php echo $username?>"/>
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><input type="submit" value="OK" /></td>
</tr>
</table>
</form>
`
somethingelse.php
<?php
foreach ($_POST as $key => $value) {
echo $key."=".$value."<br/>";
}
?>
I leave connectivity part to you :D
So, as others have pointed out, you are mixing up your client-side code and your server-side code. You need to send all the form data to a php file. The jquery ajax will send the data over to the script, and determine if this call was successful or not. If the call is not successful, you can run test logic. If it is, than you can do other logic, such as alert the user of a successful form submit.
Below is an example of the process:
ajax:
<script>
var formData = 'some data' // Get your form values and save here - postcode and email
$("button").click(function(){
$.ajax ({
method: 'POST',// you can do either post or get...
url: "page_to_handle_mysql_code.php",
data: formData
success: function( response ) {
//do something like alert("Submitted Successfully!");
}
fail: function( response) {
//Do testing such as console.log(response); NOTE: Response will be what ever your php page sends back.
}
});
)};
</script>
On your php page: page_to_handle_mysql_code.php
<?php
if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {
$postcode = $_POST['postcode'];
$email = $_POST['email'];
//connect to mysql - I prefer prepared statements as the variables are prepared for safety when sent to MySQL
$conn = new mysqli($servername, $username, $password, $dbname);//you can either put the actually values in, or I include another php page in this one that sets my variables so I can resuse my code easily.
if ($conn->connect_errno) {
echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(?,?)"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
//NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.
if (!$sql->bind_param("ss", $postcode, $email)) {
echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
}
if (!$sql->execute()) {
echo "Execute failed: (" . $sql->errno . ") " . $sql->error;
}
} else {
echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.
}
?>
This should help you get your values entered to MySQL. I hope it helps!
You can submit a form with jquery
mysqli_query is a function in your PHP, your javascript doesn't have access to the function. You have to make an http call from your javascript, which your PHP will receive and run mysqli_query on its end
I want to fill the form and able to return back to modify the records. But when I return back I want the form to have the previous values. when I put " />
I got error.
please help
Thank you!
My code
<?php
if (isset($_POST['submit'])) {
$from = 'hello#gmail.com';
$subject = $_POST['subject'];
$text = $_POST['elvismail'];
$output_form = false;
if(empty($subject) && empty($text)) {
echo 'You forgot the email subject and body text.<br />';
$output_form = true;
}
if (empty($subject) && (!empty($text))) {
echo 'You forgot the email subject.<br />';
$output_form = true;
}
if ((!empty($subject)) && empty($text)) {
echo 'You forgot the email body text.<br />';
$output_form = true;
}
if ((!empty($subject)) && (!empty($text))) {
if(isset($_POST['cancel'])) {
echo "cancel";
}
else if(isset($_POST['send'])) {
echo "submit";
}
?>
<form method="post" action="index.php">
<table>
<tr>
<td>Subject of email</td>
<td> <?php echo $subject; ?> </td>
</tr>
<tr>
<td>Body of email</td>
<td><?php echo $text ?> </td>
</tr>
</table>
<input type="submit" name="cancel" value="cancel" />
<input type="submit" name="send" value="Submit" />
</form>
<?php
}
}
else {
$output_form=true;
}
if ($output_form) {
?>
<form method="post" action="index.php">
<label for="subject">Subject of email:</label><br />
<input id="subject" name="subject" type="text" size="30" /><br />
<label for="elvismail">Body of email:</label><br />
<textarea id="elvismail" name="elvismail" rows="8" cols="40"></textarea><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
}
?>
In this scenario its much better to use client side resources rather than storing it again on php. Because it is just a temporary value and using Local Storage would benefit you alot.
Javascript or JQuery would be the best approach to accomplish this.
Step 1 : Store the value on LocalStorage after on blur of every input on the form.
Step 2 : When user gets back to page. Simply assign the last data you saved on the localStorage
Because if you refresh the page you will lose the data variables in your php and will require to fetch it again on the database thus resulting on the same data values.
I suggest you read about the LocalStorage and read about controlling inputs with JQuery.
x = $("#form").serialize();
localStorage.setItem("temp_form_data" , x);
// To retrieve it simply convert it to JSON and assign it to each inputs.
var temp = JSON.parse(localStorage.getItem("temp_form_data"));
$("your-input-target").value(temp.id);
$("other-input-target").value(temp.description);
//and so on
This is just what would the implementation look like for setting and getting input data.
I want to add users present in a given table. I am iterating whole table and sending each value to javascript file.
<?php
$sql = "select * from user where user_id not in (select second_user_id from friends where first_user_id = '$user_id'\n"
. " union\n"
. " select first_user_id from friends where second_user_id = '$user_id') limit 20";
$result_not_friends=mysqli_query($dbc,$sql)
or die("error in fetching");
// print_r($row_not_friends);
?>
<table class="table table-hover table-bordered">
<h1>Users</h1>
<tbody>
<?php
while ( $row_not_friends = mysqli_fetch_array($result_not_friends))
{
if ( $row_not_friends['user_id'] != $user_id )
{
?>
<tr>
<td>
<?php echo $row_not_friends['user_name']; ?>
</td>
<!-- here I am sending request and processing it via ajax -->
<td><i class="fa fa-user-plus send_request"></i></td>
<input type="hidden" class="send_second" value="<?php echo $row_not_friends['user_id']; ?>">
<input type="hidden" class="send_first" value="<?php echo $user_id; ?>">
</tr>
<?php
}
}
?>
</tbody>
</table>
Now I am accessing each value in a javascript file as follow:
// Here a request is send
$('.send_request').on('click',
function (e) {
e.preventDefault();
var first = $('.send_first').val();
var second = $('.send_second').val();
alert('firt id is ' + first);
alert('second id is ' + second);
$.ajax(
{
url:'send_process.php',
type:'POST',
dataType:"json",
data: { first: first, second: second },
success:function(data)
{
if(data.send_success)
{
window.location.href = "friend.php";
}
else
{
alert("something went wrong");
window.location.href = "friend.php";
}
},
error : function() { console.log(arguments); }
}
);
});
But here var second = $('.send_second').val(); gives only top-most element value of $row_not_friends['user_id'] . When I am echoing the value, it gives correct result.
Please help me.
Because you are selecting ALL the elements in the page and the default behavior of val() is it returns the first item. It has no clue you want the nth item.
First thing is you need to fix your HTML it is invalid. You can not have an input as a sibling of a tr element. You need to move it inside of a TD.
<!-- here I am sending request and processing it via ajax -->
<td><i class="fa fa-user-plus send_request"></i> <!-- removed the closing td from here -->
<input type="hidden" class="send_second" value="<?php echo $row_not_friends['user_id']; ?>">
<input type="hidden" class="send_first" value="<?php echo $user_id; ?>"></td> <!-- moved the closing td to here -->
</tr>
You need to find the elements in the same row as the button you clicked. Since the hidden inputs are npw siblings of the button you can use the siblings() method.
var btn = $(this);
var first = btn.siblings('.send_first').val();
var second = btn.siblings('.send_second').val();
I am working on a web site which displays some data that is retrieved from a database using php. Now, there are also other chekcboxes, which are included in a form. Based on the user input on these checkboxes, i wanted the div displaying the data to reload. For example, after a user checks one of the boxes and clicks apply, the div displaying should recompute the results. I realise that the form data must be passed onto an ajax function. Which would convert this form data into a json object and send it across to a php file. The php file can then access the form variables using $_POST['var']. I hope i have got the theory correct. Nevertheless, i have a number of problems during execution.
Firstly, the php code that deals with the form variables in on the same page as the form. I want to know how to direct the form data from the ajax function to this code.
Secondly, the ajax function is getting executed alright, the form is getting submitted, the page isn't reloading (as desired) but however, I am not able to access the submitted variables in the php code.
Here is my code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#filter_form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
}
});
e.preventDefault();
});
});
</script>
<div style="float: left;margin-left: -175px;" class="box2">
<h2>Filter by :</h2>
<form id="filter_form" name="filter_form" href="#">
<!--<form id="filter_form" name="filter_form" action="<?php echo $_SERVER['PHP_SELF'];?>" method ="post" href="#">-->
<h3>Location</h3>
<?php
//Get all the distinct values for filter. For example, Get all the locations available, display them in a container. Similarly for the party type as well. Connect to to the database once, get all these values,
//store them in arrays and use the arrays to display on screen.
$query = "Select LOCATION, PARTY_TYPE, GENRE, HAPPY_HOURS, OUTDOOR_ROOFTOP from venue_list order by HAPPY_HOURS";
$result = mysqli_query($con,$query);
$filter_array = array(5);
for($i=0; $i<5; $i++){
$filter_array[$i] = array();
}
while($row = mysqli_fetch_array($result)){
array_push($filter_array[0],$row['LOCATION']);
array_push($filter_array[1],$row['PARTY_TYPE']);
array_push($filter_array[2],$row['GENRE']);
array_push($filter_array[3],$row['HAPPY_HOURS']);
array_push($filter_array[4],$row['OUTDOOR_ROOFTOP']);
}
for($i=0; $i<5; $i++){
$filter_array[$i] = array_unique($filter_array[$i]);
}
?>
<ul>
<?php
foreach($filter_array[0] as $location){
?>
<li>
<input type="checkbox" id="f1" name="location[]" value="<?php echo $location?>" <?php if (isset($_POST['location'])){echo (in_array($location,$_POST['location']) ? 'checked' : '');}?>/>
<label for="f1"><?php echo $location?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Party Type</h3>
<ul>
<?php
foreach($filter_array[1] as $party_type){
?>
<li>
<input type="checkbox" id="f2" name="party_type[]" value="<?php echo $party_type?>" <?php if (isset($_POST['party_type'])){echo (in_array($party_type,$_POST['party_type']) ? 'checked' : '');}?>/>
<label for="f2"><?php echo $party_type?></label>
</li>
<?php
}
?>
</ul>
<br><h3>Genre</h3>
<ul>
<?php
foreach($filter_array[2] as $genre){
?>
<li>
<input type="checkbox" id="f3" name="genre[]" value="<?php echo $genre?>" <?php if (isset($_POST['genre'])){echo (in_array($genre,$_POST['genre']) ? 'checked' : '');}?>/>
<label for="f3"><?php echo $genre?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Happy Hours</h3>
<ul>
<?php
foreach($filter_array[3] as $happy_hours){
?>
<li>
<input type="checkbox" id="f4" name="happy_hours[]" value="<?php if($happy_hours){ echo $happy_hours;} else {echo "Dont Bother";} ?>" <?php if (isset($_POST['happy_hours'])){echo (in_array($happy_hours,$_POST['happy_hours']) ? 'checked' : '');}?>/>
<label for="f4"><?php echo $happy_hours?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Outdoor/Rooftop</h3>
<ul>
<?php
foreach($filter_array[4] as $outdoor_rooftop){
?>
<li>
<input type="checkbox" id="f5" name="outdoor_rooftop[]" value="<?php echo $outdoor_rooftop?>" <?php if (isset($_POST['outdoor_rooftop'])){echo (in_array($location,$_POST['outdoor_rooftop']) ? 'checked' : '');}?>/>
<label for="f5"><?php echo $outdoor_rooftop?></label>
</li>
<?php
$i=$i+1;
}
?>
</ul>
<br><br><br>
<div id="ContactForm" action="#">
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
</div>
<!--
<h2>Sort by :</h2>
<input type="radio" id="s1" name="sort" value="Name" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Name')?'checked':'';}?>/>
<label for="f1"><?php echo 'Name'?></label>
<input type="radio" id="s1" name="sort" value="Location" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Location')?'checked':'';}?>/>
<label for="f1"><?php echo 'Location'?></label>
<br><br><br>
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
-->
</form>
</div>
<div class="wrapper">
<h2>Venues</h2>
<br>
<div class="clist" id="clublist" href="#">
<?php
?>
<table id = "venue_list">
<tbody>
<?php
//Functions
//This function builds the query as every filter attribute is passed onto it.
function query_builder($var_name){
$append = strtoupper($var_name)." in (";
$i=0;
foreach($_POST[$var_name] as $array){
$append = $append."'{$array}'";
$i=$i+1;
if($i < count($_POST[$var_name])){
$append = $append.",";
}
else{
$append=$append.")";
}
}
return $append;
}
//We first need to check if the filter was set in the previous page. If yes, then the query needs to be built with a 'where'. If not the query will just display all values.
//We also need to check if order by is required. If yes, we will apply the corresponding sort, else we will just sort on the basis of location.
//The below 2 variables do the same.
$filter_set = 0;
$filter_variables = array('location','party_type','genre','happy_hours','outdoor_rooftop');
$map_array = array();
if(isset($_POST['location'])){
$filter_set = 1;
}
if(isset($_POST['party_type'])){
$filter_set = 1;
}
if(isset($_POST['genre'])){
$filter_set = 1;
}
if(isset($_POST['happy_hours'])){
$filter_set = 1;
}
if(isset($_POST['outdoor_rooftop'])){
$filter_set = 1;
}
if($filter_set == 1){
$query = "Select * from venue_list where ";
$append_query=array(5);
$j=0;
foreach($filter_variables as $var){
if(isset($_POST[$var])){
$append_query[$j] = query_builder($var);
$j=$j+1;
}
}
$h=0;
//Once all the individual where clauses are built, they are appended to the main query. Until then, they are stored in an array from which they are
//sequentially accessed.
foreach($append_query as $append){
$query=$query.$append;
$h=$h+1;
if($h < $j){
$query=$query." AND ";
}
}
}
else{
$query = "Select * from venue_list";
}
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$name = $row['NAME'];
$img = $row['IMAGE_SRC'];
$addr = $row['ADDRESS'];
$location = $row['LOCATION'];
echo "<script type='text/javascript'>map_function('{$addr}','{$name}','{$img}');</script>";
?>
<tr>
<td>
<img src="<?php echo $img.".jpg"?>" height="100" width="100">
</td>
<td>
<?php echo $name?>
</td>
<td style="display:none;">
<?php echo $location?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<br>
</div>
All the 3 components are part of index.php. Kindly notify me if the code is unreadable or inconvenient I will edit it. Awaiting a solution. Thank you.
in this case change your javascript code to
var submiting = false;
function submitmyforum()
{
if ( submiting == false )
{
submiting = true;
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
submiting = false;
}
});
}else
{
alert("Still working ..");
}
}
and change the form submit button to
<input name="filter_button" type="button" onclick="submitmyforum();" value="Apply" id="filter_button" class="button"/>
don't forget to change submit button type="submit" to type="button"
I really don't have any idea with this problem. I create new plug-in. Structure is easy:
div FreeQuotation_wrap2 (display the table), div FreeQuotation_wrap3 (insert new data). But after write new data and click submit page is refresh with old data.
When I click refresh I see information that it will resend data to database. It's ok- I prevent it with unique. Now I see new table with new record. How can I make it automatically?
I try 3 methods: onSubmit="" (doesn't work) and javascript (window.location = "...") and trick with session (i get error - headers already sent by...).
<?php
global $FreeQuotation_version;
global $wpdb;
echo $table_name;
global $today_date;
$table_name = $wpdb->prefix . 'free_quotation_kic';
?>
<div class="FreeQuotation_wrap">
<h2><div class="FreeQuotation_header"></div> FreeQuotation <?php echo $FreeQuotation_version; ?></h2><br>
</div>
<div class="FreeQuotation_wrap2">
<table class="widefat">
<?php
$FreeQuotation_table = $wpdb->get_results(
"
SELECT *
FROM $table_name
ORDER BY adding_date DESC
LIMIT 0 , 10
"
);
//nagłówek
echo '<thead><tr><th> ID </th><th> Quotation </th><th> Author </th><th> Display Date </th><th> Delete </th></tr></thead>';
//treść
foreach ( $FreeQuotation_table as $ogresults )
{
echo '<tr><td>';
echo $ogresults->id;
echo '</td><td>';
echo $ogresults->quotation;
echo '</td><td>';
echo $ogresults->author;
echo '</td><td>';
echo $ogresults->display_date;
echo '</td></tr>';
}
echo '<tfoot><tr><th> ID </td><th> Quotation </td><th> Author </td><th> Display Date </th><th> Delete </td></tr></tfoot>';
?>
</table>
</div>
<div class= "FreeQuotation_wrap3">
<form method="post" action="options.php">
<?php settings_fields('FreeQuotation_settings_filed'); ?>
<?php $options = get_option('FreeQuotation_options'); ?>
</form>
<?php
global $current_user;
$ufUserID = $current_user->ID;
$quotation = $_POST["quotation_textarea"];
$author = $_POST["autor_text"];
$display_date = $_POST["display_date"];
$url = $_SERVER['PHP_SELF'];
$adding_date = $today_date;
echo $url;
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'updateFeedback' ) {
$FreeQuotation = $wpdb->insert( 'wp_free_quotation_kic', array( 'quotation' => $quotation, 'author' => $author, 'display_date' => $display_date, 'adding_date' => $adding_date,) );
}?>
TUTAJ
<h3 class="widget-title">Add quotation</h3>
<form id='reloader' method='post' onSubmit="<?php echo $url;?>">
<table class="widefat" >
<thead>
<tr><th>Quotation</th><th>Author</th><th>Display Date</th></tr>
</thead>
<tbody>
<tr><td>
<textarea rows="1" cols="100" name="quotation_textarea" required></textarea>
</td>
<td>
<input type="text" name="autor_text" required></input>
</td>
<td>
<input type="text" name="display_date" required></input>
</td></th>
</tbody>
<tfoot>
<tr><th>
<input class="button button-primary" type="submit" name="submit" value="submit"/>
<?php wp_nonce_field( 'updateFeedback' ); ?>
<input name="action" type="hidden" id="action" value="updateFeedback"/>
</th></td>
</tfoot>
</table>
</form><br>
</div>
<div class="FreeQuotation_wrap4">
<h3>Zmiany:</h3>
</div>
<?php
?>
Can you help me? It's my first question hire (and I believe that the last...). Usually when I try to write a question I find the answer quickly :) Now I spend few hours with this problem and I doesn't see any solution...
I find simple solution - it's very easy and it's work. Maybe it's not professional but I don't have any other idea...
I change the order on the page. First is the form to add new position, the second is now the table with output. It means that I change two order:
<div class= "FreeQuotation_wrap3">
...
</div>
<div class="FreeQuotation_wrap2">
...
</div>
And this is my first answer on stackoverflow.com ;-)