$(document).ready(function() {
$(".eliminar").click(function(e) {
e.preventDefault();
var id = $(this).attr('data-id');
//alert(id);
$(this).closest('.holder-cesta').remove();
$.post('./php/carro_compra/eliminar.php', {
Id:id
},function(a) {
if (a=='0') {
location.href="./cesta";
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="holder-cesta">
<h4>Product 1</h4>
<button class="eliminar" data-id="1">Delete</button>
</div>
<div class="holder-cesta">
<h4>Product 3</h4>
<button class="eliminar" data-id="3">Delete</button>
</div>
<div class="holder-cesta">
<h4>Product 2</h4>
<button class="eliminar" data-id="2">Delete</button>
</div>
I'm creating the button to remove the added products.
Every product added in the cart, will have a delete button.
So my question is, how can i get the id by clicking the delete button.
I was do something like this:
if (isset($_SESSION['carrito'])) {
//Array con datos carrito.
$data = $_SESSION['carrito'];
$total = 0;
for ($i=0; $i<count($data); $i++) {
<div class="holder-cesta">
<h4><?php echo $data[$i]['Titulo']; ?></h4>
<button class="eliminar" data-id="<?php echo $data[$i]['Id']; ?>"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
<?php
}
} else {
echo "0 articulos";
} unset($arreglo);
?>
My jQuery script look like this:
$(document).ready(function() {
//Button click function.
$(".eliminar").click(function(e) {
e.preventDefault();
//Get the id attribut.
var id = $(this).attr('data-id');
//alert(id); (The alert work perfect).
//Remove the parent holder.
$(this).closest('.holder-cesta').remove();
//Control AJAX
$.post('http://domain.com/php/carro_compra/eliminar.php', {
Id:id
},function(a) {
if (a=='0') {
location.href="./cesta";
}
});
});
});
But i don´t get the ID in my eliminar.php, if i do something like this, it always ignored:
if ($arreglo[$i]['Id'] != $_POST['Id']) {
}
So $_POST['Id'], get nothing from AJAX. If i put the id manual, it work pretty.
Here i include the eliminar.php
<?php
//Session start
session_start();
//Get shoping cart data.
$arreglo = $_SESSION['carrito'];
//Reset.
$arr[] ='';
for ($i=0; $i<count($arreglo); $i++) {
if ($arreglo[$i]['Id']!= $_POST['Id']) {
$datosnuevos = ['Id' => $arreglo[$i]['Id'], 'Titulo' =>$arreglo[$i]['Titulo'], 'Precio' => $arreglo[$i]['Precio'], 'Icon' => $arreglo[$i]['Icon'], 'Cantidad' => $arreglo[$i]['Cantidad'] ];
$arr[] = $datosnuevos;
}
}
if (isset($arr)) {
$_SESSION['carrito'] = $arr;
$data = $_SESSION['carrito'];
$value_carrito = count($data);
$_SESSION['compras'] = $value_carrito;
echo "<script>window.location.reload();</script>";
} else {
unset($_SESSION['carrito']);
unset($_SESSION['compras']);
echo "0";
}
?>
Related
I used this ajax PHP code for lazy load and filter according to category, i want to combine both of them because lazy load works on first load but doesnt work with category buttons.
My AJAX code sends limit and start values to fetch.php and fetch data in the division
A 2nd ajax code sends cat_id to load-prod.php to filter data on button click
index.php
<div class="row">
<div class="col-md-12 p-3 text-center">
<span>Categories  </span>
<div class="btn-group" role="group" aria-label="Basic outlined example">
<button type="button" class="btn btn-outline-dark active showct" value="">All</button>
<?php echo show_cat(); ?>
</div>
</div>
<div class="col-md-12">
<div class="row row-cols-1 row-cols-md-3 g-4" id="showpr">
</div>
</div>
<div class="col-md-12 text-center p-3" id="datamsg"></div>
</div>
//lazy load
<script>
var limit = 9; //The number of records to display per request
var start = 0; //The starting pointer of the data
var action = 'inactive'; //Check if current action is going on or not. If not then inactive otherwise active
function lazyload(limit, start)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{limit:limit, start:start},
cache:false,
success:function(data)
{
$('#showpr').append(data);
if(data == '')
{
$('#datamsg').html("<button type='button' class='btn btn-dark' disabled>No more data</button>");
action = 'active';
}
else
{
$('#datamsg').html("<button type='button' class='btn btn-outline-dark' disabled>Loading More...</button>");
action = 'inactive';
} }});}
if(action == 'inactive')
{
action = 'active';
lazyload(limit, start);
}
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $(document).height() - 100 && action== "inactive")
{
action = 'active';
start = start + limit;
setTimeout(function(){
lazyload(limit, start);
}, 1000);}});
</script>
//show according to category
<script>
$(document).ready(function(){
$('.showct').click(function(){
var cat_id = $(this).val();
$.ajax({
url:"load-prod.php",
method:"POST",
data:{cat_id:cat_id},
success:function(data){
$("#showpr").html(data);
}});
});});
</script>
load-prod.php
<?php
include ('connect.php');
global $con;
if(isset($_POST["cat_id"]))
{
if($_POST["cat_id"]!='')
{
$cf = "select * from products where c_id = '".$_POST['cat_id']."'";
}
else{
$cf = "select * from products";
}
$filter = mysqli_query($con,$cf);
while ($ctf=mysqli_fetch_array($filter)) {
echo "<div class='col-12'><h5 class='card-title'>".$ctf['name']."</h5>";
}
}
?>
fetch.php
<?php
include ('connect.php');
global $con;
if(isset($_POST["limit"], $_POST["start"]))
{
$query = "SELECT * FROM album ORDER BY id ASC LIMIT ".$_POST["start"].", ".$_POST["limit"]."";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo "<div class='col-12'><h5 class='card-title'>".$row['name']."</h5>" ;
}
}?>
I have a problem my delete function does not work he does not delete the organisation. When I press the button it show the text if I want to delete it I say yes but it only refreshes the site. I am not an advanced programmer and some of the code I did not write myself someone else worked on the project before me so idk why he some codes are written this way and he did not use any framework.
My code
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_FILES['croppedImage'])) logoChange();
// change organisation information is not made yet
if (isset($_POST['update'])) echo "This function is not made yet!";
if (isset($_POST['deleteOrganisation'])) DeleteOrganisations();
}
//this is the logoChange function
function logoChange() {
include '../../../include/db_conn.php';
//get organisation_id
$organisation_id = $_POST['organisation_id'];
//blob file info
$fileName = $_FILES['croppedImage']['name'];
$fileTmpName = $_FILES['croppedImage']['tmp_name'];
$fileSize = $_FILES['croppedImage']['size'];
$fileError = $_FILES['croppedImage']['error'];
//change blob to png
$fileType = 'png';
//check if image is able to upload
if ($fileError === 0) {
//check if file is not too big change number to needs!
if ($fileSize < 1000000) {
//make new random filename
$fileNameNew = uniqid('', true).".".$fileType;
$fileDesination = '../../../img/uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDesination);
//check if organisation already has a logo
$get_organisation_stmt = $conn->prepare('SELECT `organisation_logo` FROM `organisations` WHERE `organisation_id` = ?');
$get_organisation_stmt->bind_param('s', $organisation_id);
$get_organisation_stmt->execute();
$result_organisation = $get_organisation_stmt->get_result();
$row = mysqli_fetch_assoc($result_organisation);
if (is_null($row['organisation_logo'])) {
//if not inserted it
$sqlUpdateLogo = 'UPDATE `organisations` SET `organisation_logo`="'.$fileNameNew.'" WHERE `organisation_id` ="'.$organisation_id.'"';
mysqli_query($conn, $sqlUpdateLogo);
echo 'image inserted';
} else {
//else replace it
unlink('../../../img/uploads/'.$row['organisation_logo']);
$sqlUpdateLogo = 'UPDATE `organisations` SET `organisation_logo`="'.$fileNameNew.'" WHERE `organisation_id` ="'.$organisation_id.'"';
mysqli_query($conn, $sqlUpdateLogo);
echo 'image replaced';
}
}
else {
echo "File to big";
}
} else {
echo "Error in file";
}
}
// here i made the delete function
function DeleteOrganisations() {
include '../../../include/db_conn.php';
//delete the organisation
$getDeleteOrganisation = $_POST['deleteOrganisation'];
$delete_organisation_stmt = $conn->prepare('DELETE FROM `organisations` WHERE `organisation_id`= ?');
$delete_organisation_stmt->bind_param('i', $getDeleteOrganisation);
$delete_organisation_stmt->execute();
$delete_organisation_stmt->close();
}
here are the functions and here is JavaScript
//link for datatable functions
$(document).ready(function(){
$('#organisations').DataTable({
"columnDefs": [
{ "orderable": false, "targets": [0, 5] }
],
"order": [[ 1, "asc" ]]
});
});
//open edit modal for logo
$(document).on("click", ".btnopenEditLogo", function(e) {
event.preventDefault();
var organisationId = $(this).val();
var url = "functions/getOrganisationActions.php";
$.ajax({
type: 'POST',
url : url,
data: {'HiddenLogoid': organisationId},
success: function (data) {
$('#myLogoEditModal').modal('show');
$("#myLogoEditModal .modal-body").html(data);
}
});
});
//open modal with info of user for editing
$(document).on("click", ".btnopenEditOrganisation", function(e) {
event.preventDefault();
var organisationId = $(this).val();
var url = "functions/getOrganisationActions.php";
$.ajax({
type: 'POST',
url : url,
data: {'HiddenOrganisationid': organisationId},
success: function (data) {
$('#myOrganisationEditModal').modal('show');
$("#myOrganisationEditModal .modal-body").html(data);
}
});
});
//delete organisation
$(document).on("click", ".btnRemoveOrganisation", function(e) {
event.preventDefault();
var remove = $(this).val();
var url = "../cms/organisations/functions/postOrganisationActions.php";
Swal.fire({
title: 'Delete this test?',
text: "If you delete the test the questions and all statistics will be lost!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33'
}).then((result) => {
if (result.value) {
$.ajax({
type: 'POST',
url : url,
data: {'deleteOrganisation': remove},
success: function (data) {
Swal.fire({
title: 'Deleted!',
text: "You deleted the survey!",
type: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
}).then((result) => {
if (result.value) {
window.location.reload();
}
});
}
});
} else if (result.dismiss === Swal.DismissReason.cancel) {
Swal.fire (
'Cancelled',
'Your test is safe :)',
'error'
)
}
});
});
this is the index
<?php
session_start();
if (!isset($_SESSION["userId"])) {
header('Location: ../../auth/login');
die();
}
$activePage = "cms";
$activeCMSTab = "organisations";
?>
<!doctype html>
<html lang="en">
<head>
<title>Admin CMS | Organisations</title>
<!-- include header -->
<?php require '../../include/header.php'; ?>
</head>
<body class="d-flex flex-column">
<!-- include navbar -->
<?php require '../../include/navbar.php'; ?>
<!-- include organisation functions -->
<?php require 'functions/getOrganisationsActions.php'; ?>
<div id="main">
<div class="container">
<div class="row">
<div id="sidenav-border" class="col-lg-3 d-none d-md-none d-lg-block">
<?php require '../../include/cms_sidenav.php'; ?>
</div>
<div class="col-lg-9">
<div class="card-theme mt-3">
<div class="clearfix">
<h5 class="card-title-theme float-left"><i class="fas fa-building"></i> Organisation list:</h5>
<i class="fas fa-info-circle fa-fw mt-2 mr-2"></i>
</div>
<hr class="hr-theme" />
<div class="card-body">
<?php getOrganisations(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- footer -->
<?php require '../../include/footer.php'; ?>
<!-- logo modal -->
<?php require 'logo-edit-modal.php'; ?>
<!-- organisation modal -->
<?php require 'organisation-edit-modal.php'; ?>
<!-- logout modal -->
<?php require '../../auth/logout-modal.php'; ?>
<!-- include js scripts -->
<script src="js/organisationFunctions.js"></script>
</body>
</html>
you need get organisation where the button is made the button is at
<?php
function getOrganisations() {
//include DataBase connection
include '../../include/db_conn.php';
//show every organisation that is approved
$sqlCollectAllOrganisations = "SELECT * FROM `organisations` WHERE `approval_admin`='1'";
$resultAllOrganisations = mysqli_query($conn, $sqlCollectAllOrganisations);
echo '<div class="table-responsive">';
echo '<table id="organisations" class="table table-striped table-bordered table-hover">';
echo '<thead>';
echo '<tr>';
echo '<th>Logo</th>';
echo '<th>Organisation</th>';
echo '<th>Parent</th>';
echo '<th>type</th>';
echo '<th>Users</th>';
echo '<th>Tools</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
//Show organisations
if ($resultAllOrganisations->num_rows > 0) {
while ($row = $resultAllOrganisations-> fetch_assoc()) {
echo '<tr>';
//organisation logo
if ($row['organisation_logo'] == '')
echo '<td class="align-middle" align="center"><img src="../../img/stock/no-image-icon.png" class="rounded d-inline mr-1" width="30px"></img><button class="btn btn-link d-inline p-0 btnopenEditLogo" value="'. $row['organisation_id'] .'">edit</button></td>';
else
echo '<td class="align-middle" align="center"><img src="../../img/uploads/'. $row['organisation_logo'] .'" class="rounded border d-inline mr-1" width="30px"><button class="btn btn-link d-inline p-0 btnopenEditLogo" value="'. $row['organisation_id'] .'">edit</button></td>';
//organisation name
echo '<td class="align-middle">' .$row['organisation_name']. '</td>';
//organisation parent
if ($row['organisation_parent'] != null) {
$sqlCollectparent = "SELECT * FROM `organisations` WHERE `organisation_id`='".$row['organisation_parent']."'";
$resultparent = mysqli_query($conn, $sqlCollectparent);
if ($parent = $resultparent-> fetch_assoc()) echo '<td class="align-middle">'.$parent['organisation_name'].'</td>';
} else {
echo '<td class="align-middle"><i class="fas fa-times" style="font-size: 16px;"></i></td>';
}
//organisation type
echo '<td class="align-middle">' . $row['organisation_type'] . '</td>';
//count users
$sqlCountUsers = "SELECT COUNT(organisation_id) AS `count` FROM `users` WHERE `organisation_id`='".$row['organisation_id']."'";
$resultcount = mysqli_query($conn, $sqlCountUsers);
if ($count = $resultcount-> fetch_assoc()) echo '<td class="align-middle">'.$count['count'].'</td>';
//buttons
echo '<td class="align-middle text-center">';
echo '<div class="btn-group">';
echo '<button class="btn-theme btn-theme-success btn-theme-sm mr-1">Add user</button>';
echo '<button class="btn-theme btn-theme-primary btn-theme-sm mr-1 btnopenEditOrganisation" value="'. $row['organisation_id'] .'"><i class="fas fa-edit fa-fw"></i></button>';
if ($_SESSION['organisation_id'] != $row['organisation_id']) echo '<button type="button" class="btn-theme btn-theme-danger btn-theme-sm btnRemoveOrganisation" value=""><i class="fas fa-trash-alt fa-fw"></i></button>';
echo '</div>';
echo '</td>';
echo '</tr>';
}
} else {
//do nothing
}
echo '</tbody>';
echo '</table>';
echo '</div>';
}
?>
I have an error and it says "DataTables warning: table id=table - Ajax error. For more information about this error, please see http://datatables.net/tn/7". After that I went to inspect element and there's 1 error and says "Failed to load resource: the server responded with a status of 404 (Not Found)"
Controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class section_controller extends CI_Controller{
public function __construct()
{
parent:: __construct();
$this->load->model('section_model','section');
}
public function index()
{
$this->load->helper('url');
$this->load->view('section_view');
}
public function ajax_list()
{
$list = $this->section_model->get_datatables();
$data = array();
$no = $_POST['start'];
foreach($list as $section) {
$no++;
$row = array();
$row[] = $section->sec_ID;
$row[] = $section->secname;
$row[] = $section->sec;
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)"
title="Edit" onclick="edit_section('."'".$section->sec_ID."'".')"><i
class="glyphicon glyphicon-pencil"></i> Edit</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->section->count_all(),
"recordsFiltered" => $this->section->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
public function ajax_edit($sec_ID)
{
$data = $this->section->get_by_id($sec_ID);
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'sec_ID' => $this->input->post('sec_ID'),
'secname' => $this->input->post('secname'),
'sec' => $this->input->post('sec'),
);
$insert = $this->section->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'sec_ID' => $this->input->post('sec_ID'),
'secname' => $this->input->post('secname'),
'sec' => $this->input->post('sec'),
);
$this->section->update(array('sec_ID' => $this->input->post('sec_ID')),
$data);
echo json_encode(array("status" => TRUE));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('sec_ID') == '')
{
$data['inputerror'][] = 'sec_ID';
$data['error_string'][] = 'ID is required';
$data['status'] = FALSE;
}
if($this->input->post('secname') == '')
{
$data['inputerror'][] = 'secname';
$data['error_string'][] = 'Section name is required';
$data['status'] = FALSE;
}
if($this->input->post('sec') == '')
{
$data['inputerror'][] = 'dob';
$data['error_string'][] = 'Section is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
?>
Model:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class section_model extends CI_Model{
var $table = 'section';
var $column_order = array('sec_ID','secname','sec',null);
var $column_search = array('secname','sec');
var $order = array('sec_ID'=>'desc');
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with
OR clause better with bracket. because maybe can combine with
other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']
['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get_by_id($sec_ID)
{
$this->db->from($this->table);
$this->db->where('sec_ID',$sec_ID);
$query = $this->db->get();
return $query->row();
}
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
}
?>
And the View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sections</title>
<link rel="stylesheet" href="<?php echo
base_url('assets/bootstrap/css/bootstrap.min.css')?>">
<link rel="stylesheet" href="<?php echo
base_url('assets/datatables/css/jquery.dataTables.min.css')?>">
</head>
<body>
<br>
<div class="container">
<h1>Sections</h1>
<br>
<button class="btn btn-success" onclick="add_section()"><i
class="glyphicon glyphicon-plus"></i> Add Section</button>
<button class="btn btn-default" onclick="reload_table()"><i
class="glyphicon glyphicon-refresh"></i> Reload</button><br><br>
<table id="table" class="table table-striped table-bordered"
cellspacing="0" width="100%">
<thead>
<tr>
<th>Section ID</th>
<th>Section Name</th>
<th>Section</th>
<th>Actions</th>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>Section ID</th>
<th>Section Name</th>
<th>Section</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
</div>
<script src="<?php echo base_url('assets/jquery/jquery-3.3.1.min.js')?>">
</script>
<script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>">
</script>
<script src="<?php echo
base_url('assets/datatables/js/jquery.dataTables.min.js')?>"></script>
<script src="<?php echo
base_url('assets/datatables/js/dataTables.bootstrap.js')?>"></script>
<script type="text/javascript">
var save_method;
var table;
$(document).ready(function(){
table = $('#table').DataTable({
"processing": true,
"serverside": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('section_controller/ajax_list')?
>",
"type": "POST"
},
"columnDefs":[
{
"targets": [-1],
"orderable": false,
},
],
});
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
function add_section()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Section'); // Set Title to Bootstrap
modal title
}
function edit_section(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('section_controller/ajax_edit/')?
>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="sec_ID"]').val(data.sec_ID);
$('[name="secname"]').val(data.secname);
$('[name="sec"]').val(data.sec);
$('#modal_form').modal('show'); // show bootstrap modal
when complete loaded
$('.modal-title').text('Edit Section'); // Set title to
Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('section_controller/ajax_add')?>";
} else {
url = "<?php echo site_url('section_controller/ajax_update')?
>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax
table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i <
data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-
error'); //select parent twice to select div form-group class and
add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
//select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / updating data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
});
</script>
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Section Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Section
ID</label>
<div class="col-md-9">
<input name="sec_ID" placeholder="Section ID"
class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Section
Name</label>
<div class="col-md-9">
<input name="secname" placeholder="Section Name"
class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Section</label>
<div class="col-md-9">
<input name="sec" placeholder="Section"
class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn
btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-
dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
</html>
I'm using codeigniter with datatables,jquery and bootstrap plugin.
This is URLs' configuration problem . if your website enabled the Friendly URL or rewrite . you should see and check this configuration.
I have drag and drop jquery. Accordion that allows user to drag and drop names into a droppable area. So what i want to do is to display dropped names on a new page after user click submit. But I cant get how to do it. I thought maybe its can be done using ajax but not sure how. Thanks in advance. Here is my code:
<link href="jquery-ui/jquery-ui.css" rel="stylesheet" />
<script src="jquery-ui/jquery.js"></script>
<script src="jquery-ui/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("#myAccordion"). accordion({heightStyle:"content", active: false, collapsible:true});
$(".source li").draggable({helper:"clone"});
$("#project ol").droppable({
activeClass: "ui-state-default",
hoverClass: "ui-state-hover",
accept: ":not(.ui-sortable-helper)",
drop: function(event, ui)
{
$(this).find(".placeholder").remove();
$("<li></li>").text(ui.draggable.text())
.addClass("project-item")
.addClass('dropClass')
.appendTo(this);
}
}).sortable({
items: "li:not(.placeholder)",
sort: function() {
$(this).removeClass("ui-state-default");
}
});
$("#myAccordion ul").droppable({
drop: function(event, ui) {
$(ui.draggable).remove();
},
hoverClass: "ui-state-hover",
accept: '.project-item'
});
$('#box').keyup(function(){
var valThis = $(this).val().toLowerCase();
if(valThis == ""){
$('.source > li').show();
} else {
$('.source > li').each(function(){
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).show() : $(this).hide();
});
};
});
});
</script>
<div id="myAccordion" style="width:20%; float:left; margin-right:30px;">
<?php for($i=321; $i<347; $i++)
{
echo "<h3>".chr($i)."</h3>";
echo '<ul class="source">';
$sql = "SELECT username FROM user WHERE username LIKE '".chr($i+32)."%' ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$name= $row["username"];
echo"<li class='ui-state-highlight'>". $name ."</li>";
}
} else
{
echo "0 results";
}
echo '</ul>';
}
?>
</div>
<form class="formcss" method="POST" action="create3.php">
<fieldset style="background-color:white;">
<div id="project" style="margin-left:10%;">
<label>Leader:</label>
<ol>
<li class="placeholder" name="leader[]" <?php if (isset($leader[$i])) echo 'value="'.$leader[$i].'"' ?>>Add leaders and checkers here</li>
</ol>
<br><br>
<div class="row">
<input type = "submit" name ="submit" class="button" value = "Create Project" onclick="userSubmitted = true;"/>
</div>
</div>
</fieldset>
</form>
Hey i have a problem on my website i want to display a image with a rating under and then when i rate the image it should change to the next picture. And there is my problem because it displays the next picture correctly but it doesn't change the id in the rating system so i am rating the same picture again and again
Source code:
$place="upload/";
$first = mysql_query("SELECT * FROM images ORDER BY RAND()");
while($wor = mysql_fetch_array($first))
{
$id=$wor['id'];
$name = $wor['name'];
$image = $place . $wor['name'];
}
$number="1";
$wrongnumber="2";
$random = mysql_query("SELECT * FROM images ORDER BY RAND()");
$place="upload/";
echo '<script> ';
while($wor = mysql_fetch_array($random))
{
$ids=$wor['id'];
$name = $wor['name'];
$images = $place . $wor['name'];
$number=$number + 1;
$wrongnumber=$wrongnumber + 1;
echo 'function ' . 'changeSrc' . $number . '() '; ?>
{
document.getElementById("rand").src="<? echo $images;?>";
document.getElementById("button").onclick=changeSrc<? echo $wrongnumber;?>;
document.getElementById("102").id=<? echo $ids;?>;
}
<?
}
?>
</script>
<img id="rand" src="<? echo $image;?>"><br>
<div id="button" onclick="changeSrc2()">
<div class="rate_widget" id="102">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
</div>
The output code:
// This is the first thing we add ------------------------------------------
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'ratings.php',
out_data,
function(INFO) {
$(widget).data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
// can't use 'this' because it wont contain the updated data
set_votes($(this).parent());
}
);
// This actually records the vote
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
$.post(
'setcookie.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
// END FIRST THING
</script><script> function changeSrc2() {
document.getElementById("rand").src="upload/1329614519daily_erotic_picdump_48-2-500x334.jpg";
document.getElementById("button").onclick=changeSrc3;
document.getElementsByClassName('rate_widget').id="125";
}
function changeSrc3() {
document.getElementById("rand").src="upload/1329614453tumblr_leb4pwc0Xc1qzy9ouo1_1280-1024x640.jpg";
document.getElementById("button").onclick=changeSrc4;
document.getElementsByClassName('rate_widget').id="65";
}
function changeSrc4() {
document.getElementById("rand").src="upload/1329614295daily_erotic_picdump_20-copy-500x333.jpg";
document.getElementById("button").onclick=changeSrc5;
document.getElementsByClassName('rate_widget').id="44";
}
function changeSrc5() {
document.getElementById("rand").src="upload/1329614301daily_erotic_picdump_80-2-500x375.jpg";
document.getElementById("button").onclick=changeSrc6;
document.getElementsByClassName('rate_widget').id="51";
}
function changeSrc6() {
document.getElementById("rand").src="upload/13296142941-3-450x600.jpg";
document.getElementById("button").onclick=changeSrc7;
document.getElementsByClassName('rate_widget').id="225";
}
function changeSrc7() {
document.getElementById("rand").src="upload/1329614284tumblr_l53l0qM6HB1qc4zlyo1_500-450x568.jpg";
document.getElementById("button").onclick=changeSrc8;
document.getElementsByClassName('rate_widget').id="19";
}
function changeSrc8() {
document.getElementById("rand").src="upload/1329614454tumblr_lro15r2fkh1qzlro6o1_500-450x301.jpg";
document.getElementById("button").onclick=changeSrc9;
document.getElementsByClassName('rate_widget').id="73";
}
function changeSrc9() {
document.getElementById("rand").src="upload/tumblr_mccaolmQPE1regfy1o1_500.jpg";
document.getElementById("button").onclick=changeSrc10;
document.getElementsByClassName('rate_widget').id="272";
}
function changeSrc10() {
document.getElementById("rand").src="upload/1329614297Pix-Mix-304-img012-500x312.jpg";
document.getElementById("button").onclick=changeSrc11;
document.getElementsByClassName('rate_widget').id="47";
}
</script>
<img id="rand" src="upload/1329614465tumblr_lscy8aqOFE1qg7sdjo1_500-450x322.jpg"><br>
<div id="button" onclick="changeSrc2()">
<div class="rate_widget" id="99">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
</div>
document.getElementById("button").onclick=changeSrc<? echo $wrongnumber;?>;
Aren't you missing brackets?
document.getElementById("button").onclick=changeSrc<? echo $wrongnumber;?>();
By the way, to reduce data laod add LIMIT 1 to your SQL query when retrieving only one row.