appending via Ajax to .closest() parent not working jquery - javascript

I'm commenting an specific post from a list. This is why I'm using .closest() parent.
JQUERY
$('.comment').on('click', function(){
var parent = $(this).closest('.post');
$(document).CommentButton(id_user,comment);
});
FUNCTION The comments posts via Ajax and retrieve a value....
jQuery.fn.CommentButton=function(id_user,comment){
$.ajax({
type: 'POST',
url: "comment.php",
data: {
"comment":comment,
"id_user":id_user,
},
success: function(data) {
//alert(data)
parent.find(".container").append(comment);//problem
}
});
}
HTML I choose a random post to comment from the list.
<ul>
<li class="post"></li>
<li class="post"></li>
<li class="post">
<div class="container"></div>
<button class="comment"></button>
</li>
<li class="post"></li>
</ul>
PROBLEM
I cant append the comment in its specific container of his parent. How should I do that?

Related

Send items from forloop populated data in django template through ajax to django view

I have been trying to create a click and populate div with ajax in my django e-commerce application. The project works in such a way that when a customer clicks on a category in men's page it populates another div
gender.html
{%for cate in cat%}
<a href="javascript:getcat()" id="catgend" cats-data="{{cate.catname}}" gen-data="{{gens.gender}}" data-sort-url="{% url 'Home:sortcat' cpk=cate.pk %}" >{{cate.catname}}</a>
{% endfor %}
<div id="products">
<div class="progress">
<img src="{% static 'img/load.gif'%}">
</div>
</div>
This sends the data to my django view through the ajax function called getcat but the data sent through is that of the first item in the loop in-respective of the loop item clicked on. below is my ajax function:
getcat()
function getcat() {
$(".progress").show()
var cat = $("#catgend").attr("cats-data");
var gender = $("#catgend").attr("gen-data");
var url = $("#catgend").attr("data-sort-url");
$.ajax({
url: url,
data: {
'cat': cat,
'gender': gender,
},
success: function (data) {
$("#products").html(data);
}
});
$(".progress").hide()
}
enter code here
From my research i discovered its because they have same ID. How do i solve the issue of dynamically changing the id over the same loop. Thanks
Replace the id attribute with a class attribute since you shouldn't have more than a single element with the same id. Also, we can change cats-data and gen-data to valid data-* attributes.
{% for cate in cat %}
<a href="#" class="catgend" data-cats="{{cate.catname}}" data-gen="{{gens.gender}}" data-sort-url="{% url 'Home:sortcat' cpk=cate.pk %}" >{{cate.catname}}</a>
{% endfor %}
Bind a click event to anchors using the new class name.
$('.catgend').on('click', function (e) {
$('.progress').show()
var data = $(this).data()
$.ajax({
url: data.sortUrl,
data: {
'cat': data.cats,
'gender': data.gen,
},
success: function (data) {
$('#products').html(data);
}
});
$('.progress').hide()
});
Utilise the data attributes to accumulate data values in a simple way.

Passing data from MVC controller to jsTree through ajax calls.

I have a jsTree with a parent node and 5 children nodes. They function fine. I am trying to implement a dynamic jsTree where with click of a node, an ajax call should pass that node's ID to my java MVC spring-boot controller and a Map with keys as child nodes' IDs and value as names of child nodes.
So far I have managed to get the value of the clicked child node's ID and pass it to my java controller through ajax call. But I'm not able to proceed further as I am not sure how to structure the data that is passed from controller to ajax call which in turn has to implement the jsTree.
Here's the code of my existing jsTree -
<div id="container">
<ul>
<li id = "id1">Root
<ul>
<li id="id 1-1">child 1</li>
<li id="id 1-2">child 2</li>
<li id="id 1-3">child 3</li>
<li id="id 1-4">child 4</li>
<li id="id 1-5">child 5</li>
</ul>
</li>
</ul>
</div>
Here's the code of my ajax -jquery call that passes the nodeID to the controller-
$(function() {
$('#container').on('changed.jstree', function (e, data) {
var i, j, r = [], rid = [];
for(i = 0, j = data.selected.length; i < j; i++) {
r.push(data.instance.get_node(data.selected[i]).text);
rid.push(data.instance.get_node(data.selected[i]).id);
}
console.clear();
console.log('Selected: ' + r.join(', '));
console.log('Selected id: ' + rid.join(', '));
$.ajax({
type: 'GET',
url: "http://localhost:8080/tree/object?nodeID="+rid.join(', '),
contentType: 'text/plain',
crossDomain: false,
async:true,
success:function() {
}
});
})
.jstree();
});
I'm limited by my knowledge of jsTree, ajax and jquery. Any help would be appreciated. I am looking into the documentation of jsTree: filling the tree through ajax calls here.
You don't want to do your own AJAX call - You can set a URL to use as per: https://www.jstree.com/api/#/?f=$.jstree.defaults.core.data and JSTree will perform the Ajax calls for you.
set the url property to your url, and data to a function that returns the node id;
'url' : 'ajax_nodes.html',
'data' : function (node) {
return { 'id' : node.id };
}
If returning the data from an Ajax call - you should probably return it in JSON instead, not in HTML.
So this page is what you should be looking at: https://www.jstree.com/docs/json/
The minimum you need is a JSON object like so;
{
id : "string" // will be autogenerated if omitted
text : "string"
children : false
}
Where Children should be true if that node can expand and trigger another all with itself as the ID passed to get its children and false if it is a leaf node.

Send order of jQuery sortable to Laravel controller

I have a collection of Article objects that have a public attribute int priority. This field ist used to display the articles in the intended order. However, I'd like to be able to rearrange the order of the articles in the admin area.
I included jQuery and with this Laravel/Blade snippet
<ul class="selectable-demo-list" id="sortable-list-basic">
#FOREACH($articles as $article)
<li> {{ $article->label}} </li>
#ENDFOREACH
</ul>
I can produce this HTML output:
<ul class="selectable-demo-list" id="sortable-list-basic">
<li> My article (ID: 1) </li>
<li> Another article (ID: 2) </li>
<li> ... </li>
</ul>
I can access the respective priority via $article->priority and their unique IDs via $article->id if these elements should be included in the code.
The <ul> posted above is rendered correctly: All <li> elements are displayed as sortable jQuery elements. If I drag an item to a certain position, it stays there for the time being.
Unfortunately, I have no idea how to save the new order (= update the items priorities according to the list positions).
This shouldn't be done directly. Instead, I want to use an update button. Maybe I can use a form and send an array like this to my controller:
$priorities = [1=>3; 2=>1; 3=>2] // ID => new priority
Is this possible? Or should I use a different approach? Any help is greatly appreciated!
Add id with each of your li like id="id-{{ $article['id'] }}"
You can call an ajax request when you are changing any order using this sortable plugin like below code
$("#sortable-list-basic").sortable({
update: function (e, u) {
var data = $(this).sortable('serialize');
$.ajax({
url: "{{ url('controller/sorting_method') }}",
type: 'post',
data: data,
success: function (result) {
},
complete: function () {
}
});
}
});
Then inside your method, take your new order for each item & save it to database such as
$ids = $request->id;
foreach($ids as $order => $id){
$article = Article::findOrFail($id);
$article->order = $order;
$article->save();
}

Fetching with PHP, using with Javascript

I'm currently facing a problem and i would like your assistance to solve it the right way. Two languages.. depending on it's other. (At least in my case).
PHP: access database, insert, select data.
Javascript: useful calling events without having to refresh my page.
Well.. i've used ajax, but my way seems quite complicated to be correct.
Let me use an example. Let's say that i have the following PHP function.
function createDiv($value1, $value2, $value3){
echo "
<div>
<h3>."$value1".</h3>
<h3>."$value2".</h3>
<h3>".$value3."</h3>
</div>
";
}
My inside my HTML i'm calling this function like this.
<?php
$values = $db->getValues(); //( Let's say that i'm getting an array )
createDiv($values[0],$values[1],$values[2]);
?>
Now lets go a step further... I want to append data inside this div when clicking on a predefined list item without having to refresh.
<ul class="social-buttons" id="demo2">
<li>
<a onclick="letterSearch(this);" >A</a>
</li>
<li>
<a onclick="letterSearch(this);" >B</a>
</li>
<li>
<a onclick="letterSearch(this);" >C</a>
</li>
<li>
So, now i'm using javascript & ajax.
function letterSearch(element){
//With this ajax i'm calling a similar function to $db->getValues();
//That i called before to get my values
//With the difference of the searching parameter
$.ajax ({
type:"POST",
url: "ajaxAccess.php",
dataType:"json",
data: {tag: 'valuesWithSearch', arguments: element.innerHTML},
success: function(result) {
var jsonValues = JSON.parse(result);
//After this point i have stored in jsonValues the expected array list that i wanted to get.
//Now what??
}
});
}
So..
My first question is: how can i put the data i just got from ajax at the bottom of my div?
jQuery.append()?
And last but not the least.. Is my approach overcomplicated? Is there any other way?
IN PHP
<?php
echo json_encode(["values"=>$db->getValues()); //Let's say this is an array
?>
IN HTML
<ul class="social-buttons" id="demo2">
<li>
<a class="letter-search" >A</a>
</li>
<li>
<a class="letter-search" >B</a>
</li>
<li>
<a class="letter-search" >C</a>
</li>
<li>
IN JAVASCRIPT/JQuery
$(".letter-search").click(function(e){
e.preventDefault();//Prevent default link action
letterSearch($(this));
})
function letterSearch(element){
$.ajax ({
type:"POST",
url: "ajaxAccess.php",
dataType:"json",
data: {tag: 'valuesWithSearch', arguments: element.text()},
success: function(result) {
var response = JSON.parse(result);
//You now have a valid JSON response
//Append if needed, or loop through and process before appending
element.append(response.values)
}
});
}

Binding not working for Knockout, ReferenceError when ko.applybindings on specific element

I have this ajax to get the data
var homeSummaryViewModel;
$(document).ready(function () {
getHomeSummaryViewModel();
});
function getHomeSummaryViewModel() {
$.ajax({
url: "/api/homeservice/get",
type: "get",
contentType: "application/json",
success: function (result) {
homeSummaryViewModel = ko.mapping.fromJSON(result);
ko.applyBindings(homeSummaryViewModel, $("#homeSummary").get(0));
},
error: function (result) {
//handle the error, left for brevity
}
});
}
Here is my html
<div class="plan-name-bronze">
<h4>Home</h4>
<div class="icon">
<i class="fa fa-trophy fa-5x"></i>
</div>
</div>
<ul class=" text-left" id="homeSummary">
<li class="plan-feature">Completed Level : <span data-bind="text: Level"></span> </li>
<li class="plan-feature">Total Score : <span data-bind="text: Score"></span> </li>
</ul>
</div>
</div>
Here is my JSON
{"Level":"Noob","Score":788}
I get this error below in knockout-3.0.0.debug.js, when id do homeSummaryViewModel.peek() i get null. i see the data is sent from server in firebug as show above JSOn Data, ko.mapping does not throw error it just is not working maybe???
ReferenceError: Level is not defined return new Function("$context",
"$element", functionBody);
i had to use
homeSummaryViewModel = ko.mapping.fromJS(result);
instead of
homeSummaryViewModel = ko.mapping.fromJSON(result);
The value binding is only for form-input elements; you need to be using the text binding.
The problem is you binding with the $.get, I created a simple test case http://jsfiddle.net/PB9KL/, it works fine.
var homeSummaryViewModel;
getHomeSummaryViewModel();
function getHomeSummaryViewModel() {
homeSummaryViewModel = ko.mapping.fromJSON('{"Level":"Noob","Score":788}');
ko.applyBindings(homeSummaryViewModel,document.getElementById("homeSummary"));
}

Categories

Resources