Video clicks count laravel - laravel

I am trying to count the number of clicks on my video using Laravel. I followed this tutorial I found on Google: http://cameronscott.co/posts/tracking-page-clicks-in-laravel but nothing is working. I clicked on the video and it didn't increment in the database. Here is my code.
Route:
Route::get('video/{id}/click','ClickController#clickvideo');
Controller:
class ClickController extends Controller
{
public function clickvideo($id){
$po=User::findorfail($id);
$po->increment('clicks');
$po->update();
}
Views:
<a href="{{url('video/{$proo->id}/click')}}" class="js-click-video" style="border:none; background:none;">
<video class="video1" id="cb" preload="auto" data-post-id="{$proo->id}" style=" overflow: hidden; width: 30vh; object-fit: cover; float:left; clear:both;
height: auto; padding-left:2%; margin-top:0px; border:2px solid white; cursor:pointer; "><source src="{{$proo->intro_video}}#t=13" playsinline alt="Video Unavailable" id="" ></source>
</a>
JavaScript:
$('.js-click-video').click(function(e){
e.preventDefault();
var post=$(this).closest('.video1');
var postId=post.attr('data-post-id');
registerPostClick(postid);
});
function registerPostClick(postid){
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN' : $('meta[name="_token"]').attr('content')
}
})
$.ajax({
type: 'post',
dataType: 'JSON',
url: '/video/' + postId + '/click',
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(JSON.stringify(xhr.responseText));
}
});
}

You are missing a mustache in your variable name here:
data-post-id="{$proo->id}"
Should be
data-post-id="{{$proo->id}}"
This should also be:
*{{url('video/{$proo->id}/click')}}*
{{url('video/' . $proo->id .'/click')}}
Also, this is not necessary
$po->update();

Related

Why it is a bad request Ajax WordPress?

I want to publish wordpress post from front end but I am getting error 400 bad request. I have added both hooks in my php file as well. Please let me know where I am mistaken.
PHP code has two functions. 1 for adding form on front end and my ajax handler for handling ajax request. If I use core PHP, I got no error but I want to use ajax just to avoid reloading. Here I am stuck and need help from an expert. I would appreciate any help, hint or link to to useful resource.
AJAX Code:
jQuery(document).ready(function($) {
$('#submit').on('click', function(e){
e.preventDefault();
let title = $('#title').val();
let content = $('#content').val();
var formData = new FormData();
formData.append('image', document.getElementById('image-input').files[0]);
formData.append('var1', title);
formData.append('var2', content);
$.ajax({
url: 'http://localhost/wpdemo/wp-admin/admin-ajax.php',
type: 'POST',
data: formData,
processData: false, //add this
contentType: false, //and this
success: function(response) {
console.log(response);
}
});
})
});
PHP Code:
<?php
/*
Plugin Name: Notification Plugin Beta Version
Plugin URI: https://www.amirsandila.com/
Description: My first ever plugin n history of technology. You will love this plugin.
Version: 1.0
Author: Amir Sandila
Author URI: https://www.amirsandila.com
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: amirsandila
Domain Path: /languages
*/
define("version", strtotime(date("Ymd")));
function my_theme_enqueue_scripts() {
wp_enqueue_script( 'custom-jquery', 'https://code.jquery.com/jquery-3.5.1.min.js', array(), version, true );
wp_enqueue_script('ajax-script', '/wp-content/plugins/wp-plugin-demo/js/script.js',array(), version, true );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( '/admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
function my_ajax_handler() {
if (isset($_FILES['image'])){
$post_title = $_POST['var1'];
$image = $_FILES['image'];
$post_content = $_POST['var2'];
$new_post = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish',
'post_name' => 'pending',
);
$pid = wp_insert_post($new_post);
add_post_meta($pid, 'meta_key', true);
if (!function_exists('wp_generate_attachment_metadata'))
{
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES)
{
foreach ($_FILES as $file => $array)
{
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK)
{
return "upload error : " . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload( $file, $pid );
}
}
if ($attach_id > 0)
{
//and if you want to set that image as Post then use:
update_post_meta($pid, '_thumbnail_id', $attach_id);
}
}
}
add_action("wp_ajax_my_ajax_handler", "my_ajax_handler");
add_action("wp_ajax_nopriv_my_ajax_handler", "my_ajax_handler");
function form_shortcode_func() {
$output = '<style>
.form-container {
width: 70%;
margin: 0 auto;
border: 1px solid #ccc;
padding: 20px;
}
.form-container input[type="text"], .form-container textarea {
width: 100%;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
.form-container input[type="submit"] {
background-color: #333;
color: #fff;
border: 0;
padding: 10px 20px;
cursor: pointer;
}
</style>
<h2> Sumit Your Article! </h2>
<div class="form-container">
<form method="POST" enctype="multipart/form-data">
<input type="text" id="title" name="title" placeholder="Post Title">
<textarea name="message" id="content" rows="20" cols="30" placeholder="Post Body"></textarea>
<input type="file" id="image-input" name="image">
<button id="submit"> submit </button>
</form>
</div>';
return $output;
}
add_shortcode('form', 'form_shortcode_func');
?>
you are missing the action parameter so wordpress doesnt know which function you want.
in your js:
var formData = {
'action' : 'my_ajax_handler',
image: document.getElementById('image-input').files[0],
var1: title,
var2: content
};
$.ajax({
//Do your ajax
});
you should really be defining your ajax url differently:
$.ajax({
url: my_ajax_object.ajax_url,
//Do your ajax
});

post id with url using ajax

im write ajax code in post url and my userid bt not respond that code
<script>
function InviteLink( id, url ){
console.log(id);
$.ajax({
url: https://abc.hrm.com/auth/login
data: { 'id' : id },
success: function(data) {
}
});
}
</script>
<button onclick="InviteLink('<?php echo $employees->fldUserID; ?>','<?php echo base_url($employee_url); ?>');" style="background-color:#00C292; color:white; font-weight: bold; margin:5px 0px;" title="Invite New Employee" data-toggle="modal" data-target="#invitelink" type="button" class="btn btn-teal btn-circle"><i class="notika-icon notika-mail"></i></button>
**front UI in button i write onclick function and get id and url.... but there are not post in my url please help me solve my problem **
You Have to add method type = "POST" in ajax Like Below
<script>
function InviteLink( id, url ){
console.log(id);
$.ajax({
type: "POST",
url: https://abc.hrm.com/auth/login,
data: { 'id' : id },
success: function(data) {
}
});
}
</script>

Laravel ajax respond appending to body but not to #results

I have problem with outputting results from search in a div with id 'results' if I append the results to body they show up but when I change it to #results it's never appearing.
Search box is in navigation in master.blade.php and every other page includes it.
master.blade.php
<form id="search_form" action="/search" method="get" autocomplete="off" class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value);" placeholder="Search">
</div>
<div id="result">
<table style="width:100%">
#if (isset($results) && count($results) > 0)
#foreach( $results as $business )
<tr>
<td>{{ $business->logo }}</td>
<td>{{ $business->name}}</td>
</tr>
#endforeach
#endif
</table>
</div>
</div>
</form>
Controller:
public function search($search_value) {
$search_text = $search_value;
if ($search_text==NULL) {
$data= Business::all();
} else {
$data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
}
//$data = $data->toArray();
return view('master')->with('results',$data);
}
Ajax:
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#results').append(data);
},
error: function(data) {
$('body').html(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
Route::
Route::post('/searching/{search}', 'SearchController#search');
If I actually look into ajax response, result is there:
<table style="width:100%">
<tr>
<td></td>
<td>dasd</td>
</tr>
</table>
But it never appears on the page! It does if the append is changed to body.
//edit
I have a loading gif which worked fine but now it never dissapears and each time it executed ajax, it doesn't want to dissapear too:
$(document).ajaxStart(function() { Pace.restart(); });
$(window).on('load', function () {
setTimeout(function(){
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
}); // set the time here
});
$(document).ready(function() {
setTimeout(function() {
$(".messages").fadeOut(5000);
});
setTimeout(function() {
$(".messages").fadeOut(5000);
});
});
css:
.se-pre-con {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
opacity: 0.5;
background-color: #6d6968;
background: url(../images/default.gif) center no-repeat #fff;
}
jQuery.ajaxSetup({
beforeSend: function (xhr, data) {
$('.se-pre-con').show();
},
complete: function ()
{
$('.se-pre-con').hide();
}
});

Uncaught ReferenceError: year is not defined in google chart using ajax/codeigniter

Good day. I want to make my column char working with database but I got this error says "Uncaught ReferenceError: year is not defined". here is my code.
JAVASCRIPT
function year()
{
var e = document.getElementById("selectyear");
var year = e.options[e.selectedIndex].text;
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('chartcontroller/chart/')?>/" + year,
type: "GET",
dataType: "JSON",
success: function(data)
{
drawChart1(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart1);
function drawChart1(data) {
var data = google.visualization.arrayToDataTable([
['Courses', 'S.Y. 2011-2012', 'S.Y. 2012-2013','S.Y. 2013-2014'],
for(var i = 1; i < data.length; i++) {
comment = data[i];
[comment.Course, comment.year_a, comment.year_b, comment.year_c],
}
]);
var options = {
title: 'ColumnChart',
hAxis: {title: 'Courses', titleTextStyle: {color: 'blue'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
//ajax end
and my view html
<div class="grid text-center" style="display: block;">
<h1 style=" color: black; font-size: 18px;">Summary of Daily Utilization of Library Holdings per Department</h1>
<div class="input-group">
<span class="input-group-addon">#</span>
<select id="selectyear" class="form-control selectyear" data-mobile="true" name="year" onchange="year();">
<?php
for ($i=$min_year; $i <= $max_year; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
</div>
<h1 style=" color: gray; font-size: 14px;">S. Y. 2011-2012, 2012-2013 & 2013-2014</h1>
<div id="chart_div1" class="chart" style="height: 400px; width: 100%;"></div>
<div id="chart_div2" class="chart" style="height: 400px; width: 100%;"></div>
in my controller
public function chart($year)
{
$data = $this->views->chart($year);
//Either you can print value or you can send value to database
echo json_encode($data);
}
no problem with ajax because when I do a debugging ajax successfully retrieve the value from database, the problem is when I put that value to my column chart like what I did in my code I've got that error.. help me please. this is the last problem I have to my thesis project.. thanks. I want to change the column chart value if the drop down has change.

Kendo Ui web Listview

I am using Listview of kendo ui. I have no server wrapper class I am using the free web version.
My controller code is given below:
public ActionResult Index()
{
return View();
}
public ActionResult GetCandidateSearch()
{
IhrmsEntities Entity = new IhrmsEntities();
List<VW_CANDBASICSEARCH> lstCandidateSearch = Entity.VW_CANDBASICSEARCH.Take(50).ToList();
return Json(lstCandidateSearch,JsonRequestBehavior.AllowGet);
}
My index.cshtml
<div>
#Html.Partial("~/Views/Home/PvCandidateBasicSearch.cshtml")
</div>
My PvCandidateBasicSearch.cshtml
<div class="gridHolder" style="width: 100%">
<div id="listCandidateView" class="itemDisplay"></div>
<div id="pager"></div>
</div>
<script type="text/x-kendo-tmpl" id="template">
<div class="itemDisplay">
<div class="text-label">${CAND_NAME} </div>
<div class="text-label">${CAND_LOCATION} </div>
<div class="text-label">${CAND_MOBILE} </div>
<div class="text-label">${CAND_PRE_EMAIL} </div>
<div class="text-label">${CAND_SKILL} </div>
<div class="text-label">${CAND_CITY} </div>
<a href="/Home/EditCandidate?id=${CAND_ID}" >Edit</a>
<a href="/Home/DeleteCandidate?id=${CAND_ID}" >Delete</a>
</div>
</script>
<style type="text/css">
.text-label {
font-size: large;
}
.itemDisplay {
margin: auto;
padding: 6px 8px;
width:auto;
min-width:200px;
height: auto;
min-height:100px;
border: 1px solid #999999;
-webkit-border-radius: 6px;
border-radius: 6px;
font-weight: normal;
background: #deefff;
}
.gridHolder{width: 100%; height:auto; min-height:300px; margin:auto;}
</style>
My javascript code in layout.cshtml is given below
<script type="text/javascript">
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Home/GetCandidateSearch',
type: "GET",
dataType: "json"
}
},
pageSize: 15
});
$("#pager").kendoPager({
dataSource: dataSource
});
$("#btnSearch").click(function () {
LoadListView();
});
function LoadListView() {
$("#listCandidateView").kendoListView({
dataSource: dataSource,
pageable: true,
template: kendo.template($("#template").html())
});
}
</script>
when I first click search button it is perfectly going to the GetCandidateSearch action method and showing result.But when I second time clicking search button it is not going the action method. Plz help me.
You're misunderstanding the the datasource concept.
The datasource is an object holds the data gathered from request. On the second click you just re-binding that datasource to the ListView...
Basically, you need to bind the list view to the datasource on page load, then "OnClick", do datasource.read()
try this:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Home/GetCandidateSearch',
type: "GET",
dataType: "json"
}
},
pageSize: 15
});
$(document).ready(function() {
$("#listCandidateView").kendoListView({
dataSource: dataSource,
pageable: true,
template: kendo.template($("#template").html())
});
});
$("#btnSearch").click(function () {
$("#listCandidateView").datasource.read();
});
Not saying that the exact code will work, but it should give you an idea of the approach.

Resources