I created block wchich you can add in it dynamically a multiple names. When I cick save, and return to the block editing, I dont see my new added names. I think that is problem with save to database. Please can someone help me with it?
Here is my code:
controller.php:
<?php defined('C5_EXECUTE') or die("Access Denied.");
Loader::block('library_file');
class MultipleBlockController extends BlockController {
protected $btName = 'Multiply TEST';
protected $btDescription = 'Multiple add. TEST';
protected $btTable = 'btDCMultiple';
protected $btInterfaceWidth = "700";
protected $btInterfaceHeight = "450";
}
db.xml:
<?xml version="1.0"?>
<schema version="0.3">
<table name="btDCMultiple">
<field name="bID" type="I">
<key />
<unsigned />
</field>
<field name="inputs" type="C" size="16"></field>
</table>
</schema>
edit.php:
<?php defined('C5_EXECUTE') or die("Access Denied.");
?>
<?php
$remove_row_icon = '<img src="'.ASSETS_URL_IMAGES.'/icons/remove_minus.png" class="remove_row" height="14" width="14" >';
$add_row_icon = '<img src="'.ASSETS_URL_IMAGES.'/icons/add_small.png" class="add_row" height="14" width="14" >';
?>
<!-- Zakladki -->
<ul id="ccm-autonav-tabs" class="ccm-dialog-tabs">
<li class="ccm-nav-active"><a id="ccm-autonav-tab-add" href="javascript:void(0);"><?php echo t('Edit')?></a></li>
</ul>
<!-- Odstep konfiguracja -->
<div style="padding: 10px">
<div class="ccm-autonavPane" id="ccm-autonavPane-add">
<h2>debug</h2>
<table>
<tr><td><?php echo 'Name';?></td><td></td></tr>
<?php
foreach($inputs as $a_name) { ?>
<tr>
<td><input type="text" size="10" name="inputs" value="<?php echo $a_name ?>" ></td>
<td><?php echo $add_row_icon; echo (' '); echo $remove_row_icon;?></td>
</tr>
<?php } ?>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.add_row').live('click',function(){
var copy_of_row = $(this).closest('tr').clone();
$(copy_of_row).find('input').val('');
$(this).closest('tr').after(copy_of_row);
});
$('.remove_row').live('click',function(){
$(this).closest('tr').remove();
});
});
</script>
view.php:
<?php defined('C5_EXECUTE') or die("Access Denied.");
?>
<div>
<?php echo $inputs ?>
</div>
Another question: How can I load an array from the DB?
You have several problems in your code:
if your field inputs is going to repeat itself, you need to add
brackets [] to its name so it becomes name="inpust[]"
In your database table, the field bID contains the block ID and it's a key
field meaning only one row in your db can have that value. In your
case, if you have 3 inputs, you will have 3 rows with the same bID
which is impossible.
I suggest you look at the core slideshow block for an example of saving multiple values for one block by using 2 separate tables.
Concerning your other question once you load the database helper you can do
$rows = $db->getArray($sql,$vals);
Where $rows will contain your array of values, $sql is your sql call (SELECT * FROM whatever_table...) and $vals (optional) contains filtering values to use in your sql.
Related
I searched this website and couldn't find an answer.
I have a php page that display a dropdown list with 2 choices. When on change, a Javascript execute a function that opens a php page to update my database, sending the ID and another parameter with the URL. The problem is the ID value is always the same (the last of the list). Can you help me please, I am very new in PHP and Javascript. Thank you in advance. Here is the PHP code and the javascript:
<?php
$AvailabilityCondition = "1=1";
if ((isset($_POST["availabilityChoice"])) && ($_POST["availabilityChoice"] !== "All")){
$AvailabilityCondition = "rented = "."'".$_POST["availabilityChoice"]."'";
}
$rentalquery = "SELECT * FROM rentals WHERE $AvailabilityCondition ORDER BY region_name, rental_name";
if ($rentalresult = $link->query($rentalquery)) {
/* fetch associative array */
while ($rowrentals = $rentalresult->fetch_assoc()) {
$NumberOfResults = $rentalresult->num_rows;
?>
<!-- ************************* This display a table with a short rental description (Region name - Rental name)
****************************** with and EDIT link, a DELETE link and an AVAILABILITY selector. ******************* -->
<div align="center">
<table >
<tr >
<td width="300" >
<?php echo ($rowrentals["region_name"]).' - '.($rowrentals["rental_name"]).'<br/>'; ?>
</td>
<td width="50">
EDIT
</td>
<td width="100" align="right">
<!-- *********** This form display the actual availability state. On change, it updates the database **************** -->
<form name="updateAvailability" method=POST" class="form-horizontal" >
<select onChange="showSelected(this.value)" id ="availabilityChoice" name="availabilityChoice" style="width: auto">
<option value="No" <?php if (($rowrentals["rented"]) == "No") echo 'selected="selected"' ?>>Available</option>
<option value="Yes" <?php if (($rowrentals["rented"]) == "Yes") echo 'selected="selected"' ?>>Rented</option>
</select> <?php echo ($rowrentals["id"]) ?>
</form>
<script type="text/javascript">
function showSelected(val){
document.getElementById ('availabilityChoice').innerHTML = val;
window.location.replace("status-update.php?rented=" + val + "&id=<?php echo ($rowrentals["id"]) ?>");
}
</script>
<!-- **************************************************************************************************************** -->
</td>
<td>
!!! DELETE !!!
</td>
</tr>
</table>
</div>
<?php
}}
/* free result set */
$rentalresult->free();
/* close connection */
$link->close();
?>
<br/><br/>
<div align="center">
<b>Back to Managers Main Menu</b>
</div>
</body>
I just posted more of my PHP page. So you can see the query and the WHILE, where $rowrentals["id"] is coming from.
Here is also a screen capture of how the page looks like: screen capture
I echoed the $rowrentals["id"] under each availability dropdown.
But whatever row I chose to change the availability, it always pass Id=9, the last one. That is what confuses me.
Before the screen capture, all five rows where "Available". Then I selected "Rented" on the first row. The page updated and since Id always =9, you can see the last row "Rented".
The Javascript is working to retrieve the value of the selected item. Because it opens this page perfectly: status-update.php?rented=Yes&Id=9
But again, Id is always 9...
Try with this:
<script type="text/javascript">
function showSelected(val){
document.getElementById ('availabilityChoice').innerHTML = val;
window.location.replace("status-update.php?rented=" + val + "&id=<?php echo ($rowrentals['id']) ?>");
}
If showSelected javascript function inside a foreach/while loop you need to extract it from loop and send id+value at the same time to showSelected function.
Thank you everybody. I found my answer. I added a counter, so this create a different function name for each database Id.
Here is the code:
$rentalquery = "SELECT * FROM rentals WHERE $AvailabilityCondition ORDER BY region_name, rental_name";
$counter =0;
if ($rentalresult = $link->query($rentalquery)) {
/* fetch associative array */
while ($rowrentals = $rentalresult->fetch_assoc()) {
$NumberOfResults = $rentalresult->num_rows;
$counter = $counter+1;
?>
<!-- ************************* This display a table with a short rental description (Region name - Rental name)
****************************** with and EDIT link, a DELETE link and an AVAILABILITY selector. ******************* -->
<div align="center">
<table >
<tr >
<td width="300" >
<?php echo ($rowrentals["region_name"]).' - '.($rowrentals["rental_name"]).'<br/>'; ?>
</td>
<td width="50">
EDIT
</td>
<td width="100" align="right">
<!-- *********** This form display the actual availability state. On change, it updates the database **************** -->
<form name="updateAvailability<?php echo $counter ?>" method=POST" class="form-horizontal" >
<select onChange="showSelected<?php echo $counter ;?>(this.value)" id ="availabilityChoice<?php echo $counter ?>" name="availabilityChoice<?php echo $counter ?>" style="width: auto">
<option value="No" <?php if (($rowrentals["rented"]) == "No") echo 'selected="selected"' ?>>Available</option>
<option value="Yes" <?php if (($rowrentals["rented"]) == "Yes") echo 'selected="selected"' ?>>Rented</option>
</select>
</form>
<script type="text/javascript">
function showSelected<?php echo $counter ;?>(val){
document.getElementById ('availabilityChoice<?php echo $counter ;?>').innerHTML = val;
window.location.replace("status-update.php?rented=" + val + "&id=<?php echo ($rowrentals["id"]) ?>");
}
</script>
I'm working on a project of a website which shows a chart. User should be able to change a displayed chart (without changing the website) by clicking one of 'Available sensors' from dropdown options. Dropdown connects to MySQL database with used sensors. The sensor's id is assigned to HTML-input ID and its name is assigned to input value.
My intension is to use sensor ID in another data.php file which is responsible for connecting to tables (MySQL) with data collected by sensors. This ID would tell to which of the tables this programm should connect.
At the moment JS script's task is to alert an ID of the chosen sensor when it's clicked on the dropdown menu. Instead of a number I get a message saying 'undefined'. Eventually it would transfer the stored id to the mentioned data.php file.
Could you please tell me whether it's necessary to use AJAX in this case or what's a possible reason of this error in my code?
I also tried to use button insted of input. When clicking on sensors names on dropdown I've received only messages with '1'. However assigning sensorName worked out in both cases. Sensors ID is stored as INT, name as VARCHAR in MySQL table.
Thank you in advance for your help :)
<div id="header_btn" class="dropdown">
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?>
<input onclick="changeSensorID(this.value)" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>" value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script>
function changeSensorID() {
var sensorID = document.getElementsByClassName("btn_drop").id;
alert(sensorID);
};
</script>
</div>
please check this code, working fine
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?><input onclick="changeSensorID(event)" onmouseover="this.style.textDecoration='underline'"
onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>"
value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script >
function changeSensorID(event){
var sensorID = event.target.id;
alert(sensorID);
}
</script>
</div>
getElementsByClassName returns array of at least one item if found any. You have to provide index of element that you want to use.
Example
var sensorID = document.getElementsByClassName("btn_drop")[0].id;
so I'm making a pagination which uses 3 different files. The page itself (index.php), the header which contains a JS Ajax scripts for changing page which is included in the index.php (header.php) and a pagination script contained in a separate PHP file which is called via the AJAX script (pagination.php).
In the index.php I have a variable which defines the category the user is currently in named $category, I would like this variable to be used in the pagination.php to select what results are shown (Only results where subcategory2 = $category).
Because pagination.php is called through an ajax script on document ready it can't see that variable. Is there any way for the two to communicate without the use of Session (which would mess up when changing to other categories) or include (which would end up calling the script twice).
Header.php:
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("/includes/pagination.php");
$(".pagination").bootpag({
total: <?php echo $pages; ?>,
page: 1,
maxVisible: 5
}).on("page", function(e, num){
e.preventDefault();
$("#results").prepend('<div class="loading-indication"><img src="/images/ajax-loader.gif" style="width: 2em; margin: 0 auto;" /><br />Loading...</div>');
$("#results").load("/includes/pagination.php", {'page':num});
});
});
</script>
Pagination.php
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
//sanitize post value
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
$page_number = 1;
}
echo $category;
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($mysqli, "SELECT ProductID, SupplierID, ProductName, ProductDesc, ProductURL, Image1URL, Image2URL, Image3URL, Image4URL, Image5URL, ProductCondition, Stock, AvailabilityDate, ProductGTIN, ProductMPN, ProductBrand, ProductGroupID, ProductColour, ProductGender, ProductAgeGroup, ProductMaterials, ProductSize, ProductPSize, Feature1, Feature2, Feature3, Feature4, Feature5, Feature6, Feature7, Feature8, Feature9, Feature10, CostPrice, Markup, Offer, Shipping, ShippingWeight, ShippingLabel FROM products ORDER BY productid ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '
<table id="productbox">
<tr>
<th class="producthead" colspan="3">'.$row["ProductName"].'</th>
</tr>
<tr>
<td class="productimgcell"><img src="'.$row["Image1URL"].'" class="productimg" /></td>
<td class="productinfo">'.$row["Feature1"].'<br />'.$row["Feature2"].'<br />'.$row["Feature3"].'</td>
<td class="productprice"><div class="pricebg">'; echo price_calc($mysqli, $row["ProductID"], $row["CostPrice"], $row["Markup"], $row["Offer"]); echo '<span class="priceinfo">inc. VAT</a></div><div style="clear:both;"></div><div class="addtocartbg">Add To Cart</div></td>
</tr>
<tr>
<td class="productfoot" colspan="3">5/5 Stars - Write A Review</td>
</tr>
</table><br />
';
}
echo '</ul>';
?>
Index.php
<?php
$category = 'AMD';
global $category;
$page_title = 'AMD Motherboards - Motherboards - PC Components';
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
$results = mysqli_query($mysqli,"SELECT COUNT(*) FROM products WHERE SubCategory2 = '$category'");
$get_total_rows = mysqli_fetch_array($results);
$pages = ceil($get_total_rows[0]/$item_per_page);
include_once($_SERVER['DOCUMENT_ROOT'].'/template/header.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/template/sidemenu.php');
?>
<div class="contentboxcontainer">
<div class="centercontentbox">
<div class="halfcontentboxcontainer">
<div class="halfcontentbox">
<div class="contenthead">Deals</div>
<div class="content">
<div class="contentcontainer">
Test
</div>
</div>
</div>
</div>
<div class="halfimgcontentboxl">
<img src="https://assets.vg247.com/current//2015/07/battlefront_leaked_alpha_tatooine_4.jpg" style="border-radius: 5px; width: 100%;" />
</div>
</div>
</div>
<div class="contentboxcontainer">
<div id="contentbox">
<div class="contenthead">Products</div>
<div class="content">
<div id="results"></div>
<div class="pageswrap"><div class="pagination"></div> <div style="clear:both;"></div></div>
</div>
</div>
</div>
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/template/footer.php');
?>
Send the category id as a post variable in the load command.
var cat = <?php echo $category; ?>
$("#results").load("/includes/pagination.php", {'page':num , 'category':cat});
For anyone else interested in an answer for this, I'm going to post my work around just in case anyone might find it useful.
In my pagination.php I added a check for the current page the user is on and compared that to a url I define. If the user is on said page then I define the category there.
pagination.php
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
if ($_SERVER['HTTP_REFERER'] == $domainurl.'/store/pc-components/motherboards/amd/') {
$category = 'AMD';
}
I had to use $_SERVER['HTTP_REFERER'] due to it being called from JS and $domainurl is defined in my config file (which is included in db_connect.php).
I can now call my variable in a mysql query on pagination.php
FROM products WHERE SubCategory2 = '".$category."'
Not the cleanest of work arounds but it saved me worrying about having to rethink the way I was doing it all.
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 ;-)