Laravel Ajax cannot update database when click on a link - ajax

I have an audio file on public folder like this-
#foreach ($songs as $song)
<a href="{{asset('/audio/' . $song->song)}}" download="" >
<button type="button" class="download" style="margin-bottom: 15px;">
<i class="glyphicon glyphicon-download">Download</i>
</button>
</a>
#endforeach
So, when i click that button it downloads the song. In my database, in "song" table there is column for song and another one for download_count which is set to default(0). I try to update download_count when i click on the link by ajax. My ajax:
$(function() {
$('.download').click(function(){
$.ajax({
url: "/update_download_count",
type:"POST",
data: {
song_id:$(this).attr('data-id')
}
});
});
});
My Route:
Route::post('/update_download_count', 'PagesController#updateDownloadCount');
Controller:
public function updateDownloadCount(){
$song_id = $_POST['song_id'];
$song->download += 1;
$song->save();
}
But, i cannot update my database however i click on the link. it still set to 0 in download_count column. Plz help, what's the wrong?

You don't actually select the song.
public function updateDownloadCount(Request $request) {
$song = Song::find($request->input("song_id"));
$song->download += 1;
$song->save();
}

Please declare object for your song modal.
public function updateDownloadCount() {
$song = Song::findOrFail($_POST['song_id']);
$song->download += 1;
$song->save();
}

public function updateDownloadCount(Request $request){
\DB::table('songs')->where('songs_id', $request->input("song_id"))->increment('download');
}

Instead of
$song->download += 1;
Try:
Song::find($request->input("song_id"))->increment('download');
I think that should work

Related

how to get filtered collection backpack laravel

I have a button that needs to pass a filtered collection from a table. Now when I click on the button, I get the entire collection
my button
$this->crud->addButtonFromView('top', 'withdrawDebtCompany', 'withdraw_debt', 'end');
button view
<form action="{{ url($crud->route.'/withdrawAllCompanyDebt') }}" method="POST">
<button class="btn btn-warning" data-style="zoom-in">
<span class="ladda-label">
{{ trans('columns.debt.allwithdraw') }}
</span>
</button>
{{ csrf_field() }}
</form>
method
public function withdrawDebtCompany()
{
$bills = $this->crud->query->get();
Bill::tryWithdrawalsIncrement($bills);
$res['success'] = 0;
$res['err'] = 0;
$bills->each(function($bill) use(&$res){
$paym = new PaymentsController();
$result = $paym->payDebt(new Request([
'bill_id'=>$bill->id,
]));
if($result['code'] == 0) {
$res['success'] += 1;
} else {
$res['err'] += 1;
}
});
\Alert::add('warning', 'Успешно списано: '.$res['success'].' | Неуспешно списано: '. $res['err'])->flash();
return redirect()->back();
}
I tried tracking the filtered collection in the button method, but that doesn't work. This is where the whole collection comes in. Filtered collection only comes after page reload
Hope to find you well.
In your <form> element you don't have any input to be POSTed, so I am wondering, why using a form there and not an <a> or similar.
I would advise you to have a look at the ListOperation https://github.com/Laravel-Backpack/CRUD/blob/main/src/app/Http/Controllers/Operations/ListOperation.php
There you will find the search endpoint that is used by datatables to get it's data.
You can apply a similar solution in your button endpoint to get the filtered results like in table.
Cheers

Generate password by button in blade file

inside Laravel Blade file I'm trying to achieve a simple password generator button that inputs generated password in field
Button:
<a class="btn btn-xs btn-success" onClick=generatePass()>Generate Me</a>
<script>
function generatePass() {
var hashed_random_password = Hash::make(str_random(12));
$('#password').val(hashed_random_password);
}
</script>
The button works, tested by using console.log('button clicked');
But hashing doesn't work, I need to achieve generating a hashed password and inputs it value directly into the password form field
Any suggestion how to get that simply in blade without invloving the routes and controller files?
<a class="btn btn-xs btn-success" onClick=generatePass()>Generate Me</a>
<script>
function generatePass() {
var pass = '';
var str='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+ 'abcdefghijklmnopqrstuvwxyz0123456789##$';
for (let i = 1; i <= 8; i++) {
var char = Math.floor(Math.random()* str.length + 1);
pass += str.charAt(char)
}
$('#password').val(pass);
}
Now at your laravel controller Hash this password.
You can't use Hash::make in javascript, that is a PHP/Laravel method.
You can use something like this to generate a random hash:
function generatePass() {
// change 12 to the length you want the hash
let randomPasswordHash = (Math.random() + 1).toString(36).substring(12);
$('#password').val(randomPasswordHash);
}
blade:
<button onclick="generateRandomPassword()">Generate Password</button>
<h2 id="password"></h2>
<script>
function generateRandomPassword() {
$.ajax({
url: '/generate-password',
success: function (data) {
$('#password').html(data);
}
});
}
</script>
route/controller:
Route::any('/generate-password', function () {
return Hash::make(Str::random(12));
});

like option in a website using codeigniter

I have a problem like this. I am creating a website using codeigniter. In it, users can ask questions and "like" them. All questions should be shown in the website by descending Order by the amount of like. If the first questions has 20 like and the second one has 18 and then, a person likes the second question ,then it has 19 likes it should stay in same place if it got 21 likes it should come to the top.
How can i do this?
I search internet so many times but i couldn't able to find out something suitable.
This is my question table.
In your view you have something like that i guess:
<input type="button" class="likeAction" data-questid="<?=$question->id?>" value="Like">
In jquery, when a like button is cliked, read the value of the data(questid) and you should start an ajax query to the likeQuestion method.
I don't know your code so I just write as i do it...
In your controller :
public function likeQuestion($quest_id){
$json = (object) []; //init an object, easier to use with json
$json->result = "error";
$res = $this->question_model->like($quest_id);
if($res){
$json->result = "success";
//read the number of like of the question
$json->num_like = $this->question_model->countLikeNumber($quest_id);
}
header("Content-type:application/json");
echo json_encode($json);
}
In your model :
public function like($quest_id){
$this->db->set('likes', 'likes+1', FALSE); //the false is important here
$this->db->where('id', $quest_id);
$this->db->update('question');
}
public function countLikeNumber($quest_id){
$this->db->select('*');
$this->db->from('question');
$this->db->where("id", $quest_id);
$query = $this->db->get();
return $query->num_rows();
}
I'll assume that you want to send your [adding like] request via ajax, and then ordering your list according the number of likes for each question, and I'll cover basically your front-end code reading the comments, so:
Your view should be like this:
<ul class="questions">
<li id="question_item_<?= $id ?>">
...
<span id="likes_<?= $id ?>"><?= $likesNum ?></span>
<button class="likeBtn" data-id="<?= $id ?>" >Like</button>
</li>
<li id="question_item_<?= $id ?>">
...
<span id="likes_<?= $id ?>"><?= $likesNum ?></span>
<button class="likeBtn" data-id="<?= $id ?>" >Like</button>
</li>
...
</ul>
Your Ajax Call:
$('.likeBtn').click(function(){
var $clicked = $(this),
questionID = $clicked.data('id'),
likesNum = $('li#question_item_' + questionID).find('span').text;
$.ajax({
url: 'PATH_TO_YOUR_CONTROLLER_METHOD_addingLike',
data: {'question_id': questionID},
dataType: 'json',
success: function(returnedData){
if(returnedData.status === 'success'){
$('li#question_item_' + questionID).find('span').text(parseInt(likesNum ) + 1);
reorderQuestions(returnedData.ids);
}
},
error: function(error){
console.log(error.resposeText);
}
});
});
/* Reordering your list at the front-end base,
* preventing server resources highly consumptions
*/
function reorderQuestions(ids){
var newUL = $('<ul class="questions">');
$each(ids, function(index, id){
newUL.append($('li#question_item_' + id));
});
$('ul.questions')replaceWith(newUL);
}
Your Controller Should behave like this:
public function addingLike($question_id){
# Increasing the number of like for question holding the specific id,
# Fetching all your questions ids ordered by the number of its likes
# Return a json object ['status': success, 'ids': [array_of_ids_ordered_by_likes]]
}

AJAX example in magento

Hello everyone,
I am a newbie to Magento. I want to learn **ajax process in Magento.** Can anyone help me to understand ajax in Magento with one simple example?
Your help will be highly appreciated.
I give you a simple example for you. To work with basic jQuery Ajax in Magento you have work in phtml page and Controller.
Just add the script in phtml page:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".like-result").click(function() {
//alert(this.id);
var id = this.id;
//alert(custid);
jQuery(".notify-status").hide();
jQuery(".notify-loader").show();
jQuery.ajax({
type: "POST",
data: 'pid=' + id,
url:'http://192.168.2.3/subhranil-demo/blog/index/likecount',
success:function(response){
if (response) {
jQuery(".notify-loader").hide();
jQuery(".notify-status").show();
jQuery("#un"+id).html(response);
}
}
});
});
});
</script>
In the above script under jQuery.ajax you can also see type, data, url. type is used for sending process like POST or GET; in data, you will send information to the controller; in URL, you can declare the controller path. Here I have a 'blog' module and I write the public function under 'index' controller and I give the function name 'likecount'. Also here my base path is http://192.168.2.3/subhranil-demo/. So I add the link to URL as following structure: http://192.168.2.3/subhranil-demo/blog/index/likecount.
Now I go to 'IndexController.php' in my controller's folder of blog module and open it. Under the class I add the following function:
public function likecountAction()
{
$blogload = Mage::getModel('blog/blog')->load($_POST['pid']);
$newid = $blogload['like']+1;
$data = array('like'=> $newid);
$blogload->addData($data);
try {
$blogload->setId($_POST['pid'])->save();
echo $newid;
} catch (Exception $e){
echo $e->getMessage();
}
}
Here in the Blog Database, I have the fields like pid (as a primary key) and like. the function works like that when you click on 'like-result' class the like increase +1.
My div structure also like that:
<?php
$allCollection=Mage::getModel("blog/blog")->getCollection();
$allCollection->addFieldToFilter('status',1);
if ($allCollection->count() >= 1)
{
$news = array();
?>
<div class="blog clearfix">
<?php
foreach ($allCollection as $news)
{?>
<p class="like-result" id="<?php echo $news->getId(); ?>"> <?php echo $news->getLike(); ?> </p>
<a style="display: none;" class="notify-loader"><img src="http://www.sendhersomething.com/skin/frontend/megatron/default/images/ajax/notify-loader.gif"></a>
<a style="display: none;" class="notify-status"><img src="http://www.sendhersomething.com/skin/frontend/megatron/default/images/ajax/ststus.png"></a>
<?php } ?>
</div>
<?php } ?>
Try this!

CakePHP 1.3 - Send non-form data to controller with js helper

I have a ul of dynamic buttons in my view that appears like the following:
<ul id="dashboard_list">
<li id="id_100" class="btn btn-primary">
<a id="id_100" href="/plugin_name/controller_name/action_name/100">Default View</a>
</li>
<li id="id_200" class="btn btn-primary">
<a id="id_200" href="/plugin_name/controller_name/action_name/200">Second View</a>
</li>
<li id="id_300" class="btn btn-primary">
<a id="id_300" href="/plugin_name/controller_name/action_name/300">Third View</a>
</li>
</ul>
The above links are created using the JSHelper as follows:
echo $this->Html->link($view->name, '/plugin_name/controller_name/action_name/'. $view->id, array('class' => 'ajax-link', 'id'=> $view->id));
I'm using the script below that I found while researching:
// onClick function
function onClick(){
$('#view_container').load($(this).attr('href'), onSuccess);
return false;
}
// activate ajax links to call the onClick function
$('.ajax-link').live('click', onClick);
// onSuccess-callback function
function onSuccess(){}
Now, in my controller / action im doing a simple check for data as follows:
function actionName() {
if ($this->data != null) {
die('We has data!');
}
else
{
die('We has no data.');
}
}
My #view_container element updates properly with "We has no data" on every click. So, I'm obviously not communicating the link's view id number (data) between the view and the controller.
Can anyone offer some direction on how to implement this functionality in CakePHP 1.3 to access the selected id (variable) in the controller? I mostly seem to find form submission examples (or just dead links), and I unfortunately don't have the option to upgrade cakePHP.
FYI: The proper helpers, scripts and the js->writeBuffer are being included.
Thank you for any responses in advance!
Rewrite your function as follows:
function actionName($id) {
debug($id);
if ($this->data != null) {
die('We has data!');
}
else
{
die('We has no data.');
}
}
If you need to do more than one variable in the URL ex:
href="/plugin_name/controller_name/action_name/300/yellow/bannana"
Then your function would look like:
function actionName($id,$color,$fruit) {
}

Resources