This is the extended question of the thread implementing php long polling
I got the solutions for that. But in my server.php i am displaying a form which will be having few input fields. This should display in #response area. Now i am able to display the same on instant basis. As it loads on seconds basis, i am not able to enter anything on any input boxes. Here is my display page
<?php
ob_start();
include('includes/sessions.php');
include('includes/config.php');
include('includes/functions.php');
$grp_id = $_GET['id'];
?>
<!DOCTYPE html>
<head>
<!-- head section -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
function getContent(timestamp)
{
var queryString = {'timestamp' : timestamp, 'id' : <?php echo $grp_id; ?>};
$.ajax(
{
type: 'GET',
url: 'http://localhost/folder/server.php',
data: queryString,
success: function(data){
// put result data into "obj"
var obj = JSON.parse(data);
// put the data_from_file into #response
$('#response').html(obj.data_from_file);
// call the function again, this time with the timestamp we just got from server.php
getContent(obj.timestamp);
}
}
);
}
// initialize jQuery
$(function() {
getContent();
});
</script>
</head>
<body<?php if ($body_classes) { echo ' class="' . $body_classes . '"'; } ?>>
<div id="page-content" class="block">
<div class="row gutter30">
<div class="col-xs-12">
<div id="response"></div>
<!--Contents in server.php will display according to the condition changes in database-->
</div>
</div>
</div>
server.php
<?php
set_time_limit(0);
$data_source_file = 'data.txt';
include('includes/sessions.php');
include('includes/config.php');
include('includes/functions.php');
// main loop
while (true) {
// if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
$last_ajax_call = isset($_GET['timestamp']) ? (int)$_GET['timestamp'] : null;
// PHP caches file data, like requesting the size of a file, by default. clearstatcache() clears that cache
// clearstatcache();
// get timestamp of when file has been changed the last time
// $last_change_in_data_file = filemtime($data_source_file);
// Create database
$sql = "SELECT max(gid) FROM base_grp WHERE gid=".$_GET['id']."";
$result = mysqli_query($conn, $sql);
$last_change_in_data_file = mysqli_fetch_array($result, MYSQLI_NUM)[0];
// if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
if ($last_ajax_call == null || $last_change_in_data_file > $last_ajax_call) {
$sql = "SELECT is_set FROM base_grp WHERE gid =".$_GET['id']."";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if($row['is_set'] == 0)
{
$data .= '<form name="frm" method="post" action="show_data.php">
<div class="row gutter30" style="margin-top:20px;">
<div class="form-group">
<img src="img/img1.png" class="image" />
<input type="text" name="img1" class="form-control" />
<input type="hidden" name="img1_id" value="3" />
</div>
<div class="form-group">
<img src="img/img2.png" class="image" />
<input type="text" name="img2" class="form-control" />
<input type="hidden" name="img2_id" value="4" />
</div>
<div class="form-group">
<img src="img/img3.png" class="image" />
<input type="text" name="img3" class="form-control" />
<input type="hidden" name="img3_id" value="2" />
</div>
<div class="form-group">
<img src="img/img4.png" class="image" />
<input type="text" name="img4" class="form-control" />
<input type="hidden" name="img4_1" value="1" />
</div>
<button type="submit" name="lock" class="btn btn-sm btn-success">SUBMIT</button>
</div>
</form> ';
$last_change_in_data_file = $row["gid"];
}
else if($row['is_set'] = 1)
{
$data .= "<div class='row gutter30' style='margin-top:20px;'>
<div class='col-xs-3'>
<img src='img/img1.png' class='image' /> </div>
<div class='col-xs-3'>
<img src='img/img2.png' class='image' /> </div>
<div class='col-xs-3'>
<img src='img/img3.png' class='image' /> </div>
<div class='col-xs-3'>
<img src='img/img4.png' class='image' /> </div>
</div>
";
$last_change_in_data_file = $row["gid"];
}
$last_change_in_data_file = $row["gid"];
}
}
// mysqli_close($conn);
// put data.txt's content and timestamp of last data.txt change into array
$result = array(
'data_from_file' => $data,
'timestamp' => $last_change_in_data_file
);
mysqli_close($conn);
// encode to JSON, render the result (for AJAX)
$json = json_encode($result);
echo $json;
// leave this loop step
break;
} else {
// wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
sleep( 1 );
continue;
}
}
Not getting how to make the entry ...
Can somebody suggest me where i am going wrong?. Thanks!
Related
I am using Tutor LMS with WordPress. There is a dashboard page and it has sub pages. I have a sub page called My Organization that allows the user to update a form and also upload a logo and backdrop image. The logo and backdrop are the images used for the main dashboard page and shows on top for all sub pages.
The good thing is that if I update the form fields and hit the update button, it will refresh and then the fields will be updated thereafter (got some major help for that one). The dingy thing is that the logo and backdrop don't update unless I refresh again.
Here is a screen recording
I have been looking for a fix but I can't seem to find anything. I tried using
<script>
window.opener.location.reload();
</script>
but it did not work.
Please let me know if you have a lead!
Here is my code for the subpage called My Organization:
<?php
global $wpdb;
$user_id = get_current_user_id();
$org_id = get_user_meta($user_id, '_org_id', true);
if (isset($_POST['update']) && wp_verify_nonce( $_POST['logo_url_nonce'], 'logo_url' ) && wp_verify_nonce( $_POST['backdrop_url_nonce'], 'backdrop_url' )) {
$orgs = $wpdb->get_results($wpdb->prepare("SELECT * FROM `wp_organization` WHERE id = $org_id"));
$user_org = null;
foreach($orgs as $org) {
$user_org = $org;
}
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
if ($_FILES['logo_url']['size'] > 0) {
$logo_attachment_id = media_handle_upload( 'logo_url', $_POST['post_id']);
$logo_url = wp_get_attachment_url($logo_attachment_id);
} else {
$logo_url = $user_org->logo_url;
}
if ($_FILES['backdrop_url']['size'] > 0) {
$backdrop_attachment_id = media_handle_upload( 'backdrop_url', $_POST['post_id']);
$backdrop_url = wp_get_attachment_url($backdrop_attachment_id);
} else {
$backdrop_url = $user_org->backdrop_url;
}
$name = isset($_POST['org_name']) ? $_POST['org_name'] : "";
$short = isset($_POST['shortname']) ? $_POST['shortname'] : "";
$ind = isset($_POST['industry']) ? $_POST['industry'] : "";
$desc = isset($_POST['description']) ? $_POST['description'] : "";
$logo = isset($_FILES['logo_url']) ? $logo_url : "";
$backdrop = isset($_FILES['backdrop_url']) ? $backdrop_url : "";
$wpdb->query(
$wpdb->prepare("
UPDATE `wp_organization` SET
name = %s,
shortname = %s,
industry = %s,
description = %s,
logo_url = %s,
backdrop_url = %s
where id = %s
",
$name, $short, $ind, $desc, $logo, $backdrop, $org_id
)
);
$orgs = $wpdb->get_results($wpdb->prepare("SELECT * FROM `wp_organization` WHERE id = $org_id"));
$user_org = null;
foreach($orgs as $org) {
$user_org = $org;
}
?>
<!-- organization info form -->
<div class="tutor-px-20">
<form class="py-4 col-md-6 mx-auto" method="post" action="" enctype="multipart/form-data">
<div class="d-flex tutor-justify-center tutor-fs-3 tutor-fw-bold tutor-mb-20">
Organization Information
</div>
<div class="tutor-form-group">
<label class="tutor-form-label">Name</label>
<input type="text" required name="org_name" value="<?php echo $user_org-> name; ?>" class="form-control mb-3" />
</div>
<div class="tutor-form-group">
<label class="tutor-form-label">Industry</label>
<input type="text" name="industry" value="<?php echo $user_org-> industry; ?>" class="form-control mb-3" />
</div>
<div class="tutor-form-group">
<label class="tutor-form-label">Short name (4 characters)</label>
<input type="text" name="shortname" required maxlength="4" value="<?php echo $user_org-> shortname; ?>" class="form-control mb-3" />
</div>
<div class="tutor-form-group">
<label class="tutor-form-label">Description</label>
<textarea class="form-control mb-3" name="description" rows="5" cols="50"><?php echo trim(stripslashes($user_org-> description)); ?></textarea>
</div>
<div class="d-flex tutor-justify-around">
<div class="tutor-form-group">
<label class="tutor-form-label">Logo (Size: 200x200px Limit: 200kb)</label>
<div class="input-group mb-3">
<input type="file" accept=".png,.jpg,.jpeg" name="logo_url" id="logo_url" multiple="false">
<input type="hidden" name="post_id" id="post_id" value="<?php echo get_the_ID()?>"/>
<?php wp_nonce_field( 'logo_url', 'logo_url_nonce' ); ?>
</div>
</div>
<div class="tutor-form-group">
<label class="tutor-form-label">Backdrop (Size: 1140x275px Limit: 600kb)</label>
<div class="input-group mb-3">
<input type="file" accept=".png,.jpg,.jpeg" name="backdrop_url" id="backdrop_url" multiple="false">
<input type="hidden" name="post_id" id="post_id" value="<?php echo get_the_ID()?>"/>
<?php wp_nonce_field( 'backdrop_url', 'backdrop_url_nonce' ); ?>
</div>
</div>
</div>
<div class="tutor-mt-32 d-flex tutor-justify-center">
<input type="submit" name="update" value='Update' class='btn btn-primary'>
</div>
</form>
</div>
The images are used in the main page called Dashboard and here is a snip of the code:
<div class="tutor-wrap tutor-wrap-parent tutor-dashboard tutor-frontend-dashboard tutor-dashboard-student tutor-mt-80 tutor-pb-40">
<div class="tutor-container" >
<?php if($org_id) { ?>
<div class="tutor-row tutor-d-flex tutor-justify-between tutor-mb-20"
style="background-image: url('<?php echo $user_org->backdrop_url; ?>'); background-size: auto; height:275px; border-radius: 20px;">
<div class="tutor-d-flex tutor-justify-center tutor-mb-60 ">
<div class="tutor-avatar tutor-avatar-xl" style="width:150px; height:150px; position: absolute; top:155px">
<img src="<?php echo $user_org->logo_url; ?>">
</div>
I would add an "id" to the div containing the image (and background). Then using ajax to push the code snip again.
Build a little example, not perfect, but should give you an idea. You can pass data to another php page, do stuff and return the data in JSON to work on it.
Note : Make sure you do thing securely (aka, use sessions to pass critical data, else someone could pass other data and get informations from other users).
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<div id="logo"><img src="loading.jpg" /></div>
<script>
function UpdateLogo() {
$.ajax({
url: "ajax.php",
type: "POST",
dataType: "json",
data: {
action: "updateLogo",
},
success: function (response) {
console.log(response);
if (response["STATUS"] == "OK") {
$("#logo").html('<img src="' + response["logo"] + '">');
}
},
error: function (jqXHR, textStatus, errorThrown) {
$("#logo").html("Error;" + errorThrown);
},
});
}
UpdateLogo();
</script>
</body>
</html>
ajax.php
<?php
if ($action = "UpdateLogo") {
//do stuff using sessions variable or whatever secure.
$return['STATUS'] = 'OK';
$return['logo'] = 'bla.jpg';
echo json_encode($return);
}
Using PHP Header method to redirect to another page after sending submit button had a problem though previously it was working fine. The problem started after putting additional form field.
Tried looking for any whitespaces, remove the code to the previous working state proved futile.
<?php
session_start();
$hostname_mysql = "localhost";
$database_mysql = "smartsaf_angkasa";
$username = "root";
$password = "";
$mysql = mysql_connect($hostname_mysql, $username, $password);
$errors = array();
//mysql_select_db( $database_mysql, $mysql);
if(!$mysql)
echo "".mysql_error();
else{
//echo "<h2>Connected to database successfully ".mysql_error()."</h2>";
mysql_select_db($database_mysql);
}
if ($_SERVER['REQUEST_METHOD'] != 'POST')
{
?>
<div>
<form class="main-container" action="admin-pakej.php" method="post" enctype="multipart/form-data" >
<div class="input-form"><label for="desc" name="lbldesc">Description</label></div><div class="input-form-right"><input type="text" name="description" size="60" required ></div>
<div class="clr"></div>
<div class="input-form"><label for="Market Price" name="lblmarketprice">Market Price</label></div><div class="input-form-right"><input type="text" name="marketprice" id="marketprice" size="20" required ></div>
<div class="clr"></div>
<div class="input-form"><label for="Membership No" name="lblmemberno">Membership Number</label></div><div class="input-form-right"><input type="text" name="membershipno" id="membershipno" size="20" onblur="change()" ><div id="disabled-text-box"><input type="text" name="membersname" size="35" disabled></div></div>
<div class="clr"></div>
<div class="input-form"><label for="Member Price" name="lblmemberprice">Members Price</label></div><div class="input-form-right"><input type="text" name="membersprice" id="membersprice" size="20" required ></div>
<div class="clr"></div>
<div class="input-form"><label for="Point PV" name="lblpointpv">PV Points</label></div><div class="input-form-right"><input type="text" name="pointpv" id="pointpv" size="20" required ></div>
<div class="clr"></div>
<div class="input-form"><label for="Package Type" name="lblpackagetype">Package Type</label></div><div class="input-form-right"><select name="package" id="package"><option value="gold">Gold</option><option value="silver">Silver</option><option value="bronze">Bronze</option></select></div>
<div class="clr"></div>
<div class="input-form"><label for="Product Page" name="lblproductpage">Product Page HTML File Name</label></div><div class="input-form-right"><input type="text" id="productpage" name="productpage" size="30"></div>
<div class="clr"></div>
<div class="input-form"><label for="Product Pics" name="lblproductpics">Product Pics</label></div><div class="clr"></div>
<div class="input-form-right"></div><div class="input-form-right"><input type="file" id="upload" name="upload" onchange="readURL(this)"></input><img id="blah" class="container" src="#" alt="preview image" /></div>
<div class="clr"></div>
<div class="input-form"></div><div class="button"><button type="submit" id="submit" name="submit">Submit</button></div>
</form>
</div>
<div class="clr"></div>
<div><p>
<!--<ul>-->
<?php
}
else
{
$desc_product = $_POST['description'];
$membershipno = $_POST['membershipno'];
$product_pics = $_FILES['upload']['name'];
$market_price = $_POST['marketprice'];
$membersprice = $_POST['membersprice'];
$package_type = $_POST['package'];
$pv_points = $_POST['pointpv'];
$productpage = $_POST['productpage'];
if (empty($desc_product) || empty($product_pics) || empty($membershipno) || empty($membersprice) || empty($pv_points) || empty($productpage))
{
array_push($errors, "Fields are empty");
}
else
{
$query = "INSERT INTO product_final (desc, ext_member_id, productpics, marketprice, memberprice, packagetype, pv_points, productpage, category) VALUES
('$desc_product', '$membershipno', '$product_pics', '$market_price', '$membersprice', '$package_type', '$pv_points', '$productpage', '')'";
$result = mysql_query($query, $mysql);
if ($result)
{
if (!headers_sent())
{
header("location:record_page.php");
exit;
}
else
{
echo "Headers already sent";
exit;
}
}
//else
//echo "".mysql_error($mysql);
}
}
?>
<!--</ul>--></p>
</div>
</body>
<script type="text/javascript">
function readURL(input)
{
if (input.files && input.files[0])
{
var reader = new FileReader();
reader.onload = function(e)
{
$("#blah")
.attr("src", e.target.result)
.width(300)
.height(250);
};
reader.readAsDataURL(input.files[0]);
}
}
function getpicPath()
{
document.getElementById("imgs").innerHTML;
}
</script>
</html>
Expect to get at least an error message to find out what is actually holding the process from sending committed form submission to another page as acknowledgement that the form has already been processed.
I think you should try
if(mysql_affeted_rows($result)==1)
{
if (!headers_sent())
{
header("location:record_page.php");
}
else
{
echo "Headers already sent";
exit;
}
}
instead of that condition and once you have redirected through header I don't think you need to use exit().
thank you.
You are getting this problem basically because some HTML code is included (which is sending the header before only) right before you are trying to send header.
Your form code is sending header initially only, thereby making it impossible to send a http header later.
Use output buffering, i.e. at the very start of your script, put ob_start(), and at the end, put ob_flush(). This enables PHP to first wait for all the output to be gathered, determine in what order to render it, and outputs it.
guide for using output buffer
I have a form that users can utilize to introduce some data to create a badge. I'm using session so that i can keep like a little history list for the users, and also if they click on one element from that list the data will be sent to the form automatically. My problem is that when i click on one element from the list a new row is inserted containing the same data, and also if i complete the form with identical data that i already have in my list again it creates another line containing the same data that i already have once. Can i do something so that my history list to contain only unique values, basically to not have the same line multiple times.
This is my code for the form:
<form method="get" autocomplete="off">
<h3>Creaza ecuson</h3>
<label>
Nume:<br><input type="text" name="nume" id="nume" required value="<?php echo $search->nume ?>"><br>
Prenume:<br><input type="text" name="prenume" id="prenume" required value="<?php echo $search->prenume ?>"><br>
Sex:<br><div class="autocomplete" style="width:300px;">
<input id="sex" type="text" name="sex" required value="<?php echo $search->sex ?>">
</div><br><br>
Rol:<br><div class="autocomplete" style="width:300px;">
<input id="rol" type="text" name="rol" required value="<?php echo $search->rol ?>">
</div><br><br>
Culoare text:<br><input type="color" name="cul" id="cul" value="<?php echo $search->cul ?>"><br><br>
Font ecuson:<br><div class="autocomplete" style="width:300px;">
<input id="font" type="text" name="font" required value="<?php echo $search->font ?>">
</div><br><br>
Format ecuson (portrait or landscape):<br><div class="autocomplete" style="width:300px;">
<input id="format" type="text" name="format" required value="<?php echo $search->format ?>">
</div><br><br>
</label>
<input type="submit" name="history" value="History" />
<button type="button" onclick="create()">Creaza</button><br><br>
</form>
My session code:
<?php
session_start();
$search = parseRequest();
storeSearch($search);
include "form.php";
$searches = $_SESSION['searches'];
function storeSearch($search) {
if (!isset($_SESSION['searches'])) {
$_SESSION['searches'] = [];
}
if (!$search->isEmpty()) {
$_SESSION['searches'][] = $search;
}
}
function parseRequest() {
$search = new SearchRequest;
$search->nume = !empty($_GET['nume']) ? $_GET['nume'] : "";
$search->prenume = !empty($_GET['prenume']) ? $_GET['prenume'] : "";
$search->sex = !empty($_GET['sex']) ? $_GET['sex'] : "";
$search->rol = !empty($_GET['rol']) ? $_GET['rol'] : "";
$search->cul = !empty($_GET['cul']) ? $_GET['cul'] : "";
$search->font = !empty($_GET['font']) ? $_GET['font'] : "";
$search->format = !empty($_GET['format']) ? $_GET['format'] : "";
return $search;
}
/**
* search request
*/
class SearchRequest
{
public $nume = "";
public $prenume = "";
public $sex = "";
public $rol = "";
public $cul = "";
public $font = "";
public $format = "";
function toQueryString() {
$params = [
'nume' => $this->nume,
'prenume' => $this->prenume,
'sex' => $this->sex,
'rol'=> $this->rol,
'cul'=> $this->cul,
'font'=> $this->font,
'format'=> $this->format
];
return http_build_query($params);
}
function isEmpty() {
return !$this->nume || !$this->prenume || !$this->sex || !$this->rol || !$this->cul || !$this->font || !$this->format;
}
}
?>
And the so called history code:
<?php
foreach ($searches as $s) {
?>
<li><a href="creare.php?<?php echo $s->toQueryString() ?>">
<?php echo $s->nume?> - <?php echo $s->prenume?> - <?php echo $s->sex?> - <?php echo $s->rol?> - <?php echo $s->cul?> - <?php echo $s->font?> - <?php echo $s->format?>
</a></li>
<?php
}
?>
I don't think the script with the autocomplete function needs to be posted here for the question that i asked. If needed i will provide.
perhaps something as simple as
function storeSearch($search) {
if (!isset($_SESSION['searches'])) {
$_SESSION['searches'] = [];
}
if (!$search->isEmpty() && !in_array($search,$_SESSION['searches') {
$_SESSION['searches'][] = $search;
}
}
Building on CFP Support's answer, here's a slightly different approach to how I would create the form and handler. It's very similar to yours but I structured the logic a bit differently. I only added 3 fields from your form but you can easily add the remaining fields.
Fiddle - http://phpfiddle.org/lite/code/354t-6sgn
<?php
session_start();
// Initialize the cart if it needs it.
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Should we show cart?
$showCart = isset($_GET['cart']) && $_GET['cart'] === 'true';
// Should we clear the cart?
if (isset($_GET['clear']) && $_GET['clear'] === 'true') {
$_SESSION['cart'] = [];
}
// Grab the current cart.
$cart = $_SESSION['cart'];
// The form was submitted
if (isset($_POST['submit'])) {
// Copy the POST data into a variable so we can modify it without side effects.
$formData = $_POST;
// Remove the submit button from the form data
unset($formData['submit']);
// Check if it is in the cart already.
if (!in_array($formData, $cart)) {
// If not, then add it.
$cart[] = $formData;
}
// Store the cart in the session.
$_SESSION['cart'] = $cart;
}
?>
<html>
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<div class="container">
<form method="post" autocomplete="off">
<h3>Creaza ecuson</h3>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="nume">Nume:
<input type="text" name="nume" id="nume" class="form-control" required>
</label>
</div>
</div>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="prenume">Prenume:
<input type="text" name="prenume" id="prenume" class="form-control" required>
</label>
</div>
</div>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="sex">Sex:
<input type="text" name="sex" id="sex" class="form-control" required>
</label>
</div>
</div>
<button class="btn btn-primary" name="submit" type="submit">Create</button>
<?php
// Toggle show/hide history
if ($showCart) { ?>
<a class="btn btn-primary" href="?" role="button">Hide Cart</a>
<?php } else { ?>
<a class="btn btn-primary" href="?cart=true" role="button">Show Cart</a>
<?php }
// If the cart is not empty, allow user to clear it.
if (!empty($cart)) { ?>
<a class="btn btn-primary" href="?clear=true" role="button">Clear Cart</a>
<?php }
?>
</form>
<?php
// Show the cart.
if ($showCart) {
echo '<pre>';
var_dump($cart);
echo '</pre>';
}
?>
</div>
</body>
</html>
Here's a way and little pseudo-code, you could implement something similar with your codebase.
The idea is, since from one computer only one person can sign up, store a unique ID for that person in session. Then when entering the data into session, check if that ID is present or not.
If it's present, do not add, if it's not, add.
Pseudo-code
$uniqueID = hash("sha256", $_SERVER['REMOTE_ADDR']); //generate a unique ID depending on IP since that would be unique for each computer
//insert into your session
if(!in($sessionHandler, $uniqueid)
{
//insert now
}
I'm having difficulties to insert the value as blob type always empty and the other method can't insert the images in a folder. Please you can show the way out. Thanks! This code is to save the image in a folder and then access it with the name to display, but is not saving the photos to the folder. I edited and include the form here, containing JavaScript and css .It looks some how messy but i'm a beginner. Thanks.
<?php
include("../views/post_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$usertext = $_POST["usertext"];
$image = $_FILES['image']['name'];
$talent =$_POST["talenttype"];
if(empty($usertext) || empty($image)|| empty($talent))
{
die();
}
$id = $_SESSION["id"];
$folder ="images/".basename($_FILES['image']['name']);
move_uploaded_file($_FILES['image']['tmp_name'],$folder) ;
$query = mysqli_query($link,"SELECT * FROM `upload` WHERE id = '$id'");
$upload = mysqli_query($link,"INSERT INTO `upload` (description,image,talent,folder) VALUES('$usertext','$image','$talent','$folder ')");
}
?>
To display, I want the photos to be save to the folder, not saving. I used blob method not inserting into the database.
<?php
include("../views/feeds_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
$query = mysqli_query($link,"SELECT * FROM `upload` ");
if ($query === false)
{
die();
}
echo '<table>';
while ($run = mysqli_fetch_assoc($query))
{
echo '<tr>';
echo '<td>';?> <img src =" <?php echo $run["image"]; ?>" height=100 width=100> <?php echo '<td>';
echo '<td>'; echo $run["description"]; echo '<td>'; echo $run["folder"];echo '<td>';
echo '</tr>';
}
echo '</table>';
?>
The form here.
<?php
include("../public/header.php");
?>
<div><title>post</title></div>
<style>
.form-inline
{
text-align: center;
margin-bottom: 50px;
}
</style>
<script type="text/javascript">
function validate(){
var usertext = document.getElementById("usertext");
var talent = document.getElementById("talenttype");
var image = document.getElementById("image");
if (usertext.value === "" && talent.value === "" && image.value ==="")
{
alert("Field Must Not be Empty");
}
}
</script>
<form class="form-inline" method ="POST" action ="post.php" enctype="multipart/form-data" onsubmit= "return validate();">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3"> </label>
<textarea class="form-control" id = "usertext" name ="usertext" rows="5" placeholder="Describe Person Here"></textarea> <br><hr>
<label class="sr-only" for="exampleInputEmail3"></label><br>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="file" class="form-control" id = "image" id="exampleInputPassword1" name="image" placeholder="image">
</div> <br><br><br> <hr>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="text" class="form-control" id = "talenttype" id="exampleInputPassword1" name = "talenttype" placeholder="Talent-Type"><br><br>
</div> <hr>
<div>
<button type="submit" name ="post" class="btn btn-default">Post</button><br>
</div>
</div>
</form>
<?php
include("../public/footer.php");
?>
I was having permission issues, the images folder permission was changed. That solves everything. Thanks!
First of all before i show you the code i will explain how my webpage works.
User selects date -> AJAX Calls On Date Change
Resulting PHP data displays in two sections on page.
First Section is Orders Table Contents
Second Section is Items Table Contents (not including the items inside Orders)
What i am trying to add is functionality to 3 buttons that will change the tables dynamically using AJAX.
I currently have working non ajax requests.
Here is the Code:
$(document).ready(function(){
$('.date-picker').change(function(){
$.ajax({
type: 'POST',
url: 'php/getproduct.php',
data: {dateorderpicker: $('.date-picker').val()},
dataType: 'JSON',
success: function(data)
{
$("#cartrow").html(data.result_1);
$("#otheritems").html(data.result_2);
}
});
});
});
PHP file for Current AJAX:
session_start();
include('db_config.php');
$datepicker = $_POST['dateorderpicker'];
$sql = "SELECT * FROM orders WHERE deliveryDate = ? AND customerId = ? ";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $datepicker, PDO::PARAM_STR);
$stmt->bindParam(2, $_SESSION['customer_id'], PDO::PARAM_INT);
$stmt->execute();
$container = array();
$data['result_1'] = $data['result_2'] = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$container[] = "'{$row['itemName']}'"; // put them inside a temporary container
$data['result_1'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/edit.php" method="post" class="form-inline pull-right">
<h3>' . $row['itemName'] . '</h3>
<h4>Total Price: $'.$row['price'].'</h4>
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>Our best seller. Full of flavour.</p>
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" value="' . $row['qty'] . '">
</div>
</div>
<input type="hidden" name="id" value="'.$row['id'].'">
<button type="submit" name="update" class="btn btn-primary">Update</button>
<button type="submit" name="delete" class="btn btn-primary">Remove</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
if(!empty($container)){
$excluded_names = implode(',', $container);
$sql = "SELECT * FROM item WHERE itemName NOT IN($excluded_names)";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$price ="";
if ($_SESSION['customer_band'] == 'A') {
$price = $row['bandA'];
}
else if ($_SESSION['customer_band'] == 'B') {
$price = $row['bandB'];
}
else if ($_SESSION['customer_band'] == 'C') {
$price = $row['bandC'];
}
else if ($_SESSION['customer_band'] == 'D') {
$price = $row['bandD'];
}
else if ($_SESSION['customer_band'] == 'E') {
$price = $row['bandE'];
}
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input id="itemname" type="hidden" name="itemName" value="'.$row['itemName'].'">
<h3>$'.$price.'</h3><input id="price" type="hidden" name="pricetotal" value="'.$price.'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input id="description" type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input id="qty" type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" id="additem" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
}
else
{
$sql = "SELECT * FROM item";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$price ="";
if ($_SESSION['customer_band'] == 'A') {
$price = $row['bandA'];
}
else if ($_SESSION['customer_band'] == 'B') {
$price = $row['bandB'];
}
else if ($_SESSION['customer_band'] == 'C') {
$price = $row['bandC'];
}
else if ($_SESSION['customer_band'] == 'D') {
$price = $row['bandD'];
}
else if ($_SESSION['customer_band'] == 'E') {
$price = $row['bandE'];
}
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input type="hidden" name="itemName" value="'.$row['itemName'].'">
<h3>$'.$price.'</h3><input type="hidden" name="pricetotal" value="'.$price.'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" id="additem" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
}
echo json_encode($data);
exit;
Both Update and Delete PHP file:
include('db_config.php');
if (isset($_POST['update']))
{
$qty = $_POST['qty'];
$id = $_POST['id'];
echo $id;
$sql = "UPDATE orders SET qty=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($qty,$id));
header('Location: ../order.php');
}
if (isset($_POST['delete']))
{
$id = $_POST['id'];
$sql = "DELETE FROM orders WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
header('Location: ../order.php');
}
The code above needs to be converted to AJAX, and both sections on the page using ajax should update the table automatically. It might be that you will call the first ajax query to reload the tables correctly?
Thanks for having a look at this.
I am having trouble wrapping my head around how i should get this work.
Alex
It is easy you can give a class (NOTE : yes class ) to your update button and similarly to delete button
Suppose your update button has class "update_task"
but your content was added to DOM after DOM already loaded, so you will need to create two ajax request with DELEGATE Methods for delete and update.
For delegate reference -
http://api.jquery.com/delegate/
// for update
$("body").delegate(".update_task","click",function(){
current_id = $(this).previous("input:hidden").val() // for current update button id,
$.ajax({
type: 'POST',
url: 'php/update_product.php',
data: {id: current_id, othervalues: other_value_of_choice},
dataType: 'JSON',
success: function(data)
{
if(data==1)
{
// what ever you want to do if data has been updated
}
}
});
});
Send AJAX request to PHP for update/delete. Return result of operation (true/false).
If result is true, update/remove from html with javascript(jquery).
By the way, don't use redirect, when you call php via ajax.