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]]
}
Related
I'm working with my project which get new orders and append to DOM with jQuery.
jQuery
setInterval(function() {
$.ajax({
type:'POST',
url:'{{URL::to('/')}}/orders',
success:function(data)
{
let obj = JSON.parse(data)
let ordersDiv = $('#ordersDiv');
let queueCount = $('#queueCount');
queueCount.html(obj.count);
ordersDiv.html(obj.data);
}
});
}, 15000);
Controller
//some code here
$data .= "<a class=\"example-image-link\"
href=\"{{URL::to('/')}}/users/uploads/profiles/{{strlen($biker-
>picture_file_path)>0?$biker>picture_file_path:'avatar.png'}}\">
<img src=\"URL::to('/')/users/uploads/profiles/$biker-
>picture_file_path:.'avatar.png'\" data-toggle=\"tooltip\"
title=\"HiBes Biker\">
</a>";
//more code here
My problem is that I'm getting this result:
<a href=\"{URL::to('\/')}\/order-details\/3159\">Details<\/a>
I expect a result something like this:
<a href=\"http://127.0.0.1:8000/order-details\/3159\">Details<\/a>
The reason your URLs still contain the placeholders is you are building HTML in your controller, not your view.
Ideally, you should switch this logic into the view, where the {{ $var }} syntax will work.
Create a new blade file bikerimage.blade.php
#foreach($bikers as $biker)
<a class="example-image-link"
href="{{URL::to('/')}}/users/uploads/profiles/{{ $biker->picture_file_path ?: 'avatar.png' }}">
<img src="{{ URL::to('/')}}/users/uploads/profiles/{{ $biker->picture_file_path ?: 'avatar.png' }}"
data-toggle="tooltip"
title="HiBes Biker"
>
</a>
#endforeach
Then in your controller, you can do something like
//some code here
$data = view('partials/bikerimage.blade.php', ['bikers' => $bikers])->render();
return [
'html' => $data,
];
This means you can still return the data as part of an ajax call, without having to build HTML in your controller.
I'm bit stuck at a place. I've got some views of small HTML sections which when combined gives the complete HTML page. I'm trying to build a website builder with Jquery, where I'm having a drop event which adds those particular views:
For example I've got HTML for slideshow:
<div id="slideshow" data-nitsid="2">
<div class="revolution-slider">
<ul>
<!-- SLIDE -->
#foreach($contents->slider as $sliders)
<li data-transition="{{ $sliders->transition }}" data-slotamount="{{ $sliders->slotamount }}" data-masterspeed="{{ $sliders->masterspeed }}">
<!-- MAIN IMAGE -->
<img src="{{ URL::asset($sliders->url) }}" alt="">
</li>
#endforeach
</ul>
</div>
</div>
In my JQuery code:
nitsbuilder.dropeventhandler = function ($item, $position) {
var nits_id = $item.data('nitsid');
$.ajax({
method: 'POST',
url: dropurl,
data: { nits_id: nits_id, _token: token},
dataType: 'json',
success: function (data) {
nitsbuilder.adder($item, $position, data);
}
});
}
Before I was having html codes in the database so it was easier to pull out the html and add to the HTML page, now I'm having html in views, how can I push/include this HTML code or view to ajax request so that my nitsbuilder.adder function executes placing the view through my controller.
My present Controller is:
class DropeventController extends Controller
{
public function htmlcode(Request $request)
{
$pluginid = $request['nits_id'];
$code = Plugins::findOrFail($pluginid);
$htmlcode = $code->code;
return response()->json(['htmlcode' => $htmlcode]);
}
}
Please guide me. Thanks
You can easily create html strings from blade views using \View::make
e.g. let's assume you have the following folder strucutre
project
...
ressources
views
snippets
snippetA
snippetB
You could now create a route / controller accepting a "name" parameter and then do the following
$name = "snippetA"; // get this from parameters
$html = \View::make("snippets.$name")->render();
You might need to also add variables depending on your views
$name = "snippetA"; // get this from parameters
$errors = []; // error variable might be needed
$html = \View::make("snippets.$name", compact('errors'))->render();
You can then return this html string
return ['html' => $html];
And access it from your ajax done function.
I hope this helps
Suppose your html is in view file called abc.blade.php, you can return the rendered view from your controller in json.
return response()->json([
'htmlcode' => View::make('abc')->render();
]);
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!
Hi, I use a php code to view the all comments to any post from my sql and I want to add a submit button to every comment in order to delete it without refreshing the page, I mean using AJAX i don't know how to write that codes and connect it with html codes i want add submit like this :
<form>
<input type="submit" id="deletecomment">
</form>
and connected it with AJAX and delete.php page to delete the comment (ajax,delete.php)???????
this is my codes
$result = mysql_query ("select * from post_comments WHERE link ='$getlink' order by link asc");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$link = $row['link'];
$time = $row['time'];
$content = nl2br($row['content']);
$name = ($row['link'] != '') ? '<h3 style="color:blue">'.$row['name'].'</h3>' : $row['name'];
$imge = $row['imge'];
echo '
<div class="commentuserbackground">
<img src="'.$imge.'" width="30px" height="30px">
<div id="comment-'.$id.'" class="username1">'.$name.'</div>
<div class="username2">'.$content.'</div><div class="commenttime"><h4 style="color:#5a5a5a">'.$time.'</h4>
</div></div>';
}
If you already have the jquery lib included in your html, you could do something like this:
# html page
<button data-id="1" class="delete_comment" /> # no need to wrap in form
# At the bottom of the body tag
$(".delete_comment").click(function(e){
e.preventDefault();
var $button = $(this), $comment = $button.parent(), id = $button.data("id");
$.ajax({
type: 'DELETE',
url: "/path/to/comment/" + id,
success: function(){ $comment.remove(); }
});
});
It's my first post in here and I haven't yet figured out to format my post properly yet, but here it goes.
So basically I can only get my code to work if i point directly to a php-file. If I try to call a method within my controller, nothing seems to happen.
My JavaScript:
$(document).ready(function() {
$(".guide_button").click(function(){
var id = $(this).text();
var data = {};
data.id = id;
$.getJSON("/guides/hehelol", data, function(response){
$('#test').text(response.id);
});
return false;
});
});
My markup:
<div id="content_pane">
<ul>
<li>RL</li>
<li>LG</li>
<li>RG</li>
<li>SG</li>
<li>GL</li>
<li>MG</li>
</ul>
</div>
<div class="description">
<h3>Description</h3>
<p id="test">This text area will contain a bit of text about the content on this section</p>
</div>
My Controller:
<?php
class Guides extends CI_Controller {
public function Guides()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
}
public function index()
{
$this->load->view('guides_view');
$title = 'Some title';
}
public function hehelol() //The controller I am desperatly trying to call
{
$id = $_GET['id'];
$arr = array ('id'=>$id);
echo json_encode($arr);
}
}
It might be my controller I have done something wrong with. As it is the code only works if create a hehelol.php file and refer to it directly like this.
$.getJSON("hehelol.php", data, function(response){
$('#test').text(response.id);
});
Anyone who knows what I need to do to make my controller work properly? Help please! :)
i just put your exact code in its entirety in my codeigniter app and it worked for me. Meaning I used this: ...$.getJSON("/guides/hehelol",...
Because you are making a $_GET request, you have to enable query strings.
In your config.php file, make sure this line is set to TRUE:
$config['allow_get_array']= TRUE;