Use cron to fetch a view which contains jQuery content? - php

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?

Related

How to make Ajax update table in wordpress database

I tried some steps I saw on the internet on how to send forms without refreshing the page using ajax but I cant seem to do it fine. Here is my code inside the form
$(".coupon_thumbsup").on('submit', function(e) {
e.preventDefault();
console.log("click");
var ThumbsUp = $(this).parent().find(".ThumbsUpVal").val();
ThumbsUp = parseInt(ThumbsUp) + 1;
$(this).parent().find(".ThumbsUpVal").val(ThumbsUp);
$(this).find(".green_thumb").css('background', 'url(http://www.accessdoorreviews.com/wp-content/uploads/2017/11/smalllike2.jpg)');
var totalvotess = $(this).parent().parent().find(".numofvotes").text();
totalvotess = parseInt(totalvotess) + 1;
$(this).parent().find(".ThumbsUpVote").val("1");
$(this).parent().parent().find(".numofvotes").text(totalvotess);
var successpercentv = ((ThumbsUp/totalvotess)*100).toFixed(2);
$(this).parent().parent().find(".successpercent").text(successpercentv);
console.log(successpercentv);
var ThumbsDown = $(this).parent().find(".ThumbsDownVal").val();
ThumbsDown = parseInt(ThumbsDown);
var companycouponid = $(this).parent().find(".companycouponid").val();
$.ajax({
type: "POST",
url: "insertcouponthumbs.php",
data: {'ThumbsUp': ThumbsUp, 'companycouponid':companycouponid, 'ThumbsDown':ThumbsDown},
});
});
And this is my php file:
<?php add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$comcoupid = $_POST['companycouponid'];
$resultcoupon = $wpdb->get_results("SELECT * FROM wp_coupon_list WHERE ID = $comcoupid");
foreach ($resultcoupon as $keyy) {
$wpdb->update($wpdb->prefix."coupon_list", array(
'ThumbsDown' => $_POST['ThumbsDown'],
'ThumbsUp' => $_POST['ThumbsUp'],
), array('ID'=>$keyy->ID)
);
}
wp_die();
} ?>

AJAX/PHP Chat refresh

Used AJAX for this chat function, however, it needs to be refreshed to retrieve new chats. I tried using setIntervala and setTimeout. sorry, noob with this.
message.php
$(document).ready(function(){
$("#btn-submit").click(function(e){
e.preventDefault()
var msgg = $("#chat-msg").val();
var href = $('#btn-submit').attr('href');
var ssid = $("#s-id").val();
var rrid = $("#r-id").val();
$.ajax({
method: "POST",
url: "http://127.0.0.1/test/admin/dashboard/ajaxMessage/",
data: {
message: msgg
}
})
.done(function(msg) {
console.log(msg);
$("#chat-msg").val("");
var head;
if (rrid != ssid) {
head = '<br><br><br><h1 class="msg-show-right">';
} else {
head = '<br><br><br><h1 class="msg-show-left">';
}
var chatBubble = head + " " + msgg + "</h1>";
$( ".msg-show-right" ).each(function( index ) {
last_bubble = $(this);
});
last_bubble.after(chatBubble)
});
});
});
dashboard.php
public function ajaxMessage () {
$message = $this->input->post('message');
$s_id = $this->session->userdata('s_id');
$r_id = $this->session->userdata('r_id');
$data = array(
'msg' => $message,
'status' => '1',
's_id' => $s_id,
'r_id' => $r_id
);
$this->admin_model->form_insert($data);
echo "true";
}
there are some unnecessary codes also.

Rating not add with ajax in wordpress

I have a problem
There is a rating system on songs (Its not my code i debugging it). but it could not add or update or show me the rating.
here is my code:
Ajax.js
function bindEvents() {
$(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
$(cssSelector.ratingLevel).click(function() {
var $this = $(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = $(cssSelector.title+':first').text();
var postdata1 = 'action=my_special_ajax_call5&rating='+rating+'&trackname='+trackname;
alert(postdata1);
jQuery.ajax({
type:'POST',
url:ajaxurl,
cache:false,
data: postdata1,
beforeSend:function(){
},
success:function(res){
$(cssSelector.rating_succes).html(res).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
Proccess.php
function implement_ajax5(){
global $wpdb;
$table = $wpdb->prefix."songs";
$table1 = $wpdb->prefix."rating";
$song_title = strip_tags($_POST['trackname']);
$rating_value = strip_tags($_POST['rating']);
$songres = $wpdb->get_row("SELECT * FROM $table WHERE `title`='$song_title'") or die(mysql_error());
$song_id = $songres->id;
$total_votes = $songres->total_votes;
$total_votes = $total_votes+1;
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'song_id' => $song_id,
'rating_value' => $rating_value,
'user_ip' => $ip
);
$check = $wpdb->get_results("SELECT * FROM $table1 WHERE song_id='$song_id' AND user_ip='$ip'");
if(!$check){
$insert = $wpdb->insert($table1,$data);
$wpdb->update(
$table,
array(
'total_votes' => $total_votes,
),
array( 'ID' => $song_id )
) or die(mysql_error());
echo 'Thank you';
}else{echo 'Already rated';}
die();
}
index.php
add_action('wp_ajax_my_special_ajax_call5', 'implement_ajax5');
add_action('wp_ajax_nopriv_my_special_ajax_call5', 'implement_ajax5');//for users that are not logged in.
I dont understand what happen when i alert it shows me right values but not add or update in database.
ok just try this in your Ajax.js at top of the page
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
And every thing goes perfect
and i think in your process page there is no need to update query. If you want to delete this there is no issue.
i get this a lot........ajaxurl needs to be defined, so i've learned that its just easier to not use ajaxurl and put in "/wp-admin/admin-ajax.php" in the url section.
Also i dont see you using non-conflict jQuery? (use the word jQuery instead of $)
You may also have issues with your postdata string, i may be wrong but what you need is action: '' ,
rating: '',
etc.
A good practice is to var_dump $_POST and exit at the beginning of your function to make sure they are passing over correctly. then in success- console.log(res) or whatever you are calling your return data
function bindEvents() {
jQuery(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
jQuery(cssSelector.ratingLevel).click(function() {
var $this = jQuery(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = jQuery(cssSelector.title+':first').text();
//alert(postdata1); -> console.log() is better for looking at objects
jQuery.ajax({
type:'POST',
url: "/wp-admin/admin-ajax.php",
cache:false,
data: {
action: 'my_special_ajax_call5',
rating: rating,
trackname: trackname
}
success:function(output){
console.log(output)
jQuery(cssSelector.rating_succes).html(output).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
see how you get on with that :)

Show data from 2 tables + zend framework

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)

Options not getting added again when the form is submitted +zendFramework

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?

Categories