I want to show data from my database into my table in html. (when i click on a link)
Table "births" fields:
district
year1999
year2000
year2001
year2002
year2003
year2004
year2005
year2006
year2007
year2008
year2009
Table "deaths" fields:
district
year1999
year2000
year2001
year2002
year2003
year2004
year2005
year2006
year2007
year2008
year2009
I will get the data from my database true an ajax call in javascript. I link to an action in my indexcontroller.
Javascript code:
$("#wijken ul li a").click(function(e){
district = ($(this).text());
loadTable(district);
});
function loadTable(district){
var param1 = district;
$.ajax({
url: 'index/getdata',
type: "POST",
data: {param1: param1},
dataType: 'json',
success: function(result)
{
var htmlContent = "";
// HOW CAN I PARSE THE DATA?
htmlContent += '</tbody></table>';
$('#tabel').html(htmlContent);
},
error: function(request, status, error){
alert(request.responseText);
}
});
}
My IndexController:
public function getdataAction()
{
// DISABLE VIEW
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
// WIJK CLICKED
$district = $this->_request->getParam('param1');
// GET THE BIRTHS/YEAR
$birthMapper = new Frontoffice_Model_BirthMapper();
$array = $birthMapper->read($district);
$this->_response->setBody(json_encode($array));
}
My BirthMapper:
public function read($wijk = null)
{
$table = $this->_dbTable;
$columns = array('wijk' => 'wijk',
'year1999' => 'year1999',
'year2000' => 'year2000',
'year2001' => 'year2001',
'year2002' => 'year2002',
'year2003' => 'year2003',
'year2004' => 'year2004',
'year2005' => 'year2005',
'year2006' => 'year2006',
'year2007' => 'year2007',
'year2008' => 'year2008',
'year2009' => 'year2009',
);
$select = $table->select()
->from($table,
$columns
)
->where('wijk = :wijk')
->bind(array(':wijk' => $wijk))
;
if ($row = $table->fetchRow($select)) {
return $row->toArray();
}
throw new Exception('The requested Births cannot be found');
}
Now I can handle the year1999,year2000,year2001,year2002,year2003,year2004,year2005,year2006,year2007,year2008,year2009 fields in my javascript as result.year1999. But how can I do this for multiple tables? (In javascript and controller)
Related
I am trying to make a simple AJAX GET call to my php backend, it hit and runs the method defined however no matter what the response data in the success function is always an empty string with a 200 response.
My ajax request is:
$("#coverage-table").on("click", "td", function() {
$(this).attr('id');
//Create Ajax call
//Get bill data/notes
//Present modal
$.ajax({
url: 'http://tms-v2.test/tms/getBillNotes',
type: 'GET',
data: {
bills: $(this).attr('id')
},
success: function(response) {
console.log(response);
debugger;
modal.style.display = "block";
}
});
});
My php method is:
public function getBillNotes() {
$bills = array_filter(explode("," ,$_GET['bills']));
$billingGateway = new BillingGateway;
$data = $billingGateway->getBillNotes($bills);
//Convert mysql object to array
while($row = mysqli_fetch_array($data)){
$items[] = $row;
}
foreach ($items as $key => $bill) {
$return[$bill['bill_id']] = [
'invoice_number' => $bill['invoice_number'],
'supplier' => $bill['supplier_name'],
'creation_date' => $bill['creation_date'],
'uploaded_by' => $bill['first_name'].' '.$bill['last_name'],
'is_credit_note' => !!$bill['type'],
'validation_status' => !!$bill['is_validating'],
'paid_date' => $bill['paid_date'],
'critical_notes' => $bill['note']
];
}
return 'TEST';
}
However this is always returning "", is this something to do with my request headers?
How to display name one by one using ajax. It seem that my FOR looping is not working to push name one by one. Is there any step that i miss? Can someone point me to where/what i did wrong.
var names = [];
var profiles = {};
var restURL = "fetch.php";
function refresh() {
$.ajax({
method: 'GET',
url:restURL,
success: function (result, status, xhr) {
for (var k in result) {
var name = result[k].name;
if (!profiles.hasOwnProperty(name)) {
names.push(name);
profiles[name] = result[k];
}
}
}
});
}
var namei = -1;
function nextName() {
namei++;
if (namei > names.length - 1) {
namei = Math.max(1, names.length - 10) - 1;
}
console.log(namei + '/' + names.length);
$('.texts li:first', '.jumbotron #atname').text(profiles[names[namei]].name);
$('.texts li:first', '.jumbotron #atdiv').text(profiles[names[namei]].division);
$('.jumbotron .tlt').textillate('start');
setTimeout(function () {
$('.jumbotron .tlt').textillate('out');
}, 5000);
}
fecth.php
$i=1;
while ( $row = mysql_fetch_assoc($rs) ) {
$response['result'][] = array(
'staffno' => $row['g_idm'],
'name' => $row['g_name'],
'division' => $row['g_div']
);
$i++;
}
echo json_encode($response);
I am trying to create custom class for jQuery File Upload plugin. I succeeded inserting data to my database however I can't read files from the database. Since I am not very familiar with object oriented programming I couldn't figure out where is the problem. Also there is not enough documentation for that.
class CustomUploadHandler extends UploadHandler {
public function get($print_response = true) {
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");
foreach ($query as $row)
{
$file = new stdClass();
$file->id = $row->id;
$file->name = $row->name;
$file->size = $row->size;
$file->type = $row->type;
$file->title = $row->title;
$file->url = $row->url;
$file->thumbnail_url = $row->thumbnail;
$file->delete_url = "";
$file->delete_type = "DELETE";
}
return $this->generate_response($query, $print_response);
}
}
I also have that in my js file :
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
I found myself with the same problem, and after doing some research i didn't found anything in the docs, so i did a workaround.
Basically i studied how is the object that the library it's sending to the front to be maped, and i rewrite the get function in my index.php from the handler in my CustomHandler.
The contra that i found, is that i started to save the size of the image in my database when is not needed, but anyway works well.
public function get($print_response = true) {
if ($print_response && $this->get_query_param('download')) {
return $this->download();
}
//this is my filter for the data the post_id
//see the main.js to see how i send it
$postId = $_GET['post_id'];
$arrayObjects = array();
$sql = 'SELECT `id`, `name`, `size` ,`post_id`, `path_img`, `descripcion` FROM `'
.$this->options['db_table'].'` WHERE `post_id`=?';
$query = $this->db->prepare($sql);
$query->bind_param('i', $postId);
$query->execute();
$query->bind_result(
$id,
$name,
$size,
$post_id,
$path_img,
$descripcion
);
// in $this->base_url i have the http:// value from my host
while ($query->fetch()) {
$arrayObjects[] = (object) array("name"=>$name,
"size"=>$size,
"url"=> $this->base_url.$path_img."/".$name
,"thumbnailUrl"=> $this->base_url.$path_img."/thumbnail/".$name
,"deleteUrl"=>$this->base_url."galeria/server/php/index.php?file=".$name."&_method=DELETE"
,"deleteType"=>'POST');
}
/* this is the object that you need to send to the front
* [name] => Captura de pantalla 2016-06-30 a las 4.40.10 p.m..png
* [size] => 61921 [url] => http://localhost/papmendoza/wp-content/uploads/galeria/Captura%20de%20pantalla%202016-06-30%20a%20las%204.40.10%20p.m..png
* [thumbnailUrl] => http://localhost/papmendoza/wp-content/uploads/galeria/thumbnail/Captura%20de%20pantalla%202016-06-30%20a%20las%204.40.10%20p.m..png
* [deleteUrl] => http://localhost/papmendoza/galeria/server/php/index.php?file=Captura%20de%20pantalla%202016-06-30%20a%20las%204.40.10%20p.m..png&_method=DELETE
* [deleteType] => POST )
*
*/
$response = array(
$this->options['param_name'] => $arrayObjects
);
return $this->generate_response($response, $print_response);
}
And in my main.js i have something like this
// i have a select in my custom form and i need the file uploader change
//with my select so here i basically do that
$('#noticia').on('change', function () {
var post_id = this.value; // or $(this).val()
$('#fileupload').addClass('fileupload-processing');
$.ajax({
url: $('#fileupload').fileupload('option', 'url') + '?post_id=' + post_id,
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
//you need to remove the files first
$("#fileupload").find(".files").empty();
$(this).fileupload('option', 'done').call(this, $.Event('done'), {result: result});
});
});
Is there a way I can set a cron to run a view on my Drupal site? I have a jQuery script on it which I would like to run once an hour.
I tried;
php http://mysite/myview
but I guess I am waaay off the mark. I get;
Could not open input file:
Here's the js which I am using on my rss feed;
// $Id
(function ($) {
Drupal.behaviors.tweetcast = {
attach: function (context, settings) {
$('div.tagspeak:not(.tags-processed)', context).addClass('tags-processed').each(function () {
var mynid, sinceid, updateinfo, sinceurl, author, tweethtml;
var currentsinceid = $('.currentsinceid').val();
var firstring = $(this).html();
var twostring = firstring.replace(/\s/g,'').replace(/^%20OR%20/gim,'').replace(/%20OR$/gim,'').replace(/%20OR%20%$/gim,'').replace(/%20OR%20$/gim,'').replace(/%$/gim,'').replace(/%20OR$/gim,'').toLowerCase();
var threestring = twostring.replace(/%20or%20/gim,'%20OR%20');
$(this).text(threestring);
var fourstring = threestring.replace(/%20OR%20/gim,' ');
var fivestring = fourstring.replace(/%23/gim,'#');
$(this).closest('.views-row').append('<div class="views-field views-field-replies"></div>');
tweethtml = $(this).closest('.views-row').find('div.views-field-replies').eq(0);
var twitter_api_url = 'http://search.twitter.com/search.json';
$.ajaxSetup({ cache: true });
$.getJSON( twitter_api_url + '?callback=?&rpp=1&q=' + threestring + '&since_id=' + currentsinceid, function(data) {
$.each(data.results, function(i, tweet) {console.log(tweet);
if(tweet.text !== undefined) {
var tweet_html = '<div class="tweetuser">' + tweet.from_user + '</div>';
tweet_html += ' <div class="sinceid">' + tweet.id + '</div>';
tweethtml.append(tweet_html);
}
});
});
$.fn.delay = function(time, callback){
jQuery.fx.step.delay = function(){};
return this.animate({delay:1}, time, callback);
}
$(this).delay(2000, function(){
title = $(this).closest('.views-row').find('div.views-field-title').eq(0).find('span.field-content').text();
link = $(this).closest('.views-row').find('div.views-field-path').eq(0).find('span.field-content').text();
author = $(this).closest('.views-row').find('div.tweetuser').eq(0).text();
mynid = $(this).closest('.views-row').find('div.mynid').text();
sinceid = $(this).closest('.views-row').find('div.sinceid').eq(0).text();
updateinfo = {sinceid: sinceid, mynid: mynid, author: author, title: title, link: link, tags: fivestring};
sinceurl = Drupal.settings.basePath + 'sinceid';
$.ajax({
type: "POST",
url: sinceurl,
data: updateinfo,
success: function(){}
});
});
});
}}
})
(jQuery);
And here is the php my module;
<?php
// $id:
function sinceid_menu() {
$items = array();
$items['sinceid'] = array(
'title' => 'sinceid',
'page callback' => 'sinceid_count',
'description' => 'sinceid',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function sinceid_count()
{
$sinceid=$_POST['sinceid'];
$mynid=$_POST['mynid'];
$author=$_POST['author'];
$title=$_POST['title'];
$link=$_POST['link'];
$tags=$_POST['tags'];
db_update('node')
->expression('sinceid', $sinceid)
->condition('nid', $mynid)
->execute();
$sql = db_query("SELECT author FROM {authordupe} WHERE author = $author");
$result = db_query($sql);
$how_many_rows = $result->rowCount();
if($how_many_rows == 0) {
db_insert('authordupe')
->fields(array(
'author' => $author,
'title' => $title,
'link' => $link,
'tags' => $tags,
))
->execute();
}
}
The basic code to run a view in Drupal is
$view = views_get_view('<your_view_machine_name>');
$view->set_display('<optional_display_name>');
$view->execute();
That said, you say have a jQuery script that runs within a view. Seriously? What is your script doing? I'd say that jQuery it's best used when you want a script to be run at client's side. Can't you write php code to accomplish whatever you need and put it in a cron hook?
i have to dependent combo box
$this->addElement('Select', 'Category',array(
'label' => 'Category:',
'AutoComplete'=> true,
'multiOptions' => array('0' => '-Category-',$a->GetCategories(),'2' => '-Add category-'),
'required' => true ));
$this->addElement('Select', 'SubCategory',array(
'label' => 'Sub Category:',
'AutoComplete'=> true,
//'multiOptions' => array('0' => '-Select Category-'),
'required' => true ));
the second one is filled using ajax
<script type="text/javascript">
//for send data i'll use jquery library
$(document).ready( function(){
$('#Category').change(function() {
var message=$('#Category option:selected').text();
if (message != '') {
$.ajax({
type: "GET",
dataType : 'json',
url: 'http://localhost/EverTags1/Authentification1/public/Product/add',
async: false,
data:{"message" : message},
success: function (respond) {
var json=JSON.stringify(respond);
var objet = eval('(' + json + ')');
e=objet.length;
var str = "";
for ( var count = 0 ; count < e; count++ ) {
str += "<option value='" + count + "'>" + objet[count].name+ "</option>"
}
$("#SubCategory").empty().append(""+str);
}
});
}
});
});
</script>
The elements were loaded correctly in the second combobox. But when I submitted the content of the second combobox disappears. how can i make them displayed
you need to update multioptions after each ajax request. i used session to do that
public function getsubcategoriesAction()
{
if($this->_request->isXmlHttpRequest())
{
$session = new Zend_Session_Namespace('mySession');
$this->getRequest()->param('id',1)
$model = new Application_Model_DbTable_Subcategory();
$result = $model->getSubcategories($category);
// save the result to session
$session->result = $result;
$this->_helper->json($result);
}
}
and in the action that render the form
public function createAction()
{
//some code here
if($this->getRequest()->isPost()){
$session = new Zend_Session_Namespace('mySession');
$subCategory = $form->getelement('subCategory');
$subCategory->addMultiOptions($session->result); // get the result back from session
//some code here
}
}
you need also to enable sessions in you application.ini
resources.session.save_path = APPLICATION_PATH "/../data/session"
resources.session.use_only_cookies = true
resources.session.remember_me_seconds = 864000
Does adding the selected='selected' attribute to the first option of #SubCategory fix it?