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.
Related
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();
} ?>
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);
Though I have searched a lot, I was not able to get a concrete answer
client side code
jQuery(document).ready(function() {
jQuery("#p_button").click ( function () {
console.log("button got clicked");
var donor_data= [ "12","13","14" ];
var damount = 1234;
var donor_obj = {
id : donor_data,
amnt : damount,
};
jQuery.ajax({
type:"POST",
dataType : "json",
url: myAjax.ajaxurl,
data: { action : "my_action",
'donors' : JSON.stringify(donor_obj),
},
success:function(response){
console.log("success " );
//console.log("success " + JSON.parse(response));
jQuery("#d_amount").val(donor_data[0]);
jQuery("#p_button").text("brrr");
},
error: function(response) {
console.log("error" + response);
},
});
});
});
server side code
function ajx_add_donations () {
global $wpdb;
$adv_don=json_decode($_REQUEST['donors']);
//$adv_don = json_decode($_POST['donors']);
//echo json_encode("phani");
//echo json_encode($result);
$dtype = 'OFFLINE';
$d_status = 'PENDING';
$ddate = current_time( 'mysql' );
$donation_e = array (
'UID' => $adv_don->id[0],
'STATUS' => $d_status,
'PMODE' => $dtype,
'AMNT' => $adv_don->amnt,
'DDATE' => $ddate
);
$d_id = update_donation_entry($donation_e);
echo json_encode("<h3> Thank you for Contribution <strong>$amount</strong></h3>");
wp_die();
}
Info needed
I'm not able to see my data base being updated, when I click the button,How to parse the Json data (array) at server side ?
Is there any way to know what I have received at server side, If I use "echo" to print a variable it is sent to ajax client ?
If answer to #2 is "NO" , how to parse the JSON data at client side ?
try this
jQuery(document).ready(function() {
jQuery("#p_button").click ( function () {
console.log("button got clicked");
var donor_data= [ "12","13","14" ];
var damount = 1234;
var donor_obj = {
id : donor_data,
amnt : damount,
};
jQuery.ajax({
type:"POST",
//dataType : "json",
url: myAjax.ajaxurl,
data: { action : "ajx_add_donations",
'donors' : JSON.stringify(donor_obj),
},
success:function(response){
console.log("success " ,response);
//console.log("success " + JSON.parse(response));
//jQuery("#d_amount").val(donor_data[0]);
//jQuery("#p_button").text("brrr");
},
error: function(response) {
console.log("error" + response);
},
});
});
});
function ajx_add_donations () {
global $wpdb;
$adv_don=json_decode(stripslashes($_REQUEST['donors']));
//$adv_don = json_decode($_POST['donors']);
//echo json_encode("phani");
//echo json_encode($result);
$dtype = 'OFFLINE';
$d_status = 'PENDING';
$ddate = current_time( 'mysql' );
$donation_e = array (
'UID' => $adv_don->id[0],
'STATUS' => $d_status,
'PMODE' => $dtype,
'AMNT' => $adv_don->amnt,
'DDATE' => $ddate
);
$d_id = update_donation_entry($donation_e);
echo json_encode("<h3> Thank you for Contribution <strong>$amount</strong></h3>");
wp_die();
}
add_action( 'wp_ajax_ajx_add_donations','ajx_add_donations' );
add_action( 'wp_ajax_nopriv_ajx_add_donations', 'ajx_add_donations');
I am creating a rating system in which when user rate any company then rate stored into rate along with the v_id table. (v_id is company id),
This is my url in which i want to rate...
www.ABC.com/controller/function/company_id
Here company_id is getting from database. I want to store the company rating into rate table. when user click on the star.
Controller
function visa_company_profile($v_id) {
$data['total_ratings'] = $this->Visa_mdl->total_ratings($v_id);
$data['total_average'] = $this->Visa_mdl->total_average($v_id);
$result = $this->Visa_mdl->get_company_profile($v_id);
$data['items_company_profile'] = $result;
$this->load->view('include/header');
$this->load->view('hotels/company_profile',$data);
$this->load->view('include/footer');
}
Views
This is ajax part in which i am sending the star values to the controller
$(document).ready(function(){
var click_val = 0;
$("#1_star").hover(function(){
$("#1_star").attr("src","<?php echo base_url('assets/rating/star.png'); ?>");
$("#2_star").attr("src","<?php echo base_url('assets/rating/blank_star.png'); ?>");
$('#3_star').attr('src',"<?php echo base_url('assets/rating/blank_star.png'); ?>");
$('#4_star').attr('src',"<?php echo base_url('assets/rating/blank_star.png'); ?>");
$('#5_star').attr('src',"<?php echo base_url('assets/rating/blank_star.png'); ?>");
});
$("#1_star").click(function(){
click_val = 1;
$.ajax({
url: '<?php echo base_url('Account/loggedin');?>',
success: function(logged_in) {
if (logged_in === "1") {
ajaxCall();
}else {
$("#l_modal").modal('show');
}
}
});
});
function ajaxCall() {
$.ajax({
method : 'POST',
data: {'click_val':click_val},
url: '<?php echo base_url('Hotels/ratings/');?>',
success: function() {
location.reload();
}
});
}
Star Controller To store Rate into data
Here i am trying to get the company id from url and store into column(v_id) rate table.
function ratings() {
date_default_timezone_set('Asia/Kolkata');
$last = $this->uri->total_segments();
$record_num = $this->uri->segment($last);
$value = array (
'rate' => $this->input->post('click_val'),
'date' => date('Y-m-d H:i:s'),
'v_id' => $record_num
);
$this->Visa_mdl->ratings($value);
}
Model
function ratings($value) {
$this->db->insert('user_ratings',$value);
}
You can do it simply modifying you ajax function input value
function ajaxCall() {
$.ajax({
method : 'POST',
data: {'click_val':click_val,'company_id':<?php echo $this->uri->segment(3)},
url: '<?php echo base_url('Hotels/ratings/');?>',
success: function() {
location.reload();
}
});
}
Again you can catch the company ID in your controller Function Hotels/ratings.
function visa_company_profile($v_id) {
$data['v_id'] = $v_id;
$data['total_ratings'] = $this->Visa_mdl->total_ratings($v_id);
$data['total_average'] = $this->Visa_mdl->total_average($v_id);
$result = $this->Visa_mdl->get_company_profile($v_id);
$data['items_company_profile'] = $result;
$this->load->view('include/header');
$this->load->view('hotels/company_profile',$data);
$this->load->view('include/footer');
}
If you pass click value in url then ajax script should be like this:
function ajaxCall() {
var company_id = '<?php echo $v_id; ?>';
$.ajax({
method : 'POST',
data: {'click_val':click_val, 'company_id':company_id},
url: '<?php echo base_url('Hotels/ratings/');?>'+click_val+'/'+company_id,
success: function() {
location.reload();
}
});
}
Because you are not passing click value in url so controller should be like that:
function ratings() {
date_default_timezone_set('Asia/Kolkata');
$record_num = $this->input->post('company_id', true);
$value = array (
'rate' => $this->input->post('click_val', true),
'date' => date('Y-m-d H:i:s'),
'v_id' => $record_num
);
$this->Visa_mdl->ratings($value);
}
And controller:
function ratings($record_num = 0, $company_id = 0) {
date_default_timezone_set('Asia/Kolkata');
$value = array (
'rate' => $record_num,
'date' => date('Y-m-d H:i:s'),
'v_id' => $company_id
);
$this->Visa_mdl->ratings($value);
}
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?