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"]);
Related
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);
}
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)
I'm working on calling scripts from the database if they match a function that's included.
Right here is what I'm using now:
3 Functions to Call Page Content:
public function ViewPageDetails() {
global $db;
$query = <<<SQL
SELECT title,body
FROM inv_pages
WHERE id = :getid
SQL;
$resource = $db->db->prepare( $query );
$resource->execute( array (
':getid' => $_GET['id'],
));
foreach($resource as $row){
$this->title = $row['title'];
$this->body = $row['body'];
}
}
public function ViewPageTitle() {
self::ViewPageDetails();
return $this->title;
}
public function ViewPageBody() {
self::ViewPageDetails();
if( is_callable($this->body) )
$this->body();
else {
echo $this->body;
}
}
I thought that that would work to call the function, but instead throws the error:
Fatal error: Call to undefined method pages::body()
Now a function I do have that would work on the flip side is
public function testcall() {
global $db;
$query = <<<SQL
SELECT body
FROM inv_pages
WHERE id = :getid
SQL;
$resource = $db->db->prepare( $query );
$resource->execute( array (
':getid' => $_GET['id'],
));
foreach($resource as $row){
if( is_callable($row['body']) )
$row['body']();
else {
echo $row['body'];
}
}
}
So $this->body() is an illegal method, but $row['body']() is perfectly fine to call. If anyone knows a way to use $this->body() instead of $row['body']() any input would be appreciated. If you need clarification please ask. I think I put the issue in pretty well however.
this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();
if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);
Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.
(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;
?>