I'm trying to separate the data that I get here and trying to register it in the database.
I get the data with a form that looks like this.
var max_input_fields=10;
var delimiter='|';
function http( data, callback ){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 ) callback.call( this, xhr.response );
};
xhr.open( 'POST', document.location.href, true );
xhr.send( data );
}
function cbhttp(r){
document.querySelectorAll('output')[0].innerHTML=r
}
function bindEvents(){
var oBttnAdd=document.getElementById('bttnadd');
var oBttnSub=document.getElementById('bttnsub');
var oForm=document.getElementById('dynelems');
var oParent=document.getElementById('loopdiv');
oBttnSub.onclick=function(e){
/* scan the form and get values from all elements ( including dynamcially added ) and submit the form via xhr */
var col=oForm.querySelectorAll('input[type="text"],textarea,select');
var data=new FormData();
data.append('delimiter',delimiter);
for( var n in col ) if( col[n] && col[n].nodeType==1 ) {
data.append( col[n].name, col[n].value.replace( delimiter, '' ) + delimiter );
}
http.call( this, data, cbhttp );
};
oBttnAdd.onclick=function(e){
/* Add new rows based upon selected option from dropdown menu */
var col=oParent.querySelectorAll('section[data-id]');
var length=col.length;
if( length < max_input_fields ){
var newid=parseInt( col[ length-1 ].dataset.id ) + 1;
var clone=oParent.childNodes[1].cloneNode( true );
clone.dataset.id=newid;
/* Set new name for the textarea */
clone.childNodes[3].childNodes[1].name='videolink'+newid;
oParent.appendChild( clone );
}
}
}
document.addEventListener('DOMContentLoaded', bindEvents,false);
<form action="adddilemman.php" id="dynelems" method="post" enctype="multipart/form-data">
<br>
<div id='loopdiv'>
<?php
/* Data-id is used by js to determine next suitable id */
echo "
<section data-id=1>
<h2>Dilemma</h2>
<div>Video länk:<br><textarea rows='1' cols='40' name='videolink1'></textarea></div>";
for( $i=1; $i <= 4; $i++ ){
/* Add four text fields and four select menus */
echo "
<div>
Answer: <input type='text' name='answer{$i}[]'/>
<select name='options{$i}[]'>";
/* Add options to each select menu */
for( $j=1; $j <= 10; $j++ ){
echo "<option value={$j}>{$j}";
}
/* Close each nested div & select menu */
echo "
</select>
</div>";
}
/* Close initial section */
echo "
</section>";
?>
</div>
<div class='input_fields_wrap'>
<div></div>
</div>
<input id='bttnadd' type='button' name='add_field_button' value='Lägg till fler svar'/>
<input id='bttnsub' type='submit' name='sub' value='Submit'/>
</form>
<output></output>
I'm using "adddilemman.php" to show the data just to see if its working and its working. But I have now idea how to register this data in the database. PS I want to register it in two different tables (textarea in a table and answers in another table)
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* This is here only to simplify development and display here */
$delimiter=isset( $_POST['delimiter'] ) ? $_POST['delimiter'] : '|';
/* process form submission: for testing purposes just echo out data sent */
foreach( $_POST as $field => $value ) {
if( $field!='delimiter' ){
if( is_array( $value ) ) echo 'Array values: '.$field.'='.rtrim( str_replace( $delimiter, ',', implode( ' ', $value ) ), ',' ).'<br />';
else echo 'String value: '.$field.'='.trim( str_replace( $delimiter, '', $value ) ).'<br />';
}
}
exit();
}
?>
Any recommendations how I can separate this data and register it in the database?
You would want to setup the form like so:
<textarea rows='1' cols='40' name='videolink1'><?php echo isset($_POST['videolink1'])?$_POST['videolink1']:""; ?></textarea>
<?php
for( $i=1; $i < 5; $i++ ){
/* Add four text fields and four select menus */
?>
<div>
<label>Answer:</label>
<input type='text' name='answer[<?php echo $i; ?>]' value="<?php echo isset($answer[$i])?$answer[$i]:''; ?>" />
<select name='options[<?php echo $i; ?>]'>
<?php
for( $j=1; $j <= 10; $j++ ){
if($options[$i] == $j){
echo "\t\t\t\t\t<option selected='selected' value={$j}>{$j}</option>\r\n";
} else {
echo "\t\t\t\t\t<option value={$j}>{$j}</option>\r\n";
}
}
?>
</select>
</div>
<?php
}
?>
I would prepare the post data like so:
<?php
$vidlink = "";
$answers = array();
$options = array();
if(isset($_POST['sub'])){
$vidlink = htmlentities($_POST['videolink1']);
for($i=1;$i<=count($_POST['answer']);$i++){
$answer[$i] = $_POST['answer'][$i];
$options[$i] = $_POST['options'][$i];
}
}
?>
This will place the content of the answers and options in their own arrays but with the same indexes. You can loop and place them in the DB any way you like. Here is an example:
$con = mysqli_connect("localhost", "root", "", "wildfire");
if($con === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
for($i=1;$i<=$count($answer);$i++){
if ($stmt = mysqli_prepare($con, "INSERT INTO answer_det ('aid', 'answer', 'points') VALUES (?, ?, ? )")) {
mysqli_stmt_bind_param($stmt, "isi", $i, $answer[$i], $options[$i]);
mysqli_stmt_execute($stmt);
}
}
Here is all the code I used for testing on phpfiddle.org:
<?php
$vidlink = "";
$answers = array();
$options = array();
if(isset($_POST['sub'])){
$vidlink = htmlentities($_POST['videolink1']);
for($i=1;$i<=count($_POST['answer']);$i++){
$answer[$i] = $_POST['answer'][$i];
$options[$i] = $_POST['options'][$i];
}
}
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="dynelems" method="post" enctype="multipart/form-data">
<div id='loopdiv'>
<section data-id=1>
<h2>
Dilemma
</h2>
<div>
Video länk:
<br />
<textarea rows='1' cols='40' name='videolink1'><?php echo isset($_POST['videolink1'])?$_POST['videolink1']:""; ?></textarea>
</div>
<?php
for( $i=1; $i < 5; $i++ ){
/* Add four text fields and four select menus */
?>
<div>
<label>Answer:</label>
<input type='text' name='answer[<?php echo $i; ?>]' value="<?php echo isset($answer[$i])?$answer[$i]:''; ?>" />
<select name='options[<?php echo $i; ?>]'>
<?php
for( $j=1; $j <= 10; $j++ ){
if($options[$i] == $j){
echo "\t\t\t\t\t<option selected='selected' value={$j}>{$j}</option>\r\n";
} else {
echo "\t\t\t\t\t<option value={$j}>{$j}</option>\r\n";
}
}
?>
</select>
</div>
<?php
}
?>
</section>
</div>
<div class='input_fields_wrap'>
<div>
</div>
</div>
<input id='bttnadd' type='button' name='add_field_button' value='Lägg till fler svar'/>
<input id='bttnsub' type='submit' name='sub' value='Submit'/>
</form>
<output>
<?php
if(isset($_POST['sub'])){
htmlentities(var_export($_POST));
var_export($answer);
var_export($options);
}
</output>
</html>
Related
I have a problem with my database and doing the update of it. I have a database table stock with 5 columns (stock_id, p_id, brand_id, cat_id, availability). I want to do an update from the frontend. So when the popup show up and I fill in the form, UPDATE doesn't work. I have 3 files. First one stock.php that read database and works fine. the seconf one that open if you click edit looks like this:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
$query = "SELECT * FROM stock WHERE stock_id = $id";
$results = $database->get_results( $query );
foreach( $results as $row ){
$cat_id = $row['cat_id'];
$brand_id = $row['brand_id'];
$p_id = $row['p_id'];
?>
<form method="post" name="form">
<input id="stock_id" name="stock_id" type="hidden" value="<?php echo $row['stock_id'];?>"/>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">CATEGORY</label>
<select id="category" name="category" class="form-control">
<?php
$qex = "SELECT * FROM category";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['cat_id']; ?>"<?php
if ($cat_id == $rowex['cat_id'])
echo 'selected'; ?>><?php echo $rowex['cat_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">BRAND</label>
<select id="brand" name="brand" class="switchable form-control">
<?php
$qex = "SELECT * FROM brand";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['brand_id']; ?>"<?php
if ($brand_id == $rowex['brand_id'])
echo 'selected'; ?> class="brand_<?php echo $rowex['cat_id'];?>"><?php echo $rowex['brand_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">PRODUCT NAME</label>
<select id="product" name="product" class="switchable form-control">
<?php
$qex = "SELECT * FROM product";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['product_id']; ?>"<?php
if ($product_id == $rowex['product_id'])
echo 'selected'; ?> class="product_<?php echo $rowex['brand_id'];?>"><?php echo $rowex['product_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">IN STOCK</label>
<input type="number" id="availability" name="availability" value="<?php echo $row['availability'];?>" class="form-control"/>
</div>
</div>
<div class="clearfix"></div>
<div>
<input type="submit" value="Update Data" class="pull-right btn btn-primary submit" style="margin-right:15px;"/>
<span class="pull-left error" style="display:none;margin-left:15px;"> Please Enter Valid Data</span>
<span class="pull-left success" style="display:none;margin-left:15px;"> Data updated!</span>
<div class="clearfix"></div>
</div>
</form>
<?php
}
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
var stock_id = $("#stock_id").val();
var category = $('select[name="category"]').val()
var brand = $('select[name="brand"]').val()
var product = $('select[name="product"]').val()
var availability = $("#availability").val();
var dataString =
'stock_id='+ stock_id +
'&brand=' + brand +
'&category=' + category +
'&product=' + product +
'&availability=' + availability
;
if(
stock_id=='' ||
brand=='' ||
category=='' ||
product=='' ||
availability==''
){
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update-stock.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
$("#category").change(function () {
if ($(this).data('options') == undefined) {
$(this).data('options', $('select.switchable option').clone());
}
var id = $(this).val();
var that = this;
$("select.switchable").each(function () {
var thisname = $(this).attr('name');
var theseoptions = $(that).data('options').filter('.' + thisname + '_' + id);
$(this).html(theseoptions);
});
});
//then fire it off once to display the correct elements
$('#category').trigger('change');
});/** Document Ready Functions END **/
</script>
<?php } ?>
This is my code for update-stock.php that supposed to be updating the database:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST) {
$stock_id = $_POST['stock_id'];
$brand = $_POST['brand'];
$category = $_POST['category'];
$product = $_POST['product'];
$availability = $_POST['availability'];
$update = array(
'p_id' => $product,
'brand_id' => $brand,
'cat_id' => $cat,
'availability' => $availability
);
$where_clause = array(
'stock_id' => $stock_id
);
$updated = $database->update( 'stock', $update, $where_clause, 1 );
}
?>
I have a 2 problems.
Update doesn't work at all. I am just getting the message Please Enter Valid Data
My form doesn't show up the correct value of the PRODUCT NAME. Example: In the database and my main table that read information from database product name is 2.1.1 but when I click on edit and open my pop-up form that show up 2.1.3 for example.
Thank you so much in advance for your help.
This one works PERFECT fetch_brand.php:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
$query = "SELECT * FROM brand WHERE brand_id = $id";
$results = $database->get_results( $query );
foreach( $results as $row ){
$cat_id = $row['cat_id'];
?>
<form method="post" name="form">
<input id="brand_id" name="brand_id" type="hidden" value="<?php echo $row['brand_id'];?>"/>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">CATEGORY</label>
<select id="category" name="category" class="form-control">
<?php
$qex = "SELECT * FROM category";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['cat_id']; ?>"<?php
if ($cat_id == $rowex['cat_id'])
echo 'selected'; ?>><?php echo $rowex['cat_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">BRAND NAME</label>
<input type="text" id="brand_name" name="brand_name" value="<?php echo $row['brand_name'];?>" class="form-control"/>
</div>
</div>
<div class="clearfix"></div>
<div>
<input type="submit" value="Update Data" class="pull-right btn btn-primary submit" style="margin-right:15px;"/>
<span class="pull-left error" style="display:none;margin-left:15px;"> Please Enter Valid Data</span>
<span class="pull-left success" style="display:none;margin-left:15px;"> Data updated!</span>
<div class="clearfix"></div>
</div>
</form>
<?php
}
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
var brand_id = $("#brand_id").val();
var brand_name = $("#brand_name").val();
var category = $('select[name="category"]').val()
var dataString =
'brand_id='+ brand_id +
'&brand_name=' + brand_name +
'&category=' + category
;
if(
brand_id=='' ||
brand_name=='' ||
category==''
){
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update-brand.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
});/** Document Ready Functions END **/
</script>
<?php } ?>
update-product.php :
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST) {
$p_id = $_POST['p_id'];
$brand = $_POST['brand'];
$category = $_POST['category'];
$product = $_POST['product'];
$update = array(
'product_name' => $product,
'brand_id' => $brand,
'cat_id' => $cat
);
$where_clause = array(
'p_id' => $p_id
);
$updated = $database->update( 'product', $update, $where_clause, 1 );
}
?>
This one works excellent! So I am pretty sure that I made a mistake in my code for the stock.
I am working on an e-testing system in which when a candidate login the test for which he/she was register will be shown to him/her.
I am getting the specific test through session to show the questions containing in that test. This was successfully done with the help of some "if" checks and two while loops(1 for questions and 2nd for answers against that question) having the form of radio buttons for selecting an answer.
Now each time when loop execute it create a form for single question and its answer, that way for multiple questions it results in multiple.
I am getting the checked radio buttons through ajax and posting it to another php file but I need a question id of checked answer as well to be passed to the 2nd php file
I used session but it only get the id of 1st checked and not for the others.
The 2nd php file name is answers.php for the time being i just want to post and get all values and session in answers.php file.
the main problem is with $_SESSION ['qid'] = $id; session
Note: i have used unset and destroy session to free the session and tried to re start it but i am field to do so..
<?php
include ("connection.php");
// $mysql_row = '';
$query_run = null;
$test = $_SESSION ['id'];
var_dump ( $_SESSION ['id'] );
$query1 = "SELECT * FROM question where testid = '" . $_SESSION ['id'] . "'";
if ($query_run = mysql_query ( $query1 )) {
if (mysql_num_rows ( $query_run ) == null) {
print "No result";
} else {
// echo'<form action="ss.php" method="post">';
while ( $mysql_row = mysql_fetch_assoc ( $query_run ) ) {
$id = $mysql_row ['qid'];
$_SESSION ['qid'] = $id;
echo ' <div class="panel-heading" style="background: black; font-weight:bold;">Question </div>';
$data = $mysql_row ['questions'];
?>
<form>
<br>
<div class=" form-control well well-sm">
<?php echo'<div style="font-weight:bold;"> Q: '.$data.' </div> '; ?>
<br>
</div>
<?php
$query1 = "SELECT * FROM `answer` where id='" . $id . "'";
if ($query_run1 = mysql_query ( $query1 )) {
if (mysql_num_rows ( $query_run ) == null) {
} else {
while ( $mysql_row1 = mysql_fetch_assoc ( $query_run1 ) ) {
$data1 = $mysql_row1 ['ans1'];
$data2 = $mysql_row1 ['ans2'];
$data3 = $mysql_row1 ['ans3'];
$data4 = $mysql_row1 ['ans4'];
echo "\n";
?>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option1</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data1' name='opt1' onclick='OnChangeRadio (this)'> $data1<br />";
?>
<br>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option2</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data2' name='opt1' onclick='OnChangeRadio (this)'> $data2<br />";
?>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option3</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data3' name='opt1' onclick='OnChangeRadio (this)'> $data3<br />";
?>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option4</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data4' name='opt1' onclick='OnChangeRadio (this)'> $data4<br />";
// echo'</form>';
?>
</div>
<?php
echo '</form>';
}
}
}
// $view_id1 = $view_id;
// echo $view_id1;
}
}
} else {
print mysql_error ();
}
// unset($_SESSION['qid']);
?>
connection.php
<?php
session_start ();
if (! $_SESSION ['user']) {
header ( "Location: index.php" );
// redirect to main page to secure the welcome
// page without login access.
}
I am using a WordPress plugin that provides a front end editor to create a custom post type (directory). When I create a new directory listing the page redirects back to the /listings/my-listings/, however when I edit an existing listing and click the save button it dose not redirect. The page page instead refreshes and adds a # to the end of the URL (/listings/edit-listing/#). Could anyone look at this and help me to tweak the php or provide a javascript/jquery to redirect me back to the /listings/my-listings/?
I believe it has something to do with the .submit class at the bottom of the code...
Code:
<?php
get_header();
/**
* The template for displaying the Add/edit listing page.
* You can override this file in your active theme.
*
* #license GNU General Public License (Version 2 - GPLv2) {#link
http://www.gnu.org/licenses/gpl-2.0.html}
*/
global $wp_query, $wp_taxonomies, $post, $post_ID, $CustomPress_Core,
$Directory_Core;
$listing_data = '';
$selected_cats = '';
$error = get_query_var('dr_error');
$post_statuses = get_post_statuses(); // get the wp post status list
$options = $Directory_Core->get_options('general');
$allowed_statuses = $Directory_Core->get_options('general'); // Get the ones we allow
$allowed_statuses['moderation'] = (empty($allowed_statuses['moderation']) ) ? array('publish' => 1, 'draft'=> 1 ) : $allowed_statuses['moderation']; // Get the ones we allow
$allowed_statuses = array_reverse(array_intersect_key($post_statuses, $allowed_statuses['moderation']) ); //return the reduced list
//Are we adding a Listing?
if (is_page($Directory_Core->add_listing_page_id)) {
//Make an auto-draft so we have a post id to connect attachemnts to. Set global $post_ID so media editor can hook up. Watch the case
$post_ID = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $Directory_Core->post_type, 'post_status' => 'auto-draft' ) );
$listing_data = get_post($post_ID, ARRAY_A );
$listing_data['post_title'] = ''; //Have to have a title to insert the auto-save but we don't want it as final.
$editing = false;
}
//Or are we editing a listing?
if(is_page($Directory_Core->edit_listing_page_id)){
$listing_data = get_post( $_REQUEST['post_id'], ARRAY_A );
$post_ID = $listing_data['ID'];
$editing = true;
}
$post = get_post($post_ID);
if ( isset( $_POST['listing_data'] ) ) $listing_data = $_POST['listing_data'];
require_once(ABSPATH . 'wp-admin/includes/template.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/post.php');
$editor_settings = array(
'wpautop' => true, // use wpautop?
'media_buttons' => true, // show insert/upload button(s)
'textarea_name' => 'listing_data[post_content]', // set the textarea name to something different, square brackets [] can be used here
'textarea_rows' => 10, //get_option('default_post_edit_rows', 10), // rows="..."
'tabindex' => '',
'editor_css' => '', // intended for extra styles for both visual and HTML editors buttons, needs to include the <style> tags, can use "scoped".
'editor_class' => 'required', // add extra class(es) to the editor textarea
'teeny' => false, // output the minimal editor config used in Press This
'dfw' => false, // replace the default fullscreen with DFW (needs specific css)
'tinymce' => true, // load TinyMCE, can be used to pass settings directly to TinyMCE using an array()
'quicktags' => true // load Quicktags, can be used to pass settings directly to Quicktags using an array()
);
$listing_content = (empty( $listing_data['post_content'] ) ) ? '' : $listing_data['post_content'];
wp_enqueue_script('set-post-thumbnail');
?>
<script type="text/javascript" src="<?php echo $Directory_Core->plugin_url . 'ui-front/js/jquery.tagsinput.min.js'; ?>" ></script>
<script type="text/javascript" src="<?php echo $Directory_Core->plugin_url . 'ui-front/js/media-post.js'; ?>" ></script>
<script type="text/javascript" src="<?php echo $Directory_Core->plugin_url . 'ui-front/js/ui-front.js'; ?>" >
</script>
<?php if ( !empty( $error ) ): ?>
<br /><div class="error"><?php echo $error . '<br />'; ?></div>
<?php endif; ?>
<div class="dr_update_form">
<form class="standard-form base" method="post" action="#" enctype="multipart/form-data" id="dr_update_form" >
<input type="hidden" id="post_ID" name="listing_data[ID]" value="<?php echo ( isset( $listing_data['ID'] ) ) ? $listing_data['ID'] : ''; ?>" />
<input type="hidden" name="post_id" value="<?php echo ( isset( $listing_data['ID'] ) ) ? $listing_data['ID'] : ''; ?>" />
<?php if(post_type_supports('directory_listing','title') ): ?>
<div class="editfield">
<label for="title"><?php _e( '<strong>Agent Name:</strong>', $Directory_Core->text_domain ); ?></label>
<input class="required" type="text" id="title" name="listing_data[post_title]" value="<?php echo ( isset( $listing_data['post_title'] ) ) ? esc_attr($listing_data['post_title']) : ''; ?>" />
<p class="description"><?php _e( 'Enter agents name here.', $Directory_Core->text_domain ); ?></p>
</div>
<?php endif; ?>
<!-- Start Add Featured Image / Agent Headshot-->
<?php if(post_type_supports('directory_listing','thumbnail') && current_theme_supports('post-thumbnails') ): ?>
<div class="editfield">
<div><strong>Agent Headshot:</strong></div>
<?php if(empty($options['media_manager']) ): ?>
<?php if(has_post_thumbnail()) the_post_thumbnail('thumbnail'); ?><br />
<script type="text/javascript">js_translate.image_chosen = '<?php _e("Feature Image Chosen", $Directory_Core->text_domain); ?>';</script>
<span class="upload-button">
<?php $class = ( empty($options['field_image_req']) && !has_post_thumbnail() ) ? 'required' : ''; ?>
<input type="file" name="feature_image" size="1" id="image" class="<?php echo $class; ?>" />
<button type="button" class="button"><?php _e('Add Agent Headshot', $Directory_Core->text_domain); ?></button>
</span>
<br />
<?php else: ?>
<div id="postimagediv">
<div class="inside">
<?php
$thumbnail_id = get_post_meta( $post_ID, '_thumbnail_id', true );
echo _wp_post_thumbnail_html($thumbnail_id, $post_ID);
?>
</div>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<!-- End Add Featured Image / Agent Headshot-->
<!-- Start Taxonimy, Category and custom All Services-->
<?php
//get related hierarchical taxonomies
$taxonomies = get_object_taxonomies('directory_listing', 'objects');
$taxonomies = empty($taxonomies) ? array() : $taxonomies;
//Loop through the taxonomies that apply
foreach($taxonomies as $taxonomy):
if( ! $taxonomy->hierarchical) continue;
$tax_name = $taxonomy->name;
$labels = $taxonomy->labels;
//Get this Taxonomies terms
$selected_cats = array_values( wp_get_post_terms($listing_data['ID'], $tax_name, array('fields' => 'ids') ) );
?>
<div id="taxonomy-<?php echo $tax_name; ?>" class="dr_taxonomydiv">
<label><?php echo $labels->all_items; ?></label>
<div id="<?php echo $tax_name; ?>_all" class="dr_tax_panel">
<?php
$name = ( $tax_name == 'category' ) ? 'post_category' : 'tax_input[' . $tax_name . ']';
echo "<input type='hidden' name='{$name}[]' value='0' />"; // Allows for an empty term set to be sent. 0 is an invalid Term ID and will be ignored by empty() checks.
?>
<ul id="<?php echo $tax_name; ?>_checklist" class="list:<?php echo $labels->name; ?> categorychecklist form-no-clear">
<?php wp_terms_checklist( 0, array( 'taxonomy' => $tax_name, 'selected_cats' => $selected_cats, 'checked_ontop' => false ) ) ?>
</ul>
</div>
</div>
<?php endforeach; ?>
<!-- End Taxonimy, Category and custom All Services-->
<div class="clear"><br /></div>
<!-- Start Custom Press / Custom Fields-->
<?php if ( isset( $CustomPress_Core ) ) : ?>
<?php echo do_shortcode('[custom_fields_input style="editfield"]'); ?>
<?php endif; ?>
<?php if ( !empty( $error ) ): ?>
<br /><div class="error"><?php echo $error . '<br />'; ?></div>
<?php endif; ?>
<!-- End Custom Press / Custom Fields-->
<!-- Start Select as Draft/Pyblic-->
<div class="editfield" >
<label for="title"><?php _e( 'Status', $Directory_Core->text_domain ); ?></label>
<div id="status-box">
<select name="listing_data[post_status]" id="listing_data[post_status]">
<?php
foreach($allowed_statuses as $key => $value): ?>
<option value="<?php echo $key; ?>" <?php selected( ! empty($listing_data['post_status'] ) && $key == $listing_data['post_status'] ); ?> ><?php echo $value; ?></option>
<?php endforeach; ?>
</select>
</div>
<p class="description"><?php _e( 'Please select a status for your listing. If you select your listing status as “Published” your listing will be made live and available for the public to view. If you select your listing status as “Draft” your listing will not be visible to the public and you can come back later to finish/publish.', $Directory_Core->text_domain ); ?></p>
</div>
<!-- End Select as Draft/Pyblic-->
<div class="submit">
<?php wp_nonce_field( 'verify' ); ?>
<input type="submit" value="<?php _e( 'Save Changes', $Directory_Core->text_domain ); ?>" name="update_listing">
<input type="button" value="<?php _e( 'Cancel', $Directory_Core->text_domain ); ?>" onclick="location.href='<?php echo get_permalink($Directory_Core->my_listings_page_id); ?>'">
</div>
<?php //echo do_shortcode('[ct_validate]') ; ?>
</form>
</div>
<?php get_footer(); ?>
Since your PHP is inside your code, you do not need the action attribute in your <form> tag. take action="#" out of the form tag and you should be good to go.
Right here:
<form class="standard-form base" method="post" action="#" enctype="multipart/form-data" id="dr_update_form" >
The action attribute is to send the data to another url and is why you get the # at the end of the current url.
something like this?
<input id="myButton" type="submit" value="<?php _e( 'Save Changes', $Directory_Core->text_domain ); ?>" name="update_listing">
<script type="text/javascript">
document.getElementById("myButton").onclick = function () {
location.href = "www.yoursite.com/listings/edit-listing/";
};
</script>
Here is what I need to do.
I have a php page wich generates a page like site.com/result.php?id=355 plus there is dynamic content fetched from a MySql database.
The problem: The user is redirected to that page before the content even exists in the Mysql database (it is still processed on server side). This means the user has to refresh the page few times for about 3 sec and the results are there.
I want to show a loading image while there is nothing to display until the content is in the database. Once the content can be displayed it should be printed automatically without the user having to refresh page manually.
Code :
File upload and redirect:
">
<input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
<input name="userfile" type="file" id="exampleInputFile">
<p class="help-block">Select File To Crypt.</p>
<!-- <input type="hidden" name="MAX_FILE_SIZE_BIND" value="10485760" />
<input name="binded" type="file" id="exampleInputFile">
<p class="help-block">Select File To Bind</p> -->
<p>
<button type="submit" name="submit" class="btn full-width btn-primary">Crypt and Scan</button>
</p>
</form>
<?php
if (!isset($_POST['submit']))
{
} else
{
mysql_connect("localhost", "scarr", "12345") or
die("Could not connect: " . mysql_error());
mysql_select_db("scar");
$uploaddir = '/var/www/html/upl/';
$_rand = generateRandomString();
$_namerand = $_rand . ".exe" ;
$uploadfile = $uploaddir .$_namerand ;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
if ($_FILES['MAX_FILE_SIZE']['size'] == 0 && $_FILES['MAX_FILE_SIZE']['error'] == 0)
{
}
$linked = "http://192.168.129.137/upl/" . $_namerand;
$sql = mysql_query("INSERT INTO Task (link, name) VALUES ('$linked', '$_rand')");
if (!$sql) {
echo 'Could not run query: ' . mysql_error();
exit;
}
?>
<form name='redirect' action='result.php?name=' method='GET'>
<input type='hidden' name='name' value='<?php echo $_rand; ?>'>
<script type='text/javascript'>
document.redirect.submit();
</script>
</form>
<?php
} else {
}
}
function generateRandomString($length = 8) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
?>
Code Result page:
<?php
mysql_connect("localhost", "scar", "12345") or
die("Could not connect: " . mysql_error());
mysql_select_db("scanner");
$namestr = $_GET["name"];
$result = mysql_query("SELECT id,name,Result FROM Results WHERE name = '$namestr'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
?>
<div id="content">
<h1><center><font color="green">{ 0/42 }</font></center></h1>
<table><thead><th>LiveGr Name</th><th>Result</th></thead>
<tr><td>LiveGridSys </td><td><font color ='Red'><?php printf($row[2])?></font></td></tr>
</table>
i am doing a php script wherein I need to remember the checked checkbox and save it all the database. Unfortunately, my code save only the current page where I checked the checkbox but the other checked box became unchecked.
Example In Page 1 I checked 3 items, on the second page I checked I tem. When I click the submit button I only got the checked item of the current page. And when I go back to the previous page the item that I checked became unchecked.How can I preserved and save the value of my checked checkbox through pagination?
here is my code for CreateTest.php
<html>
<body>
<?php
ob_start();
session_start();
include("connect.php");
error_reporting(0);
$item_per_page=10;
$results = mysqli_query($con,"SELECT COUNT(*) FROM tblitem");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<form name="myform" action="CreateTest.php" method="POST" onsubmit="return checkTheBox();" autocomplete="off">
<body>
<?php
if(isset($_POST['save'])){
$testPrice = $_POST['testPrice'];
$testName = $_POST['testName'];
$items = $_POST['items'];
$quantity = $_POST['quantity'];
$testDept = $_POST['testDept'];
$measurement = $_POST['measurement'];
global $con;
Tool::SP_Tests_Insert(strip_tags(ucwords($testName)), $testPrice, $testDept);
$result = mysqli_query($con, "SELECT MAX(TestID) FROM lis.tbltests");
$data= mysqli_fetch_array($result);
$testID=$data[0];
foreach ($items as $key => $value){
$checkedItem[] = $value;
echo $value, " | ",$quantity[$key], " | ",$measurement[$key], "<br>";
mysqli_query($con,"INSERT INTO tbltestitem (TestID, ItemID, ItemQuantity, ItemMeasurement) VALUES ($testID, $value, '$quantity[$key]', '$measurement[$key]')");
}
echo "<script type='text/javascript'>alert('Succesfully added test!')</script>";
$site_url = "tests.php";
echo "<script language=\"JavaScript\">{location.href=\"$site_url\"; self.focus(); }</script>";
}else if(!isset($_POST['save'])){
$selectDept='';
$result= mysqli_query($con,"select * from tbldepartment");
$selectDept.="<option value=''>Select Department:</option>";
while($data = mysqli_fetch_array($result)){
$selectDept.="<option value='{$data['DeptID']}'>{$data['DeptName']}</option>";
}
?>
<td style="vertical-align: top;">
<body>
<div id="container" align="center">
<div id="title">Create Test</div>
<div id="a">Input Test Name:</div><div id="b"><input type="text" name="testName" id="myTextBox" onkeyup="saveValue();" ></div>
<div id="a">Input Test Price:</div><div id="b"><input type="number" name="testPrice"></div>
<div id="a">Select Department:</div><div id="b"><select name="testDept" ><?php echo $selectDept; ?></select></div>
<div id="results"></div><div id="a"><?php echo $pagination; ?></div>
<div align="right" style="padding: 10px;"><input type="submit" name="save" value="Submit"></div> </div>
<?php
}
?>
</body>
</html>
This is my fetch_pages.php code.
this php page help me to keep the textbox values through pagination through jquery it will be loaded without going the another page of pagination
<?php
include("connect.php");
require_once('classes/tool.php');
$item_per_page=10;
//sanitize post value
$page_number = $_POST["page"];
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con,"SELECT * FROM tblitem ORDER BY ItemID ASC LIMIT $position, $item_per_page");
$connection=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$selectMeasure='';
$measurements = Tool::SP_Measurement_Select();
foreach($measurements as $measure) {
$selectMeasure.='<option value=' . $measure['MeaName'] . '>' . $measure['MeaName'] . '</option>';
$i=0;
while($item = mysqli_fetch_array($results))
{
echo "<div id='a'><input type='checkbox' name='items[$i]' id='item[]' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
echo "<div id='b'><input type='number' name='quantity[$i]' class='quantity' /></div>";
echo "<div id='b'><select name='measurement[$i]' class='quantity'>'".$selectMeasure."'</select></div>";
$i++;
}
?>
Hope you can help me. Thanks in advance
Ugg... way too much code to look through.
The short answer, however, is that you pass values from one form to another using <input type-"hidden"...> markup.
Warning, code type free-hand
Page1.php
<form action="page2.php">
<div>
<input type="checkbox" name="test1">
</div>
</form>
Page2.php
<?php
if (is_set($_REQUEST["test1"])) {
$test1 = $_REQUEST["test1"];
} else {
$test1 = false;
}
<form action="page3.php">
<div>
<input type="hidden" name="test1" value="<?php echo $test1 ?>">
</div>
</form>
Page3.php
<?php
$test1 = $_REQUEST["test1"];
?>