jquery ui's"selectable" - need to call codeigniter model function - php

(Original Questions) I am using jquery ui's selectable script to control specific active keywords in my webapp. View here: www.rickymason.net/letschat/main/home for reference
I have very little experience with javascript and I'm trying to figure out how to launch a function I have in my main model.
Updated function based on answers:
I have updated my code to support the new JSON/AJAX format. This required me to create an active/inactive session filter so that the user can add filters normally, and always use AJAX to update the thread list. This just made more sense to me.
Here is the code I have currently, which still is not working. I am attempting to make it so when the user clicks on a selectable category (through Jquery UI), the divID associated with the selection is passed through AJAX and returns a threadlist array that updates the div id ="board".
Here is my current Controller set up:
public function home($page = 'home')
{
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$data['threads'] = $this->thread_model->session_load();
$data['title'] = ucfirst($page); // Capitalize the first letter
$data['page'] = $page;
$this->load->view('templates/head', $data);
$this->load->view('templates/nav', $data);
$this->load->view('main/newthread', $data);
$this->load->view('main/addfilter', $data);
$this->load->view('main/checkbox', $data);
$this->load->view('main/displayfilter',$data);
$this->load->view('main/board', $data);
$this->load->view('templates/footer');
}
public function updatefilters($filters)
{
$filterarray = split("|", $filters);
$this->thread_model->create_session_filter($filterarray);
$threadarray = $this->thread_model->get_threads();
$data['json'] = '{"content":' + $threadarray + '}';
$this->load->view('json_view', $data); // See step 4!!!
}
Here is my current model code:
public function get_threads()
{
$filter = $this->session->userdata('filter');
$num_tags = count($filter);
if ($num_tags > 0 && $num_tags <= 8) {
$sql_select = "SELECT DISTINCT t.* ";
$sql_from = " FROM ";
$sql_where = " WHERE ";
$sql_joins = "";
$sql_order = "ORDER BY t.timestamp DESC";
for ($i=0;$i<$num_tags;++$i) {
if ($i==0) {
$sql_from .= " filter AS f ";
$sql_where .= " f.tag LIKE '%" . $filter[0] . "%'";
$sql_joins .= " INNER JOIN filter_thread AS ft ON ft.filter_id = f.filter_id
INNER JOIN thread AS t ON ft.thread_id = t.thread_id";
}
else {
$sql_where .= " OR f.tag LIKE '%" . $filter[$i] . "%'";
}
}
} else {
break;
}
$sql = $sql_select . $sql_from . $sql_joins . $sql_where . $sql_order;
$query = $this->db->query($sql);
$thread = $query->result_array();
return json_encode($thread); //I am aware this is not correct
}
public function create_session_filter($filterstring)
{
$filterarray[] = $filterstring;
$filter['filter'] = $filterarray;
if ($this->session->userdata('filter') == TRUE) {
$sessionfilter = $this->session->userdata('filter');
$new = array_merge($sessionfilter, $filter['filter']);
$this->session->unset_userdata('filter');
$filter['filter'] = $new;
$this->session->set_userdata($filter);
} else {
if (!$filterstring) {} else {
$this->session->set_userdata($filter);
}
}
}
public function create_session_inactive_filter($filterstring)
{
$filterarray[] = $filterstring;
$filter['inactivefilter'] = $filterarray;
if ($this->session->userdata('inactivefilter') == TRUE) {
$sessionfilter = $this->session->userdata('inactivefilter');
$new = array_merge($sessionfilter, $filter['inactivefilter']);
$this->session->unset_userdata('inactivefilter');
$filter['inactivefilter'] = $new;
$this->session->set_userdata($filter);
} else {
if (!$filterstring) {} else {
$this->session->set_userdata($filter);
}
}
}
And here is my current view code:
application/main/json_view.php
<?php
header("Content-Type: application/json");
echo $json;
?>
aplication/main/bdisplayfilter.php
<script>
$(function() {
$( "#selectable" ).selectable({
selected: updateFilters,
unselected: updateFilters
});
function updateFilters(ev, ui){
alert ("hello");
// get the selected filters
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("|");
$.ajax({
url: '/main/updateFilters', //see step 2
data: { filters: filters },
success: function(data){
// data is whatever json you decide to return from the server.
// An easy way to do things is have data look like this:
// { content: "<div>All my new threads that I want to show up</div>" }
// then, you can replace some element on the page with the new content
// For example, say your container has an id of threadContainer:
$('#select').replaceWith(data.content);
}
}); }
});
</script>
<ol id="selectable">
<li class="ui-state-default" id="everything">Everything!</li>
<li class="ui-state-default" id="entertainment">Entertainment</li>
<li class="ui-state-default" id="sci/tech">Sci/Tech</li>
<li class="ui-state-default" id="news">News</li>
<?php
if ($this->session->userdata('inactivefilter') == true) {
$inactivefilter = $this->session->userdata('inactivefilter');
foreach ($inactivefilter as $new)
{
echo "<li class='ui-state-default' id='custom'>$new</li>";
}
}
?>
</ol>
<?php
if ($this->session->userdata('inactivefilter') == true) {
echo "<form action='".base_url()."main/clear_filter'><input type='submit' value=clear></form>";
} ?>

EDIT: I've updated the url and data parts of the ajax call and added an additional step to enable query string parameters.
1) Make the AJAX call
You will want to make the same call for selected and unselected, since you can have multiple filters and you need things to update accordingly on both events. So, I'll define a common function that both events can call.
$(function() {
$( "#selectable" ).selectable({
selected: updateFilters,
unselected: updateFilters
});
function updatefilters(ev, ui){
// get the selected filters
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("|");
$.ajax({
url: '/index.php',
data: { c: main, m: updateFilters, filters: filters },
success: function(data){
// data is whatever json you decide to return from the server.
// An easy way to do things is have data look like this:
// { content: "<div>All my new threads that I want to show up</div>" }
// then, you can replace some element on the page with the new content
// For example, say your container has an id of threadContainer:
$('#threadContainer').replaceWith(data.content);
}
});
}
});
2) Enable query string parameters in application/config.php
The section called Enabling Query Strings at the bottom of this article explains how to do that:
http://codeigniter.com/user_guide/general/urls.html
3) Create an action that will receive the filters
Note that I'm using a controller called Page (which would live in /application/controllers/page.php). This action (updateFilters) could live in any controller you want.
class Page extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
}
function updateFilters($filters)
{
$filterarray = split("|", $filters);
create_session_filter($filterarray);
$articlesHTML = getThreadList($filterarray); // See step 4!!!
$data['json'] = '{"content":' + $articlesHTML + '}';
$this->load->view('json_view', $data); // See step 5!!!
}
/* I've updated this slightly to accept an array */
public function create_session_filter($filterarray)
{
$filter['filter'] = $filterarray;
//... the rest of your stuff you already had
}
}
4) Implement getThreadList method
I don't think you mentioned if you already had something set up for this. This would basically take an array of filters and then render a thread list based off that.
5) Create json_view (if not already there)
This will set the content type so that the browser knows the content is json.
In /application/views/json_view.php:
<?php
header("Content-Type: application/json");
echo $json;
?>

Related

Get authenticated data via other methods

So I'm running into an issue and I can't seem to figure it out, so I'm reaching out to see if anyone can help me.
I have a method called show_instagram_table() which has the following:
private function show_instagram_table(): string
{
$table = '';
if ($authenticated_users = get_option('instagram_authenticated_users')) {
foreach ($authenticated_users as $authenticated_user) {
$table .= '<table class="widefat"><tbody>';
// ----------- Remove other items non-needed ---------------
if (Instagram::get_items()) {
$table .= $this->show_authenticated_buttons($authenticated_user);
}
$table .= '</tbody></table>';
}
}
return $table;
}
Which calls on show_authenticated_buttons():
private function show_authenticated_buttons($user): string
{
$buttons = '<tr>';
$buttons .= $this->show_deauthorize_instagram_button($user);
$buttons .= '</tr>';
return $buttons;
}
This calls on show_deauthorize_instagram_button():
private function show_deauthorize_instagram_button($user): string
{
return '<td><button class="button button-primary instagram-deauthorize" style="margin-right: 5px">Deauthorize</button>';
}
Using AJAX, when the button is clicked, is will target that method and send the response back to PHP:
So..
jQuery('.instagram-deauthorize').click(function(e) {
e.preventDefault();
const data = {
'action': 'deauthorize_instagram_via_button',
};
jQuery.post(instagram_object.ajax_url, data, function() {
window.location = url;
});
});
Will trigger this method (I've tested it, it deletes the option):
public function deauthorize_instagram_via_button($user)
{
if (!get_option('instagram_authenticated_users')) {
return;
}
$users = get_option('instagram_authenticated_users');
if (count($users) === 1) {
delete_option('instagram_authenticated_users');
$this->instagram->delete_cache();
}
exit;
}
Here is where I am stuck:
I am wanting to send authenticated_user data inside the foreach from show_instagram_table all the way to my deauthorize_instagram_via_button() method, but it's impossible for me to target it.
Does anyone know what I can change/improve? I've already tried passing it down using $user params and no luck.
(Sorry for the lack of pictures, I am not allowed to post them).
Thanks all!
You can add one more attribute for each row.
You can use something like data-id or else.
For example :
private function show_authenticated_buttons($user): string
{
$buttons = '<tr data-id="'.$user->id.'">';
$buttons .= $this->show_deauthorize_instagram_button($user);
$buttons .= '</tr>';
return $buttons;
}
Then, you can get each user id (by using $(this).attr("data-id")).
jQuery('.instagram-deauthorize').click(function(e) {
e.preventDefault();
const data = {
'action': 'deauthorize_instagram_via_button',
'user_id': $(this).attr("data-id")
};
jQuery.post(instagram_object.ajax_url, data, function() {
window.location = url;
});
});
Finally your deauthorize_instagram_via_button will get the user_id.

Getting parameter value from $resource in Angular using PHP

I'm trying to retrieve data from my Wordpress database using an Angular factory. Using ng-click="updateCommentsById(v.id.videoId)" I call the following function:
$scope.updateCommentsById = function(id) {
commentRepository.query(({videoId: id}), function (data) {
$scope.comments = data;
});
}
That corresponds to the following factory definition:
angular.module("app")
.factory("commentRepository",
function($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php/:videoId",
{
videoId:"#id"
});
});
The problem is how to get the videoId parameter into my PHP function inside get_comments.php:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
echo $id;
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM analyser_posts WHERE video_id = $id", OBJECT);
echo wp_json_encode($result);
}
}
get_comments_by_id(videoId);
EDIT:
Turns out the get_results() method doesn't allow variables inside SQL statements, I should use prepare() (safer anyway) instead. I also changed the request URL. The new code becomes:
angular.module("app")
.factory("commentRepository",
function ($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php?video_id=:videoId");
});
and PHP:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
var_dump($id);
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$result = $wpdb->prepare("SELECT * FROM analyser_posts WHERE video_id = $id", OBJECT);
var_dump($result);
$result_array = array();
if($result){
foreach($result_array as $r){
$result_array[] = $r;
}
}
var_dump($result_array);
echo json_encode($result_array);
}
}
get_comments_by_id($_GET["video_id"]);
However the var_dumps show that the id gets passed correctly, only the prepare() doesn't actually execute anything. Should I wrap that in a get_results?
You could extract it from the URI:
//$args is an array of every part separated by `/` (ignoring the query string)
$args = explode('/',strtok(trim($_SERVER['REQUEST_URI'],'/'),'?'));
//the last element is the video id
$video_id = end($args);
Live demo
Got it to work using the answers (including those now removed) and comments. The function inside my Angular controller code:
$scope.updateCommentsById = function(id) {
commentRepository.query(({videoId: id}), function (data) {
$scope.comments = data;
});
}
Repository:
angular.module("app")
.factory("commentRepository",
function ($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php?video_id=:videoId");
});
get_comments.php:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$sql = $wpdb->prepare("SELECT * FROM `analyser_posts` WHERE `video_id` = '$id'", OBJECT);
$result = $wpdb->get_results($sql);
echo json_encode($result);
}
}
get_comments_by_id($_GET["video_id"]);

Ajax request in MVC doesn't return corresponding value to the HTML page

Below is my script in Dashboard module.
$(function()
{
var o;
$.get('dashboard/xhrgetInsert',function(o)
{
for(var i = 0;i <= o.length; i++)
{
$("#appendHere").append("<div>"+o[i].text+"</div>");
}
},'json');
$("#randomInsert").submit(function()
{
alert("hi");
var data = $(this).serialize();
var url = $(this).attr("action");
$.post(url,data,function(o)
{
$("#appendHere").append("<div>"+o+"</div>");
},'json');
return false;
});
});
Supposedly, when I'm in the dashboard page this function(xhrgetInsert) has to return value to be appended in the HTML. Unfortunately, it doesn't append anything and as I checked in the chrome console 'response'..it says method doesn't exist. But If I type the method name in the url, it shows the values returned in json format as I specified so.
Same goes for 'xhrInsert()' function as it doesn't return value to be appended. Database connection is perfect as it can insert and select data from db just unable get back the values..
I'm wondering first, why it says the method doesn't exist, and secondly why doesn't return any value?
My 'Dasboard controller making call to dashboard model'
public function xhrInsert()
{
$this->model->xhrInsert();
}
public function xhrgetInsert()
{
$this->model->xhrgetInsert();
}
Dashboard model contains mysql queries to the database whcih return values in jason format
public function xhrInsert()
{
$text = $_POST['text'];
$sql = $this->db->prepare("INSERT INTO data(text)VALUES(:text)");
$sql->execute(array(':text'=>$text));
echo json_encode($text);
}
public function xhrgetInsert()
{
$sth = $this->db->prepare("SELECT * FROM data");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$data = $sth->fetchAll();
echo json_encode($data);
}
Finally, this is my HTML for dashboard
<h1>Dashboard</h1>
<form id="randomInsert" action="<?php echo URL;?>dashboard/xhrInsert" method="post">
<label>Text: </label><input type="text" name="text"/><br/>
<input type="submit"/>
</form>
<div id="appendHere"></div>
Console Screenshot
Function should return the result json data to ajax request so it won't render the whole html page with result.
public function xhrInsert(){
echo $this->model->xhrInsert();
die;
}
public function xhrgetInsert()
{
echo $this->model->xhrgetInsert();
die;
}
Model
public function xhrInsert()
{
$text = $_POST['text'];
$sql = $this->db->prepare("INSERT INTO data(text)VALUES(:text)");
$sql->execute(array(':text'=>$text));
return json_encode($text);
}
public function xhrgetInsert()
{
$sth = $this->db->prepare("SELECT * FROM data");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$data = $sth->fetchAll();
return json_encode($data);
}

how to display data from database using $.post

hey iam trying to take data from data base using $.post. Here iam taking db data as json ecoded. But i couldn't display or alert the data. If possible how can i display the json array? how can i check the database values in json format? pls help me. iam using codeigniter
function profile_view(id3)
{
$.post("<? echo base_url();?>Attendance/Prev_leave_record", {id:id3},function(data){
//do something
});
}
controller
function Prev_leave_record()
{
$teacher_id=$this->input->post('id');
$teacher_details=$this->AM->prev_record($teacher_id);
$out=array(
'teacher_details'=>$teacher_details);
// echo '{"teacher_details":'.json_encode($teacher_details).'}';
echo json_encode($out);
}
model
function prev_record($teacher_id)
{
$this->db->select('leave_from_date,leave_to_date');
$this->db->from('leave_data');
$this->db->where('applied_user_id',$teacher_id);
$teacher_details=$this->db->get();
return $teacher_details;
}
Try this
Model:
Your model made a query but didn't return the result of the query.
See Returning Query Results.
function prev_record($teacher_id)
{
//This is opinion, but it will be much more efficient
//not using Query Builder for such a simple query
$sql = "SELECT leave_from_date, leave_to_date FROM leave_data WHERE applied_user_id = ?";
$query = $this->db->query($sql, [$teacher_id]);
//always check that the query produced results
//the next statement returns one row as an array or
//returns NULL if the query produced no results
return $query->num_rows() > 0 ? $query->row_array(): NULL;
}
Controller:
function Prev_leave_record()
{
$teacher_id = $this->input->post('id');
$teacher_details = $this->AM->prev_record($teacher_id);
if(isset($teacher_details))
{
$out['results'] = "Success";
$out['teacher_details'] = $teacher_details;
}
else
{
$out['results'] = "Failed";
}
echo json_encode($out);
}
javascript:
function profile_view(id3)
{
$.post("<? echo base_url();?>attendance/prev_leave_record", {id:id3},
function(data)
{
console.log(data); //so you can see the structure returned
if(data.results === "Success){
alert("Cool, it worked: " + data.teacher_details);
} else {
alert("Opps, we didn't get anything.");
}
}
);
}
Try this,
function profile_view(id3)
{
$.post("<? echo base_url();?>Attendance/Prev_leave_record", {id:id3},function(data){
console.log(data); // or alert(data);
});
}
Then check the console from Inspect element from browser (F12 or ctrl+shift+i)

codeigniter - display data from data base in dropdown [duplicate]

This question already has answers here:
Ajax drop down for Country State & City in Codeigniter?
(3 answers)
Closed 8 years ago.
i am creating an application in codeigniter for the form we want country and state in drop down on change selection of country
Controller is like
public function user()
{
$data = array();
$this->load->model('enquiry');
$this->load->helper('url');
$data['result'] = $this->enquiry->get_reqtutor();
$data['countries'] = $this -> country_model -> get_countries();
$this->load->view('Table\DemoHistory',$data);
}
function get_states($country) {
$this->load->helper('url');
$this->load->model('state_model');
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->state_model->get_states($country)));
}
and model is like
state_model`
<?php
class State_model extends CI_Model {
public function __construct() {
$this -> load -> database();
}
function get_states($country = null){
$this->db->select('state_id, state_name');
if($country != NULL){
$this->db->where('country_id', $country);
}
$query = $this->db->get('state_master');
$states = array();
if($query->result()){
foreach ($query->result() as $state) {
$cities[$state->state_id] = $state->state_name;
}
return $states;
} else {
return FALSE;
}
}
}
?>
country_model
<?php
class Country_model extends CI_Model {
public function __construct() {
$this -> load -> database();
}
function get_countries() {
$this -> db -> select('country_id, country_name');
$query = $this -> db -> get('country_master');
$countries = array();
if ($query -> result()) {
foreach ($query->result() as $country) {
$countries[$country -> country_id] = $country -> country_name;
}
return $countries;
} else {
return FALSE;
}
}
}
?>
Ajax is like
<script type="text/javascript">// <![CDATA[
$(document).ready(function(){
$('#country').change(function(){ //any select change on the dropdown with id country trigger this code
$("#cities > option").remove(); //first of all clear select items
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: /mtb/Schedule/get_states/"+country_id, //here we are calling our user controller and get_cities method with the country_id
success: function(cities) //we're calling the response json array 'cities'
{
$.each(cities,function(state_id,state_name) //here we're doing a foeach loop round each city with id as the key and city as the value
{
var opt = $('<option />'); // here we're creating a new select option with for each city
opt.val(state_id);
opt.text(state_name);
$('#cities').append(opt); //here we will append these new select options to a dropdown with the id 'cities'
});
}
});
});
});
// ]]>
</script>
and view is
<?php $countries['#'] = 'Please Select'; ?>
<label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?>
<?php $cities['#'] = 'Please Select'; ?>
<label for="city">State: </label><?php echo form_dropdown('state_id', $cities, '#', 'id="cities"'); ?>
i am getting country name while my state value is not comming in dropdown please help........
Things to consider about your code:
You have an error here url: /mtb/Schedule/get_states/"+country_id, missing double quote at the beggining. Always use a debugging tool, like firebug, it will show you the javascript errors.
Another thing, the code
if($country != NULL){
should be
if(!is_null($country)){
take a look at is_null function.
Another thing, instead of application/x-json json header you should use application/json.
Another thing, the code
echo(json_encode($this->state_model->get_states($country)));
should be
echo(json_encode($this->state_model->get_states($country)));
exit;
otherwise unexpected result might be appended to the final json. Example: CodeIgniter profiling.
Another thing, the code
$countries = array();
if ($query -> result()) {
foreach ($query->result() as $country) {
$countries[$country -> country_id] = $country -> country_name;
}
return $countries;
} else {
return FALSE;
}
should be
$countries = array();
foreach ($query->result() as $country) {
$countries[$country -> country_id] = $country -> country_name;
}
return $countries;
because having no countries and returning FALSE will give you an error in form_dropdown function, take a look inside it. The same goes for get_states function.
This is how much I see in a preliminary look of your code.

Categories