Ajax call in codeigniter - php

i actually want to use ajax in CodeIgniter to update value in the database.
below is the code given:
views/list_user.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Admin Panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/screen.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.round_button_circle').click(function() {
//Now just reference this button and change CSS
//$(this).css('background','green');
var id=this.value;//Getting the id of the user to update the status from unpublish to publish
var url='<?php echo base_url(); ?>index.php/ajax_controller/user_status';
alert(id+url);
$.ajax({
type: 'POST',
url: 'url', //We are going to make the request to the method "list_dropdown" in the match controller
data: 'id='+id, //POST parameter to be sent with the tournament id
success: function(data)
{
}
});
});
});
</script>
</head>
<body>
<div id="page-heading">
<div class="button">Create User</div><!--create category-->
<h1>USERS</h1><!--users's list-->
</div>
<!-- end page-heading -->
<table border="0" style="width:97%;margin:0px auto" cellpadding="0" cellspacing="0" id="content-table">
<tr>
<td>
<!-- start content-table-inner START -->
<div id="content-table-inner">
<div class="stdiv"><div class="msg1">
<?php
if(isset($_GET['msg']))
{
$msg=$_GET['msg'];
if($msg=="usertype")
{
echo "User has been Created";
}
if($msg=="create")
{
echo "User has been Created";
}
if($msg=="delete")
{
echo "User has been Deleted";
}
if($msg=="update")
{
echo "User has been Updated";
}
}
?>
</div>
</div>
<!-- start category-table -->
<table border="0" cellpadding="0" style="width:100%;margin:0px auto" cellspacing="0" id="product-table">
<tr>
<tr>
<th class="tbl_hdr">USER ID</th> <!--ID-->
<th class="tbl_hdr">‫NAME</th> <!--Name-->
<th class="tbl_hdr">EMAIL</th> <!--Email-->
<th class="tbl_hdr">PHONE NUMBER‎</th> <!--ph number-->
<th class="tbl_hdr">STATUS</th> <!--publish/unpublish-->
<th class="tbl_hdr" colspan="2">ACTION</th> <!--edit/delte-->
</tr>
<?php foreach($users as $user){?>
<tr>
<td><?php echo $user->id;?></td>
<td><?php echo $user->username;?></td>
<td><?php echo $user->email;?></td>
<td><?php echo $user->contact;?></td>
<td ><button id="status" class="round_button_circle" value="<?php echo $user->id;?>"></button></td>
</tr>
<?php }?>
</table>
<!-- end product-table................................... -->
</div>
<!-- end content-table -->
<!-- start paging..................................................... -->
<!-- end paging................ -->
<div class="clear"></div>
<!-- end content-table-inner ............................................END -->
</td>
</tr>
</table>
<div class="clear"> </div>
</div>
<!-- end content -->
<div class="clear"> </div>
</div>
<!-- end content-outer........................................................END -->
<div class="clear"> </div>
<!-- start footer -->
</body>
</html>
controller/ajax_controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_Controller extends CI_Controller {
// Show view Page
// This function call from AJAX
public function user_status()
{
$id=$this->input->post('id');
$data = array(
'status' => 1
);
$this->db->where('id', $id);
$this->db->update('tbl_users', $data);
echo "1";
}
}
Its giving me the url and the id which i want to update in the database in the alert box...but its not updating the value in the database once the button is clicked..
Can anyone help???

There is one mistakes in your code.
Change
url: 'url', // in ajax call
To
url: url, // do not use quotes with url variable

Related

How can I download a file using a button from fetched row

I was able to fetch and display the data but I am unable to download the file using dowload button.
I am storing images inside a folder call images in root. [http://localhost/images/]
How can I actually download a file using this download button?
My Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Records</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style type="text/css">
.bs-example{
margin: 20px;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</head>
<body>
<div class="bs-example">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="page-header clearfix">
<h2 class="pull-left">Records</h2>
</div>
<?php
include_once 'dbconfig.php';
$result = mysqli_query($conn,"SELECT * FROM book");
?>
<?php
if (mysqli_num_rows($result) > 0) {
?>
<button type="Home" name="change" onclick="window.location.href='mgrmenu.php'">Home</button>
<table class='table table-bordered table-striped'>
<tr>
<td>Name</td>
<td>Age</td>
<td>Mobile</td>
<td>File</td>
</tr>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row["Fname"]; ?></td>
<td><?php echo $row["age"]; ?></td>
<td><?php echo $row["patientNo"]; ?></td>
<td><?php echo $row["images"];?><Button> Download</Button></td>
</tr>
<?php
$i++;
}
?>
</table>
<?php
}
else{
echo "No result found";
}
?>
</div>
</div>
</div>
</div>
</body>
</html>
How can I create my download button to actually download that particular file?
<a href="/path/to/image" download>
<img src="/path/to/image" />
</a>
If you want to download any file on clicking a button you must try this:
<a class="btn" href="<?= $your_path_to_file ?>" download>Download File</a>

How to pass php variable to a new page for deleting a row from the database?

On the list.php page, I am passing a variable using hidden input method in form.
This form redirects to listd.php where the variable is used to run an SQL query to delete a particular row from the database where the variable==name.
If I print the variable on listd.php before processing SQL query then it is visible but during when query is processed it gives unidentified index error.
The code in listd.php works if I take input from the user on the same page.
list.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sports </title>
<link rel="stylesheet" href="main.css" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Tangerine">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Great+Vibes|Roboto|Barrio" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<?php
require ("config.php");
?>
<div class="row">
<div class="container-fluid">
<div class="jumbotron text-center">
<h3> List Events</h3>
<?php
session_start();
if($_SESSION['username'])
echo "<h2>Welcome ".$_SESSION['username']."!</h2>";
else
header('location:index.php');
//session_start();
if(isset($_SESSION['username']))
echo "<h3><a href='logout.php'>Logout</a></h3>";
?>
</div>
</div>
</div>
<div class="container">
<h2>Hover Rows</h2>
<p>The .table-hover class enables a hover state on table rows:</p>
<table class="table table-hover">
<thead>
<tr>
<th>Event </th>
<th>Add</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<!--
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
-->
<?php
{$result="SELECT name FROM events";
$q = mysqli_query($conn,$result) or die(mysql_error());
while ($row=mysqli_fetch_array($q))
{
echo "<tr> <td>";
echo $row['name'];
echo "</td>";
echo "<td>";
echo '<button> Add </button> <br><br>';
echo "</td>";
echo "<td>";
echo '<form action="liste.php" method="post" >';
echo '<input type="hidden" name="edit" value="';?>
<?php echo $row['name'];
echo'"> <input type="submit" value="Edit">';
echo "</form>";
echo "</td>";
echo "<td>";
echo '<form action="listd.php" method="post" >';
echo '<input type="hidden" name="del2" value="';?>
<?php echo $row['name'];
echo'"> <input type="submit" value="Delete">';
echo "</td>";
echo "</form>";
}
}
?>
<!--
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
-->
</tbody>
</table>
</div>
</body>
</html>
listd.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sports </title>
<link rel="stylesheet" href="main.css" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Tangerine">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Great+Vibes|Roboto|Barrio" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<?php
require ("config.php");
?>
<div class="row">
<div class="container-fluid">
<div class="jumbotron text-center">
<h3> Events </h3>
<div class="row">
<div class="container-fluid text-primary text-center">
<br>
<button class="btn"> Add </button> <br><br>
<button class="btn"> Edit </button> <br><br>
<button class="btn"> Delete </button> <br><br>
<button class="btn"> View </button> <br><br>
</div>
</div>
<?php
session_start();
?>
<form action="listd.php" method="post" class="a">
<table>
<tr>
<td> Category Name </td>
<td>
<strong>
<?php echo $_POST["del2"];
$k=$_POST['del2'];
?>
</strong>
</td>
</tr>
<tr>
<td></td>
<td> <input type="submit" value="Delete" name="delete"> </td>
</tr>
</table>
</form>
<?php
$event=$k;
if(isset($_REQUEST['delete'] )&& $event )
{
$sql="DELETE FROM events WHERE name='$event'";
if(mysqli_query($conn,$sql))
{
echo "deleted Succesfully";
//header('location:listd.php');
}
else
echo "error";
}
?>
</div>
</div>
</div>
</body>
</html>
It's really not necessary to use two forms to do this, unless this is a very dangerous action. this is also the source of your problem. $k is not preserved on the second postback. Requests are stateless. When you submit the second form, the listd.php script runs again from the start, and the values assigned to variables the last time it ran. This is the normal behaviour of HTTP requests in general.
A single-form version might look like this:
list.php
<?php
//this needs to be before anything else otherwise the redirect might fail due to headers already sent.
session_start();
if(isset($_SESSION['username'])) //corrected to use isset(). Only one test for this is needed.
{
echo "<h2>Welcome ".$_SESSION['username']."!</h2>";
echo "<h3><a href='logout.php'>Logout</a></h3>";
}
else
{
header('location:index.php');
die(); //script needs to die because webcrawlers/bots will ignore the redirect header, and view the rest of the page anyway, without permission. Using die() means the rest of the page never gets output.
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sports </title>
<link rel="stylesheet" href="main.css" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Tangerine">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Great+Vibes|Roboto|Barrio" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<?php
require ("config.php");
?>
<div class="row">
<div class="container-fluid">
<div class="jumbotron text-center">
<h3> List Events</h3>
</div>
</div>
</div>
<?php
$message = null; //will hold any extra message to the user resulting from data processing actions (such as delete)
//only run the next section if del2 has been submitted from a postback.
if(isset($_POST['del2']))
{
$event = $_POST['del2'];
$sql= "DELETE FROM events WHERE name='$event'"; //here you should use parameterised queries, I will leave it to you to look this up online, using the link I gave in the comments.
if(mysqli_query($conn,$sql))
{
$message = "Deleted succesfully";
}
else
{
$message = "error";
//here you should check mysqli_error() and log the output somewhere (not visible to the user)
}
}
?>
<div class="container">
<h2>Hover Rows</h2>
<!-- here is an example of how you can inject the confirmation message into somewhere suitable in the page. You can modify this to suit your needs. -->
<?php if ($message != null) { echo "<p><b>".$message."</b></p>"; } ?>
<p>The .table-hover class enables a hover state on table rows:</p>
<table class="table table-hover">
<thead>
<tr>
<th>Event </th>
<th>Add</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
$result="SELECT name FROM events";
$q = mysqli_query($conn,$result) or die(mysqli_error()); //corrected to use mysqli_error not mysql_error
while ($row=mysqli_fetch_array($q))
{
echo "<tr> <td>";
echo $row['name'];
echo "</td>";
echo "<td>";
echo '<button> Add </button> <br><br>';
echo "</td>";
echo "<td>";
echo '<form action="liste.php" method="post" >';
echo '<input type="hidden" name="edit" value="';
echo $row['name'];
echo'"> <input type="submit" value="Edit">';
echo "</form>";
echo "</td>";
echo "<td>";
echo '<form action="list.php" method="post" >';
echo '<input type="hidden" name="del2" value="';
echo $row['name'];
echo'"> <input type="submit" value="Delete" onclick="return confirm("Are you sure?");>'; //adds a confirmation dialog box to the delete button
echo "</td>";
echo "</form>";
}
?>
</tbody>
</table>
</div>
</body>
</html>
You do not need listd.php at all.
P.S. A separate hint: I see you are copying the same HTML <head> etc material into every page script. This is not necessary. You can create two files e.g. header.php and footer.php. In header.php you can put the opening <html> and <head> tags right down to <body> and any other enclosing tags necessary for the consistent layout of all your pages. Then in footer.php you can put the equivalent closing tags. And then in all the other pages of your site you can simply write <?php require_once("header.php"); ?> as the first line and <?php require_once("footer.php"); ?> as the last line. Then any changes you need to make to the headers (e.g. new CSS files or something) are automatically applied to all the pages without tedious copy/paste actions. Although I suggested that you remove your second script here, you can do this for any other pages in your site. It's also a good general principle of code re-use which you can apply to all kinds of situations in your future code.
P.P.S. I'd also consider using an up-to-date doctype. The HTML5 doctype declaration is simply <!DOCTYPE html>. This will likely result in more consistent behaviour of the HTML and CSS in your page, and future-proofs your application against deprecation of older doctypes which are no longer in current use.

I can't update my basket at database(using ajax!) when a user changes the count of products that he/she bought?

I have a eshop. in user basket the user added some products. now he/she wants to change(increase or decrease) the number(count) of the products. I have wrriten this part with ajax but it doesn't work. every thing seems right! I don't know whats wrong! please help me...
"at the end I have added "update_order.php" page's code."
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
include('database.php');
$object=new myclass_parent;
?>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link href="css/bootstrap.min.css" rel="stylesheet"/>
<link href="css/bootstrap.rtl.min.css" rel="stylesheet"/>
<script type="text/javascript">
$(document).ready(function () {
$(".navbar-right li .navbar-brand").hide();
});
</script>
<title></title>
</head>
<body>
<?php
include('header.php');
?>
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<div class="container content info">
<h4>سبد خرید</h4>
<div class="row">
<div style="display:none;margin-top:10px;" id="err_alert" class="alert alert-danger ">
<span id="empty_err"> </span>
</div>
<div class="table-responsive">
<table class="table my_table">
<thead>
<tr>
<th>فروشنده</th>
<th>توضیحات کالا</th>
<th>تعداد</th>
<th>قیمت واحد</th>
<th colspan="2">قیمت کل</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_COOKIE['mybasket'])){
$query="select * from tblbasket where cookiename=? and payment=0";
$array=[$_COOKIE['mybasket']];
$result_array=$object->select($query,$array);
foreach($result_array as $result){
$productid=$result['productid'];
$count=$result['count'];
$query2="select * from tblproducts where id=?";
$array2=[$productid];
$result_array2=$object->select($query2,$array2);
$img=$result_array2[0]['img'];
$title=$result_array2[0]['title'];
$price=$result_array2[0]['price'];
$info=$result_array2[0]['info'];
?>
<tr id="<?php echo $productid; ?>" class="pitem">
<td rowspan=''>amazoon.com</td>
<td>
<img src="<?php echo $img; ?>" width="100" height="80"/>
<div>
<strong><?php echo $title; ?></strong>
<p><?php echo $info; ?></p>
</div>
</td>
<td>
<input style="width:50px" type="number" id="pcount" class="pcount"
onKeyDown="return checknumber(event);" min="1" value="<?php echo $count; ?>">
</td>
<td><span id="pprice"><?php echo $price; ?></span> تومان</td>
<td><span id="kol_price"><?php echo $count*$price; ?></span> تومان</td>
<td><a style="cursor:pointer;" class="remove"><img src="images/delete.png" alt="حذف محصول" title="حذف محصول"/></a></td>';
<?php
}//foreach
?>
</tr><!--basket_items-->
</tbody>
</table>
<br/>
</div>
</div>
<?php
}//isset cookie
?>
<div class="row">
<div class="col-12">
<table class="table-responsive tbl jamkharid">
<thead>
<tr><th>پیش فاکتور خرید</th></tr>
<tr><th>مبلغ کل</th><th>مالیات 9%</th><th>هزینه ارسال</th> <th>مبلغ پرداختی نهایی</th></tr>
</thead>
<tbody>
<td><span id="jam_kharid"></span> تومان</td><td><span id="maliat"></span> تومان</td>
<td><span id="delivery">0</span> تومان</td><td><span id="jam_kharid_final"></span> تومان</td>
</tbody>
</table>
</div><!--col12-->
</div><!--row-->
<div class="row">
<?php if(isset($_SESSION['email'])){ ?>
مرحله بعد
<?php }//if
else{
?>
مرحله بعد
<?php }//else ?>
</div>
</div>
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<?php
include('footer.php');
?>
</body>
</html>
<script>
var timer;
function jam_kharid(){
var amount=0;
var buy_amount=0;
clearTimeout(timer);
timer=setTimeout(function(){
$(".pitem").each(function(index, element) {
var pcount=$(this).find("#pcount").val();
var pprice=$(this).find("#pprice").text();
amount=amount+parseInt(pcount)*parseInt(pprice);
buy_amount=(1.09*amount).toFixed(0);
});//each pitem function
$(".pitem .pcount").change(function(){
var pcount=$(this).val();
var pprice=$(this).parents(".pitem").find("#pprice").text();
var kol_price=parseInt(pcount)*parseInt(pprice);
$(this).parents(".pitem").find("#kol_price").text(kol_price);
jam_kharid();
//****************************************************************************************************************
var productcount=pcount;
var productid=$("#pcount").parents(".pitem").attr('id');
alert(productid);
$.ajax({
url:'update_order.php',
type:'POST',
data:{productid:productid,cookiename:<?php echo $_COOKIE['mybasket']; ?>,productcount:productcount}
})//ajax
.done(function(msg){
alert(msg);
})//done
//****************************************************************************************************************
});//change
$(".jamkharid").find("#jam_kharid").html(amount);
$('.jamkharid').find("#maliat").text(amount*0.09);
$('.jamkharid').find("#jam_kharid_final").text((1.09*amount).toFixed(0));
},600);
}//jam_kharid
jam_kharid();
function khali(){
var l=$('.pitem').length;
if(l==0){
$('#err_alert').show(300); $('#err_alert #empty_err').show(); $('#err_alert #empty_err').html('هیچ محصولی در سبد خرید شما موجود نمی باشد!');
$('.my_table').hide();
$('.jamkharid').hide();
}
}//function p_length
khali();
$(".remove").click(function(){
var id_pitem=$(this).parents(".pitem").attr('id');
var pitem_parent=$(this).parents(".pitem");
$.ajax({
url:'delete.php',
type:'POST',
data:{id:id_pitem}
})//ajax
.done(function(){
pitem_parent.remove();
alert('محصول مورد نظر حذف شد');
jam_kharid();
khali();
})//done
})//remove click function
function checknumber(e){
if( (e.keyCode==65 && e.ctrlKey) || (e.keyCode>=35 && e.keyCode<=40) || ($.inArray(e.keyCode,[8,46])!=-1) ){
return;
}//if
if( e.shiftKey || ((e.keyCode<48 || e.keyCode>57) && (e.keyCode<96 || e.keyCode>105)) ){
e.preventDefault();
}//if
}//checknumber
</script>
////////////////////////////////////////////////////////////////////////////////
update_order.php :
////////////////////////////////////////////////////////////////////////////////
<?php
include('database.php');
$object=new myclass_parent;
$product_id=intval($_POST['productid']);
$cookie_name=$_POST['cookiename'];
$product_count=intval($_POST['productcount']);
$query_update="update tblbasket set count=? where cookiename=? and productid=? and payment=0";
$array=array($product_count,$cookie_name,$product_id);
$object->myquery($query_update,$array); echo $product_id;
?>

Form if then Else/ifElse HTML on submit

I have a form that I need to act in specific ways. Example: User brings equipment back: I don't want that to show up in my form. User takes equipment out: I want it to generate to my form, they enters some information, form sends information to database. User takes equipment out: it too generates said form, he doesn't enter any information, form submits information after 20 sec, information is in database.
I was doing a simple page refresh to get the information into my form but that was pulling all the equipment that had been brought into the warehouse that day. So I commented that out and then I would get stuck on my ajax page.
I then tried creating a new php page that had a 301 page refresh and that worked to get the page back to my index page, however, my form wasn't working properly and so I commented out the auto submit and now my form works great... except I can't fulfill this last requirement where the page will submit the data if the user forgets to put his equipment information in.
I'm looking to do an if/then/else type of page submission. However, I can't figure out how to do one purely in either php or html. This is what I have figured out so far but it doesn't work and I know I'm way off somewhere.
<!DOCTYPE html>
<html>
<body>
<!--This is the one that is currently commented out in my code
<script type="text/javascript">
window.setTimeout(function() {
window.location = 'index.php'},1000*2);
</script>
</body>
</html> -->
//This is my pipe dream
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case ‘DONE’:
document.getElement('formSubmit').submit();
break;
}
} else {
<script type="text/javascript">
window.setTimeout(function(){
document.getElement('formSubmit').submit();
},1000*30);
</script>
}
?>
I don't know that much about jQuery other than going through a codecademy, and I know even less javascript. I'm a database person that got "conned" into building an advanced form/webpage. So I'm learning PHP, CSS, jQuery and HTML as I code.
Index.php:
<!DOCTYPE html>
<html>
<head>
<meta name=“Warehouse 3962” content="width=device-width, initial-scale=1.0">
<link href="style.css" type="text/css" rel="stylesheet">
<script type="text/javascript">
<!—window.setTimeout(function(){
document.getElement(‘formSubmit').submit();
},1000*30); —>
</script>
</head>
<body>
<section class="w">
<div class="row">
<div class="small columns">
<img src="logo.png" />
<h3 class="green">Users</h3>
</div>
<h6>Warehouse 3962</h6>
</div>
<div class="row">
<div class="small columns">
<form action="ajax.php" method="post" id="formSubmit">
<table id="equipment-table">
<thead>
<tr>
<th>Equipment</th>
<th>Amount</th>
<th>Val1</th>
<th>Val2</th>
</tr>
</thead>
<tbody>
<?php foreach
($results['tags'] as $equipment) {
if ($equipment['category'] == "Part") { ?>
<tr>
<td><?= $equipment['Amount']; ?></td>
<td class="text-center"><?= $equipment[‘quantity']; ?></td>
<td><input type="text" name="val1" /></td>
<td><input type="text" name="val2" /></td>
</tr>
<?php } // end if
} // end foreach ?>
<tr>
<td colspan="4" style="text-align: right;"><input type="submit" class="button" name="DONE" value="DONE" /></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</section>
</body>
</html>
Please try this new solution. This will send a post every 30 seconds containing only the input boxes containing text on them.
<!DOCTYPE html>
<html>
<head>
<meta name="Warehouse 3962" content="width=device-width, initial-scale=1.0">
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<section class="w">
<div class="row">
<div class="small columns">
<img src="logo.png" />
<h3 class="green">Users</h3>
</div>
<h6>Warehouse 3962</h6>
</div>
<div class="row">
<div class="small columns">
<form action="ajax.php" method="post" id="formSubmit">
<table id="equipment-table">
<thead>
<tr>
<th>Equipment</th>
<th>Amount</th>
<th>Val1</th>
<th>Val2</th>
</tr>
</thead>
<tbody>
<?php
foreach ($results['tags'] as $equipment) :
if ($equipment['category'] === "Part") :
?>
<tr>
<td>
<?php echo $equipment['Amount']; ?>
</td>
<td class="text-center">
<?php echo $equipment['quantity']; ?>
</td>
<td>
<input id="<?php echo $equipment['number'];?>-val1" type="text" name="<?php echo $equipment['number'];?>-val1"/>
</td>
<td>
<input id="<?php echo $equipment['number'];?>-val2" type="text" name="<?php echo $equipment['number'];?>-val2"/>
</td>
</tr>
<?php
endif;
endforeach;
?>
<tr>
<td colspan="4" style="text-align: right;">
<input type="submit" class="button" name="DONE" value="DONE" />
</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</section>
<script type="text/javascript">
function sendData() {
var inputs = document.getElementById('equipment-table').getElementsByTagName('input'),
data = [],
name, val1, val2;
for (var i = 0; i < inputs.length; i++) {
if ( inputs[i].type === 'submit') {
continue;
}
if ( inputs[i].value ) {
name = inputs[i].name.split('-val');
val1 = inputs[i].name.split('val1');
if (val1.length > 1) {
data.push({name: name[0], val1: inputs[i].value});
}
else {
data.push({name: name[0], val2: inputs[i].value});
}
}
}
window.setTimeout(function() {
sendData();
},30000);
}
sendData();
</script>
</body>
</html>
You cannot mix PHP with JavaScript and why you set a timeout to 1000*30, that is equal to set a timeout to 30000 which means 30 seconds.
Then, you can use the 'require' attribute in the input filed to force the user to fill the required information.
<!DOCTYPE html>
<html>
<head>
<meta name="Warehouse 3962” content="width=device-width, initial-scale=1.0">
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<section class="w">
<div class="row">
<div class="small columns">
<img src="logo.png" />
<h3 class="green">Users</h3>
</div>
<h6>Warehouse 3962</h6>
</div>
<div class="row">
<div class="small columns">
<form action="ajax.php" method="post" id="formSubmit">
<table id="equipment-table">
<thead>
<tr>
<th>Equipment</th>
<th>Amount</th>
<th>Val1</th>
<th>Val2</th>
</tr>
</thead>
<tbody>
<?php
foreach ($results['tags'] as $equipment) :
if ($equipment['category'] == "Part") : ?>
<tr>
<td><?= $equipment['Amount']; ?></td>
<td class="text-center">
<?php echo $equipment[‘quantity']; ?>
</td>
<td>
<input id="val1" type="text" name="val1”/>
</td>
<td>
<input id="val2" type="text" name="val2"/>
</td>
</tr>
<?php
endif;
endforeach;
?>
<tr>
<td colspan="4" style="text-align: right;">
<input type="submit" class="button" name="DONE" value="DONE" />
</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</section>
<script type="text/javascript">
window.setTimeout(function(){
var val1 = document.getElementById("val1").value,
val2 = document.getElementById("val1").value;
if ( ! val1 && ! val2 ) document.getElement('formSubmit').submit();
},30000);
</script>
</body>
</html>

Error while implementing implode ,explode array with php

I have this code, that picks article content from my word press db then outputs it onto a table, using a loop. once a user select the articles they like they submit the selection to my next page call it displaypage to display the selected articles.
the selection page code looks like this.
<?php /*
Template Name: News Selector Template
*/
//Pull the data
$posts = $wpdb->get_results
("
SELECT
p1.*,
wm2.meta_value
FROM
mp_posts p1
LEFT JOIN
mp_postmeta wm1
ON (
wm1.post_id = p1.id
AND wm1.meta_value IS NOT NULL
AND wm1.meta_key = '_thumbnail_id'
)
LEFT JOIN
mp_postmeta wm2
ON (
wm1.meta_value = wm2.post_id
AND wm2.meta_key = '_wp_attached_file'
AND wm2.meta_value IS NOT NULL
)
WHERE
p1.post_status='publish'
AND p1.post_type='post'
ORDER BY
p1.post_date DESC LIMIT 0,30
");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div class="container">
<div class="header"><img src="/sample/images/logo_main_300x100px.png" alt="logo" name="sample_logo" width="300" height="100" id="logo" style="background-color: #FFF; display:block;" />
<!-- end .header --></div>
<div class="content">
<h1>sample Top 30 Articles</h1>
<p>Select the articles you want to add to the newsletter</p>
<form action="http://sample.net/brands/sample/newsletter/" method="post">
<table width="960" border="2" summary="A collection of all the articles">
<caption>
Article Selection
</caption>
<tr>
<th scope="col">Select</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
<th scope="col">Cover</th>
<th scope="col">link</th>
</tr>
<?php
// if(isset($_POST['submit'])){
if (have_posts($posts)) {
// var_dump($posts); die();
foreach($posts as $post) {
//foreach($_POST['article_list'] as $post){
?>
<tr>
<th scope="row"><input type="checkbox" name="article[]" value="<?php echo $post->ID; ?>" /></th>
<td headers="article[]"><?php echo $post->post_title; ?></td>
<td headers="article[]"><?php echo $post->post_excerpt; ?></td>
<td headers="article[]"><?php echo '<img src="https://sample/wp-content/uploads/'.$post->meta_value.'" width="100px" alt="" />'?></td>
<td headers="article[]"><?php echo $post->guid; ?></td>
</tr>
<?php
}
}
?>
<p><input type="hidden" name="metas" value="<?php echo implode(",", $post); ?>"></p>
</table>
<div>
<p><input type="submit" name="Generate" value="submit"/></p>
</div>
</form>
<!---->
</div>
<!-- end .content --></div>
<div class="footer">
<p>sample Management System</p>
<!-- end .footer --></div>
<!-- end .container --></div>
</body>
</html>
Iv used implode to collect the array variables of all selected articles via a check box option.
on my display page i wrote this simple code to see the output of the array.
<?php /*
Template Name: Newsletter Template
*/
$posts = explode(",", $_POST['metas']);
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<?php echo $posts[0]->guid ?>
<?php echo $posts[0]->meta_value ?>
<?php echo $posts[0]->post_title ?>
<?php echo $posts[0]->post_excerpt ?>
</body>
</html>
Now when i submit the selected articles from the first page i'm supposed to be able to access the various array elements in my display page, but that's not the case. i get the
ERROR
Warning: implode(): Invalid arguments passed in
/home/sampled/public_html/brands/sample/wp-content/themes/newsample/page-newsselector.php
on line 164
i don't know where i went wrong with my implementation.
HELP PLEASE

Categories