So basically to give a brief before exploring in to the code I give below.
Basically what I'm trying to do is, I have a modal in one of my php page as below. I'm trying to show the model from a php function "fetch_assignment_history" given below. There is a button in which we can add users to the assignment, and the button onclick event(onClick="assign(this.dataset.id)") call function passing the id from the php function to JS function.
So when the user click the button the JS function shows the modal as well as get the assignment id in the function. This assignment id is set (through JS) to data attribute of multiple select dropdown in the modal.
Now the point where I'm stuck is, a setinterval constantly fetch the assigned users. This basically collect from mysql database of users who were added to the assignment (comma delimitted id's).
When the modal is opened I want the previously assigned users to be selected in the multiple select (as per data in mysql) as default. For this I want to get the id passed from the onclick event
My HTML part (modal)
<div id="assignee" class="modal custom-modal fade" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title text-center">Assignment</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="col-md-12 col-sm-12 col-xs-12 form-group has-feedback">
<label style="color:#333D79FF; font-size:15px;">Add Users <span class="text-danger">*</span></label>
<div>
<select class="select2_multiple form-control" multiple="multiple" id="userslist" name="userslist[]" style="width: 100%;left: 10px;">
<option id="none" value="">Select Users</option>
<?php
My PHP CODE TO PULL OUT DATA FROM MYSQL DB
?>
<option value="<?php echo $id; ?>" data-useravatar="<?php echo $avatar; ?>" data-usertitle="<?php echo $firstname;echo " ";echo $lastname; ?>" data-role="<?php echo $role; ?>" data-assignment=""><?php echo $firstname;echo " ";echo $lastname; ?></option>
<?php } ?>
</select>
</div>
<div id="usersfetch"></div>
</div>
</div>
</div>
</div>
</div>
My PHP
1. function to fetch assignment history.
Below button onclick goes to JS and shows modal. and also pass id
function fetch_assignment_history($connect)
{
$query = "
SELECT * FROM assignment
WHERE id = '".$_SESSION['id']."'
ORDER BY id ASC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '<ul class="list-unstyled">';
foreach($result as $row)
{
$user_name = '';
$dynamic_background = '';
$message = '';
$assignmentname = $row["assignmentname"];
$name = $row["name"];
$id = $row['id'];
$output .= '
<div class="x_panel" style=" font-size:14px;">
<span class="controlbuttons">
<button class="btn btn-round" data-id="'.$id.'" onClick="assign(this.dataset.id)"><i class="material-icons" title="Assign">person_add</i></button>
</span>
</div>
';
}
$output .= '</ul>';
return $output;
}
function to assigned user history
function fetch_assigned_user_history($connect)
{
some php queries
}
My JS
I want the assignid from function assign(assignid) to be called from function fetch_assigned_user_history(). How do I accomplish this??????
setInterval(function(){
fetch_assigned_user_history();
}, 1000);
function assign(assignid)
{
var assignid = assignid;
$("#assignee").modal("show");
$('#userslist').data("assignment",assignid);
}
function fetch_assigned_user_history()
{
var action = "fetch_assigned_user_data";
var getid = ;// I need to get the ID from the previous function from onclick event function assign(assignid)
$.ajax({
url:"assignment.php",
method:"POST",
data:{action:action, assignmentid:getid},
success:function(data)
{
$('#usersfetch').html(data);
}
})
}
Hope I'm clear with my question. Appreciate for an advise to fix.
To summarise, the basic question is how to call variable of one JS function in to another (in this example id's) so that i can get the list of users in that assignment? Also how to get it selected by default the Multiple select with database values.
You already stored 'assignid' in data-* attribute, you can just retrieve it when you need it
function assign(assignid) {
var assignid = assignid;
$("#assignee").modal("show");
// You already store your assignid at here
$('#userslist').data("assignment",assignid);
}
function fetch_assigned_user_history()
{
var action = "fetch_assigned_user_data";
// Now you just need to retrieve it
var getid = $('#userslist').data("assignment");
$.ajax({
url:"assignment.php",
method:"POST",
data:{action:action, assignmentid:getid},
success:function(data)
{
$('#usersfetch').html(data);
}
})
}
Related
I've created a table with data and auto-generated buttons. When i click in 1 button .add_task, a modal opens, which display another table according to retrieved key: user_id of button.
The functionallity of button is shown below:
$(document).on('click', '.add_task', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"actions/fetch_jobs.php",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
$('#jobModal').modal('show');
$('.modal-title').text("Jobs");
`$('#vis_id')`.val(user_id);
$('#show_inseredjobs').html(data);
}
})
});
The problem is that i want to take value $('#vis_id') or user_id and put it in a php query of opened modal.
<div id="jobModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="job_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Jobs</h4>
</div>
<div class="modal-body">
<div id="show_inseredjobs"></div>
<br/>
<select name="job_desc" class="form-control action" id="job_desc" data-live-search="true" title="Select Job"></select>
</div>
<div class="modal-footer">
<input type="hidden" name="vis_id" id="vis_id" />
<?php
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
if($result->num_rows == 1) {
// row not found, do stuff...
?>
<span class="glyphicon glyphicon-print"></span>print button
<?php
}
?>
<input type="submit" name="action" id="action" form="job_form" class="btn btn-success" value="Προσθήκη" />
<button type="button" class="btn btn-default" data-dismiss="modal">Άκυρο</button>
</div>
</div>
</form>
</div>
</div>
More specifically, i want to do that: $result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
How can i pass that js variable in php?
I tried different combinations of expressing variable, but the code crashes. If i try to give manually numbers, the code works. To conclude, how can i pass value $('#vis_id') or user_id in $result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
Your modal is static and you can't run PHP code in the modal.
I think you must do this.
First change:
<?php
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
if($result->num_rows == 1) {
// row not found, do stuff...
?>
<span class="glyphicon glyphicon-print"></span>print button
<?php
}
?>
To:
<div id="job_desc"></div>
And then, in the actions/fetch_jobs.php file when you return data:
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = '".$_POST["user_id"]."' AND job_desc='Fumes'");
if ($result->num_rows == 1) {
$response = "";
foreach ($result as $row) {
$response .= '<span class="glyphicon glyphicon-print"></span>print button';
}
}
return json_encode([YOUREPREVIOUSRETRUN,$response]);
And then in ajax part you must parse json data first variable [YOUREPREVIOUSRETRUN] your previous data and second data you must put it on $("#job_desc").html(second data).
Or, you can use an iframe for this part but I don't suggest that.
From what I can tell by looking at the structure of your modal, you seem to be using Bootstrap, though I am unclear on the version. If it's Bootstrap 5, read on. If not, please add that information to your question, and let me know.
Here's how you can do it all in one call.
First, change the page from which you are opening the modal, so that the modal isn't a part of it. You need to make a separate file to hold the modal contents. Let's call that file remote-file.php. This would be inside that file.
<?php
// your PHP logic goes here - parse the received $_POST parameters, prepare your query - if needed, query your database
// retrieve the data, and place it in variables for later display
require 'conn.php';
$jvid = isset($_POST['jvid'] ? (int)$_POST['jvid'] : 0;
$result = $conn->prepare("SELECT job_desc FROM jobspervisit WHERE jvid = ? AND job_desc='Fumes'");
$result->bind_param("i",$jvid);
$result->execute();
if($result && $result->num_rows == 1) {
// row found, do stuff
$output = '<span class="glyphicon glyphicon-print"></span>print button';
} else {
$output = "Nothing found";
}
?>
<div class="modal-dialog">
<form method="post" id="job_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Jobs</h4>
</div>
<div class="modal-body">
<div id="show_inseredjobs"></div>
<br/>
<select name="job_desc" class="form-control action" id="job_desc" data-live-search="true" title="Select Job"></select>
</div>
<div class="modal-footer">
<input type="hidden" name="vis_id" id="vis_id" value="<?=$jvid?>">
<?php
echo $output;
?>
<input type="submit" name="action" id="action" form="job_form" class="btn btn-success" value="Προσθήκη" />
<button type="button" class="btn btn-default" data-dismiss="modal">Άκυρο</button>
</div>
</div>
</form>
</div>
Some notes about previous code:
it is assumed that jvid in your database is an INT type colum. Because of that, we could do (int)$_POST['jvid']
if jvid is not an INT but another type of column, we wouldn't do the (int)$_POST['jvid'] bit, and our binding would be slightly different
// prepare the query
$jvid = $_POST["jvid"];
$results = $conn->prepare("SELECT job_desc FROM jobspervisit WHERE jvid = ? AND job_desc='Fumes'");
$results = $conn->bind_param("s",$jvid);
$result->execute();
Next, in the original page, where your buttons are (and where your modal's HTML was), you would need this line of code for the modal.
<div class="modal fade" id="jobModal"></div>
This is going to be a wrapper for your modal content. All the rest will be going inside the remote-file.php. Also, your button element, the one that's opening the modal on click? That button doesn't need to have a data-bs-target attribute, because the following code will work (since you're using jQuery and all).
<button class="btn btn-lg btn-success add-task" id="btn" data-id="1234">Open modal</button>
<div class="modal fade" id="jobModal"></div>
<script>
$(document).ready(function() {
$(document).on('click', '.add_task', function(){
var user_id = $(this).attr("id");
$('#jobModal').load('remote-file.php',{'jvid':user_id },function(){
var jobModal = new bootstrap.Modal($('#jobModal')[0], {
backdrop:"static",
show:true
});
jobModal.show();
});
});
});
</script>
Final notes:
jQuery version: 3.6.3
Bootstrap version: 5.3.0
firstly, let me express that I have tried four methods (All slightly different) that all seem to produce the same issue, which is no data being outputted, even simple echo 'test' to rule out a DB issue (and also trying TEST in html on the called page, no result.
Here is a snapshot of the HTML and Javascript:
(document).on('change','category_id',function(){
var id = $(this).val();
$.ajax({
method: 'POST',
url: 'supportgetsubcats.php',
data: {'subcatid' : id},
success: function(data){
$('#subcatresponse').hide().html(data).fadeIn(); // update the DIV
}
});
});
<div class="form-group">
<label class="col-sm-2 control-label">Category *</label>
<div class="col-sm-4">
<select class="form-control" class="category_id" name="category_id" id="category_id">
<option value="" selected="selected">-- Select --</option>
<?php
$query="select * from support_categories where hide = '0' or hide is NULL order by name ASC";
$rs=sqlsrv_query($conn,$query);
while($row=sqlsrv_fetch_array($rs))
{
extract($row);
?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php
}
?>
</select>
</div>
</div><!-- form-group -->
<div class="form-group">
<div id="subcatresponse" name="subcatresponse" class="col-sm-4">
</div>
</div><!-- form-group -->
Here is the PHP that is called:
<?php require_once("includes/header.php");
error_reporting(E_ALL);
echo 'TEST';
if(isset($_POST["subcatid"])){
// Capture selected country
$category = $_POST["subcatid"];
$query="select * from support_subcategories where parent_category = '" . $category . "' order by name ASC";
$rsp=sqlsrv_query($conn,$query);
$subCatArr = array();
while($row=sqlsrv_fetch_array($rsp))
{
$subcat = $row['name'];
array_push($subCatArr, $category, $subcat);
}
// Display city dropdown based on country name
if($category == '-- Select --'){
} else {
echo '<label class="col-sm-2 control-label">Sub Category</label>';
echo '<select class="form-control" name="subcategory_id" id="subcategory_id">';
foreach($subCatArr[$category] as $value){
echo '<option value="'. $value .'">'. $value .'</option>';
}
echo "</select>";
}
}
?>
I get no response, not even basic text back, so I am not entirely sure what is wrong with the AJAX call, jQuery is included and proven to be working as the menu system on this interface won't display without jQuery so I am confident that is not the issue.
It looks like for whatever reason, the data from the HTML Select is not being passed to the AJAX call for POST.
Any thoughts greatly appreciated, TIA.
Try changing
(document).on('change', 'category_id', function() {
to
$(document).on('change', '#category_id', function() {
The second parameter to the on call takes a selector, but you seem to be passing in the name of the element instead. The name of the element is used when trying to access the element in PHP, and you use the selector (id, class, element) in JavaScript.
Alternatively, you could also use
$('#category_id').on('change', function()
You haven't posted it in your question, but in case you don't have it, it is always a good idea to only execute your jQuery code after the page has finished loading, otherwise your code may be trying to access an element that hasn't been loaded yet.
Surround your jQuery code with
$(document).ready(function() {
// Run jQuery code
}
add type='POST' to your ajax call
Also change this
(document).on('change','category_id',function(){
to
$(document).on('change','category_id',function(){
I'm working currently on an backend script for an projects My PHP skills are ok, I get working what I want. But everything about JS/AJAX/jQuery I did not understand.
Ok, my problem:
I have thumbnails for videos and photo sets and want to set cover photos for each. I use at the moment an popup script, that works.
But I use an admin theme (based on Bootstrap), that I purchased and it will be look much better, when I use modals and not popups.
I try many things to get my script from the popup get working into the modal - but I fail all the time.
I open the modal with
<a class="btn red btn-outline sbold" href="<?php echo $website; ?>/modals/photo_cover.php?photoid=<?php echo $row['id']; ?>" data-target="#ajax" data-toggle="modal"> Generiere Thumbnails </a>
This opens an preloader modal, that I add to my page also. I want this, because I want to add an automatic generation of thumbs in the future. So, it should be show the loader while the thumbs will be generate.
<div class="modal fade bs-modal-lg" id="ajax" role="basic" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<img src="<?php echo $website; ?>/assets/global/img/loading-spinner-grey.gif" alt="" class="loading" />
<span> Generiere Thumbnails ...</span>
</div>
</div>
</div>
</div>
Then the (external) modal will be open with my script:
<?php
include_once ('../classes/LS.php');
include_once ('../inc/config.php');
?>
<style>
label > input { visibility: hidden; position: absolute; }
label > input + img { cursor:pointer; border:2px solid transparent; }
label > input:checked + img { border:2px solid #f00; }
</style>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Galerievorschau</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "UPDATE content_pic_db SET pic_poster_file = :pic_poster_file WHERE id = :id";
$stmt = $dbh1->prepare($sql);
$stmt->bindParam(':id', $_GET['photoid']);
$stmt->bindParam(':pic_poster_file', $_POST['poster']);
$stmt->execute();
?>
<div class="portlet-body">
<div class="note note-danger"><p>Klicke auf ein Bild um es als Vorschaubild für die Galerie festzulegen.</p></div>
<div class="row">
<div class="col-sm-12 col-md-12">Das Vorschaubild wurde erfolgreich Deiner Galerie zugewiesen. Du kannst jetzt dieses Fenster schliessen.</div>
</div>
</div>
<?php } else { ?>
<div class="portlet-body">
<div class="note note-danger"><p>Klicke auf ein Bild um es als Galerievorschau festzulegen.</p></div>
<div class="row">
<form id="preview" method="POST">
<?php
if (!empty($_GET['photoid'])) {
$stmt = $dbh1->prepare('SELECT pic_count, pic_path FROM content_pic_db WHERE id = :id');
$stmt->execute(array(':id' => $_GET['photoid']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$pfad = $row['pic_path'] . '/thumbs/';
$scan = glob($pfad . "*.{jpg}",GLOB_BRACE);
for ($i = 0; $i<count($scan); $i++) {
if (strlen($scan[$i]) >= 3) {
?>
<div class="col-sm-6 col-md-6">
<label class="thumbnail">
<input type="radio" name="poster" value="<?php echo substr($scan[$i], 50); ?>" />
<img title="Klicke auf ein Bild um es als Vorschau auszuwählen" src="<?php echo $website; ?>/stream_g.php?id=<?php echo $_GET['photoid']; ?>&file=<?php echo substr($scan[$i],50); ?>" />
</label>
</div>
<?php
}
}
}
}
?>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer"><button type="button" class="btn red" data-dismiss="modal">Fenster schliessen</button></div>
<script>$('input[name=poster]').change(function () { $("#preview").submit(); });</script>
And here are starting my problem.
The modal will be open, but when I choose an image (I "replace" the radio buttons with the images) as cover, the modal will just be closed and nothing will be written to the database.
As popup everything is working, but not as modal.
I think, I have to use JS/AJAX/jQuery to write to the database. But I don't know how ... I read already a lot of tut's but I don't understand how it works.
Would be nice if someone could explain me step by step how I can get this working ...
And I need to know how to execute a script and get informed, if it is finished. As I say before, I want to add an option to generate thumbs. So I want to open the preloader modal, generate the thumbs and when it's finished it should be show the 2nd modal for choosing the cover.
you can't write in database using JS (jQuery or Ajax). It is only possible using frameworks like node.js (server-oriented js) but I think you don't have to act like this.
Native Javascript isn't a back-end language
Look, you have to use PHP to interact with databases. Javascript is a front-end language, at this level (considering we will not use node.js, this is another thing :p). So, you can considere web development like this :
FRONT END (Client side) | BACK END (Server side)
[HTML + CSS] [JS] <-->[AJAX]<--> [PHP][SQL]
If you want your page to make things dynamically, you have to build everthing in a different way.
I suggest you to considere this way of working
[HTML -> import jQuery and write ajax request] - index.html (only scripts)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="application/javascript">
$.ajax({
type: 'post',
dataType: 'json',
url: 'request.php',
success: function(data){ //Building an array using database datas directly in the body
var content = "<table><tr><th>Lastname</th><th>Firstname</th><th>Email</th></tr>";
for(i = 0; i < data.length; i++) {
content += "<tr><td>" + data[i].lastname + "</td><td>" + data[i].firstname + "</td><td>" + data[i].email + "</td></tr>";
}
content += "</table>";
document.body.innerHTML += content;
}
});
</script>
[PHP -> Requests database and return datas] - request.php
<?php
$dbname = "YOUR DATABASE NAME HERE";
$host = "DATABASE HOST ADDRESS HERE";
$user = "LOGIN USERNAME HERE";
$pass = "LOGIN PASSWORD HERE";
try {
$bdd = new PDO('mysql:host='.$host.';dbname='.$dbname.';charset=utf8', $user, $pass);
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
$table = "TABLE NAME HERE";
$colonnes = "*"; //COLUMNS TO SELECT HERE, * FOR ALL
$request = $bdd->query('SELECT ' . $colonnes . ' FROM ' . $table); //SQL QUERY
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BUILDING THE TABLE TO RETURN %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
TABLE STRUCTURE EXAMPLE :
------------------------------------
| id | lastname | firstname | email |
------------------------------------
*Line 1*
*Line 2*
*Etc...*
*/
$i = 0;
foreach($request as $req) {
$table[$i]['lastname'] = $req['lastname'];
$table[$i]['firstname'] = $req['firstname'];
$table[$i]['email'] = $req['email'];
$i++;
}
echo json_encode($table); //echo will show datas when executing this script, the ajax request will take every showed data in its success method
exit();
?>
Obviously, using this work methodology makes that each page of your website is an html file. Only the PHP scripts are using the .php extension. This is, for me, a sexier way of working ^^
I'm working on a project of a website which shows a chart. User should be able to change a displayed chart (without changing the website) by clicking one of 'Available sensors' from dropdown options. Dropdown connects to MySQL database with used sensors. The sensor's id is assigned to HTML-input ID and its name is assigned to input value.
My intension is to use sensor ID in another data.php file which is responsible for connecting to tables (MySQL) with data collected by sensors. This ID would tell to which of the tables this programm should connect.
At the moment JS script's task is to alert an ID of the chosen sensor when it's clicked on the dropdown menu. Instead of a number I get a message saying 'undefined'. Eventually it would transfer the stored id to the mentioned data.php file.
Could you please tell me whether it's necessary to use AJAX in this case or what's a possible reason of this error in my code?
I also tried to use button insted of input. When clicking on sensors names on dropdown I've received only messages with '1'. However assigning sensorName worked out in both cases. Sensors ID is stored as INT, name as VARCHAR in MySQL table.
Thank you in advance for your help :)
<div id="header_btn" class="dropdown">
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?>
<input onclick="changeSensorID(this.value)" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>" value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script>
function changeSensorID() {
var sensorID = document.getElementsByClassName("btn_drop").id;
alert(sensorID);
};
</script>
</div>
please check this code, working fine
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?><input onclick="changeSensorID(event)" onmouseover="this.style.textDecoration='underline'"
onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>"
value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script >
function changeSensorID(event){
var sensorID = event.target.id;
alert(sensorID);
}
</script>
</div>
getElementsByClassName returns array of at least one item if found any. You have to provide index of element that you want to use.
Example
var sensorID = document.getElementsByClassName("btn_drop")[0].id;
I have a simple webpage which generates a random quote from my database upon refreshing the page. I wish to implement some AJAX and JQuery in order to generate quotes via the button rather than having to refresh the page. I have done some research but I am not sure how to implement this in Codeigniter. My current code is below...
Page controller:
public function index() {
$this->load->model('quote_model', '', TRUE);
$data['quotes'] = $this->quote_model->getRandom();
$this->load->view('home', $data);
}
The view:
<?php include ('layout/header.php'); ?>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 quote-holder">
<img src="application/assets/alan1.jpg" alt="..." class="img-circle img-responsive">
<br>
<blockquote class="text-center">
<p><?php echo $quotes[0]['quote']; ?></p>
<footer class="text-center"><?php echo $quotes[0]['character_name']; ?> in <cite title="Source Title"><?php echo $quotes[0]['series_name']; ?></cite></footer>
</blockquote>
<button type="button" class="btn btn-default center-block">Generate quote</button>
</div>
</div>
<?php include ('layout/footer.php'); ?>
Here is the function in the model I am retrieving the data from:
function getRandom() {
$query = $this->db->query("
SELECT * FROM quotes, characters, series
WHERE quotes.series_id = series.series_id AND quotes.character_id = characters.character_id
ORDER BY rand()
LIMIT 1
");
return $query->result_array();
}
Should I simply be using something like this?
$("button").click(function(){
$.get( "Page/index", function( data ) {
//output data to page element...
}
});
getI would do something like: controller:
public function callme()
{
$this->load->model('quote_model);
$data['quotes'] = $this->quote_model->getRandom();
}
Then in my footer:
condole.log("click button")
var_url = "controller/callme" // the url to the controller and method
$.get({
url: url
})
But meh, im bad at programming and even worse at jquery :D
Make hidden input for offset
<button onclick="showmore()" value="showmore" />
<input type="hidden" name="offset" id="offset" value="15"/>
Now Your Ajax Call
function showmore(){
$.ajax({
url:my_controller/showmore,
data:{
offset :$('#offset').val()
},
type:json,
success :function(data){
$('#show-more').prepand(data.view)
$('#offset').val(data.offset)
}
})
}
Your Controller
function showmore(){
$limit = '10';
$offset = $this->input->get('offset');
$result = $this->yourmodel->getdata($offset,$limit);
$data['view'] = $result;
$data['offset'] =$offset +10;
echo json_encode($data);
}
Your Model
$query = $this->db->get('your_table', $limit, $offset);
$data=$query->result_array();
return $data;