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.
Related
I have below code to get more results on page scroll.
It works fine on localhost and on server laptop/desktop.
It does not work on mobile and does not load more results on scroll.
I cannot figure it out why this is happening or what is causing this not to work on mobile.
<?php
$getItemLID = $dba->prepare('SELECT MAX(id) as id FROM items
where status = ? AND ename like ?');
$getItemLID->bind_param('ss', $status,$param);
$getItemLID->execute();
$resultLID = $getItemLID->get_result();
$rowLID = $resultLID->fetch_assoc();
$thelastid = $rowLID['id'];
$status = 1;
$getscategory = $dba->prepare('SELECT * FROM mytable
where status = ?
order by id asc');
$getscategory->bind_param('s', $status);
$getscategory->execute();
$resultGSC = $getscategory->get_result();
while ($rowGSC = $resultGSC->fetch_assoc()) {
$scid = $rowGSC['id'];
$scename = $rowGSC['ename'];
?>
<div class="message_box" data-id="<?php echo $scid; ?>" style="padding-right: 5px;">
<div class="portfolio-item-wrap" style="border-radius: 3%;">
<span class="portfolio-description">
<h3><?php echo $scename; ?></h3>
</span>
</div>
</div>
<?php } ?>
<div id="msg_loaderw" style="display: none;">
<div class="card">
<div class="card-body">
<div class="d-flex align-items-center">
<strong>Loading...</strong>
<div class="spinner-border ml-auto" role="status" aria-hidden="true">
</div>
</div>
</div>
</div>
</div>
<div id="msg_loader">
</div>
<script>
$(document).ready(function () {
$(window).scroll(function () {
var thislastid = "<?php echo $thelastid; ?>";
if($(window).scrollTop() == ($(document).height() - $(window).height())) {
$("#msg_loaderw").show();
var msg_id = $(".message_box:last").data("id");
$.ajax({
type: "POST",
url: "inc/items/search_items_get.php",
data: {msg_id: msg_id},
cache: false,
success: function (data) {
//Insert data after the message_box
$(".message_boxx").append(data);
if (msg_id == thislastid) {
$("#msg_loaderw").hide();
$("#msg_loader").html('<hr><div class="card"><div class="card-body"><div class="align-items-center"><strong><center>That is all what we have for now.</center></strong></div></div></div>');
}
}
});
}
});
});
</script>
Below is : inc/items/search_items_get.php
<?php
include ('../default/db.php');
if (isset($_POST['msg_id']) && isset($_POST['msg_id']) !== NULL) {
$msg_id = $_POST['msg_id'];
$status = 1;
$limit = 12;
$getItem = $dba->prepare('SELECT * FROM mytable
where id > ? AND status = ?
order by id asc');
$getItem->bind_param('ss', $msg_id,$status);
$getItem->execute();
$resultItem = $getItem->get_result();
while ($rowItem = $resultItem->fetch_assoc()) {
$itemID = $rowItem['id'];
$itemName = $rowItem['ename'];
?>
<div class="message_box" data-id="<?php echo $itemID; ?>" style="padding-right: 5px;">
<div class="portfolio-item-wrap" style="border-radius: 3%;">
<span class="portfolio-description">
<h5><?php echo $itemName; ?></h5>
</span>
</div>
</div>
<?php
}
} else {
echo "Message ID is empty";
}
?>*emphasized text*
It seems it's a script issue just try changing the code a bit , hopefully it will work:
<script>
$(document).ready(function () {
$(window).scroll(function () {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
$("#msg_loaderw").show();
var msg_id = $(".message_box:last").data("id");
$.ajax({
type: "POST",
url: "inc/items/search_items_get.php",
data: {msg_id: msg_id},
cache: false,
success: function (data) {
//Insert data after the message_box
$(".message_boxx").append(data);
if (msg_id == thislastid) {
$("#msg_loaderw").hide();
$("#msg_loader").html('<hr><div class="card"><div class="card-body"><div class="align-items-center"><strong><center>That is all what we have for now.</center></strong></div></div></div>');
}
}
});
}
});
});
</script>
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'm relatively new to the world of programming and this is my first question on stack overflow. I have to create a system written in php and jquery that allows to order a series of images and, based on the order, create a banner-style animation. The only problem is that when the script selects the images from the div to create the animation they disappear. thanks in advance for your collaboration
the javascript
$(document).ready(function () {
const images = document.querySelectorAll('.imgw');
$('#preview').html(images[0]);
$("#genera").click(function () {
setInterval(banner, 2500);
var index = 1;
});
});
const banner = () => $('#preview').fadeOut('slow', function () {
$(this).html(images[index]);
$(this).fadeIn('slow', function () {
if (index == images.length - 1) {
index = 0;
} else {
index++;
}
});
})
the html file
<section>
<div class="row" style="margin-top:25px;">
<div class="col text-center">
<h2 style="margin-top:25px;">Anteprima</h2>
<div id="preview">
</div>
</div>
</div>
</section>
<section>
<div class="row" id="slides" style="margin-top:25px;">
<div class="col text-center">
<!-- <div id="box"> -->
<h2 style="margin-top:25px;">Slides</h2>
<ul id="sortable">
<?php
$html = "";
$count = 1;
foreach ($images as $img) {
$url = $img["url"];
$size = $img["size"];
$humanSize = $img["human_size"];
$html .= "\t\t<img src='{$url}' class='imgw' id='{$count}' alt='image_{$count}' />\n";
$count++;
}
echo $html;
?>
</ul>
</div>
I read the documentation better and solved the problem
the javascript
var images = $('.ui-sortable').children("img").clone();
var index = 1;
const banner = () => $('#anteprima').fadeOut('slow', function () {
$(this).html(images[index]);
$(this).fadeIn('slow', function () {
if (index == images.length - 1) {
index = 0;
} else {
index++;
}
});
})
setInterval(banner, 2500);
I am making a product displaying page of an ecommerce website. The products are to be filtered by brands on the basis of brands that are checked by the customer. For this I have used an ajax request everytime a brand is checked. The problem is that the page cannot receive the get variables that i am sending to the same page. The ajax request is not giving any errors and also the chrome debugger side is also not showing any error at all. This is the page:
snapshot of the products page
And this is the code of the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<?php
session_start();
include('includes/pdo_connect.php');
include('includes/pdo_functions.php');
$logged_in;
$user_first_name;
if(isset($_SESSION['user'])){ //Determining if the user is logged in or not.
if($_SESSION['user']=='user'){
$user_id = $_SESSION['user_id'];
global $logged_in;
$logged_in = true;
global $user_first_name;
$user_first_name = $_SESSION['user_first_name'];
}
} else {
$_SESSION['user'] = 'guest';
$user_id = $_SERVER['REMOTE_ADDR'];
}
$cat;
if(isset($_GET['cat'])){
global $cat;
$cat = $_GET['cat'];
}
include('includes/logged_in.php');
if(isset($_GET['brand_list'])){
$brand_list = $_GET['brand_list'];
} else {
echo "<script>alert('value not received');</script>";
}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="styles/list_style.css?<?php echo time(); ?>">
<link rel="stylesheet" type="text/css" href="styles/thickbox.css" media="screen">
<script type="text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="js/thickbox.js"></script>
<?php
$where = array();
if(!empty($brand_list)){
echo "ajax working";
if(strpos($brand_list, ',')!==false){
$brand_choices = explode(',', $brand_list);
$barray = array();
foreach($brand_choices as $value) {
$barray[] = "brand_id = $value";
}
$where[] = '('.implode(' OR ', $barray).')';
} else {
$where[] = '(brand_id= '.$brand_list.')';
}
} else {
//echo "ajax not working ";
}
$w = implode(' AND ', $where);
$w = "where product_cat=$cat ".$w;
$filter_query = "select * from products $w ";
echo "filter query: ".$filter_query;
$first_load = 'filter';
function show_filtered(){
//echo "<script>alert('filter query working');</script>";
global $filter_query;
global $con;
global $brand_name;
try{
$stmt = $con->prepare($filter_query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $data) {
$product_id = $data['product_id'];
$product_cat = $data['product_cat'];
$product_brand = $data['product_brand'];
$product_title = $data['product_title'];
$product_price = $data['product_price'];
$product_desc = $data['product_desc'];
$product_image = $data['product_image'];
echo "
<div class='product_container $brand_name'>
<a href='details.php?pid=".$product_id."' alt='".$product_title."'>
<div class='img_div'>
<img src='admin/product_images/".$product_image."?".time()."' alt='".$product_title."'/>
</div>
<div class='index_product_desc'>".$product_title."</div>
<div class='index_product_price'>₹".$product_price."</div>
</a>
</div>
";
}
} catch(PDOException $e){
echo "Error in show_list(): ".$e->getMessage();
}
}
function show_brands(){
global $con;
global $cat;
global $brand_name;
try{
$query = "select * from cat_brand where cat_id = $cat";
$stmt = $con->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
//$brand = array();
foreach ($result as $data) {
$brand_id = $data['brand_id'];
//echo "<script>alert('$brand_id');</script>";
$query1 = "select * from brands where brand_id = $brand_id";
$stmt1 = $con->prepare($query1);
$stmt1->execute();
$result1 = $stmt1->fetchAll();
echo "<ul>";
foreach ($result1 as $data1) {
$brand_name = $data1['brand_title'];
echo "<li><input type='checkbox' value='$brand_id' id='$brand_name' class='brand_check' name='brandchoice'> $brand_name</li>";
}
echo "</ul>";
}
} catch(PDOException $e){
echo "Error in show_brands: ".$e->getMessage();
}
}
function show_price(){
}
?>
</head>
<body>
<div class="wrapper">
<header>
<div class="home_logo">
<a href="index.php">
<img src="images/skyshop_sumopaint.png" alt="Site Home">
</a>
</div>
<div class="login">
<?php user();?> |
<?php login_status(); ?>
</div>
<div class="form">
<form method="get" target="" name="searchbar_form">
<input type="text" name="searchbar" id="searchbar">
<input type="submit" id="search_button" value="Search">
</form>
</div>
</header>
<div class="menubar">
<div class="dropdown">
<button onclick="dropdownToggle()" class="dropdown-button">Shop By Category</button>
<ul class="dropdown-content" id="dropdownContent">
Categories
<?php getcats(); ?>
</ul>
</div>
<div class="menubar-div">
<ul class="menu-items">
<?php getcats(); ?>
</ul>
</div>
<div class="cart">
Cart (0)
</div>
</div>
<div class="content">
<div class="nav">
</div>
<div class="list_wrapper">
<!--/////////////////////////////////////////////// Filter div /////////////////////////////////////////////////////-->
<div class="filter">
<span class="filter_heading">Select Brands</span>
<a href="" class="clear" id="clear_brands">Clear<a>
<div class="brand_div">
<?php
show_brands();
?>
</div>
<div class="price_div">
</div>
</div>
<!--/////////////////////////////////////////////// List div ///////////////////////////////////////////////////////-->
<div class="list">
<div class="loading">
<img src="images/loadingAnimation.gif">
</div>
<?php
show_filtered();
?>
</div>
</div>
<div class="footer">
FOOTER
</div>
</div>
</div>
<?php
?>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
</script>
</body>
</html>
I am using alert() in the beforeSend in the ajax request and it returns the correct data as expected. But the PHP section of the page does not received the values. There are no errors on the PHP side or the browser debug window.
I checked your code line by line. and figure out that you have code for ajax inside the function named "filter" function filter().
Now you are calling this filter function on by onclick event of the element with id clear_brands
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
and by this code i came to know that at the end your ajax call is not being made because you click event was not triggered,
So either you should trigger this event on your document get ready or you have to do it by clicking on that element.
Just think about the flow once.
i was testing your script in my local and
with some modification i have made it working.
did some changes like
at the end of the script i just putted this code below.
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
And ajax call was executed..
check out my entire HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<a href="" class="clear" id="clear_brands">Clear<a>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
</script>
</body>
</html>
In Chrome do Ctrl+Shift+I to open Developer Tools and check Console for errors and Network tab to see if the data is passed in request.
I want my second selects options to vary depending on the choice in the first select.
If you pick "Skalman" you can't pick "Whole day with lunch" and if you choose "Lilleskutt" you can't choose "Half day".
I haven't worked with AJAX before but thinking that it might be the right way to go, if anyone could help me out I would be more than grateful!
I get the options from the database, using two functions in Booking.php:
private function get_room_options() {
$this->load->model('Booking_Model');
$rooms = $this->Booking_Model->get();
$rooms_form_options = array();
// get room title and store in array
foreach ($rooms as $id => $room) {
$rooms_form_options[$id] = $room->title;
}
return array(
'rooms_form_options' => $rooms_form_options,
);
}
public function get_package_options() {
$room = $this->input->post('searchData');
$this->load->model('Package_Model');
$packages = $this->Package_Model->get();
$packages_form_options = array();
foreach ($packages as $id => $package) {
$packages_form_options[$id] = $package->package_name;
}
return array(
'packages_form_options' => $packages_form_options,
);
}
And in my booking.php you find the form:
<?php
echo form_open('booking/preview') ?>
<div>
<?php echo form_label('Conference Room: ', 'id') ; ?>
<?php echo form_dropdown('id', $rooms_form_options, set_value('id')); ?>
</div>
<div>
<?php echo form_label('Package type: ', 'package_id') ; ?>
<?php echo form_dropdown('package_id', $packages_form_options, set_value('package_id')); ?>
</div>
<div>
<?php echo form_label('Number of Participants: ', 'number_people') ; ?>
<?php echo form_input('number_people', set_value('number_people')) ; ?>
</div>
<div>
<?php echo form_submit('preview', 'Book'); ?>
</div>
<?php echo form_close(); ?>
And my script so far:
<script type="text/javascript">
$(function() {
$(document).on('change', '[name=id]', function(e){
var searchData = $(this).val();
$.ajax({
url: "<?php echo base_url('index.php/booking/get_package_options'); ?>",
type: 'POST',
data: searchData,
success: function() {
// how should I get the options in here?
}
});
});
});
</script>
CodeIgniter doesn't support ajax.For more clarification http://phpframeworks.com/
So lets start from view
<?php echo form_open('booking/preview') ?>
<div>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<?php echo form_label('Conference Room: ', 'id'), form_dropdown('id', $rooms_form_options, set_value('id')) ?>
</div>
<div>
<?php echo form_label('Package type: ', 'package_id'), form_dropdown('package_id', $packages_form_options, set_value('package_id')) ?>
</div>
<div>
<?php echo form_label('Number of Participants: ', 'number_people'), form_input('number_people', set_value('number_people')) ?>
</div>
<div>
<?php echo form_submit('preview', 'Book') ?>
</div>
<?php echo form_close() ?>
Here optimize your code by removing trailing semicolon & multiple echo
into single statement.
Now in your js part
$(function() {
$(document).on('change', '[name=id]', function(e){
var searchData = $(this).val();
$.post('YOUR_SEARCH_URL', { data : searchData }).done(function(data, textStatus, jqXHR) {
var h = '';
$(data.YOUR_SERVER_RESPONSE_KEY).each(function(i, v){
h += '<option value="' + i + '">' + v + '</option>'
});
$('[name=package_id]' ).html(h);
}).error(function(jqXHR, textStatus, errorThrown) {
//Handle your ajax error
});
});
});
Now at your controller
public function YOUR_CONTROLLER_ACTION() {
$data = $this->input->post('data');
//Do your work & get data from model for the id
//now send json response
return $this->output
->set_content_type('application/json')
->set_output(json_encode(YOUR_JSON_RESPONSE_ARRAY));
}
Check this two links http://code.runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php & http://code.tutsplus.com/tutorials/codeigniter-from-scratch-day-8-ajax--net-9243 for more details