i want to have simple functionality in my app. When user clicks on "show replies" button, div with class "replies" will show up, then button changes to "hide replies" and when click it again the div will disappear. I am close but the problem is: when I click on button first time (after reloading page), the button changes to "hide", data is not showing up. Until i click it second time it shows and then i have data and button "show replies". In other words: ajax call doesn't work on first time, data prints properly even with first click. Please help me to understand what is wrong.
ajax
$(document).ready(function () {
$(".showReplies").click(function () {
let id = $(this).attr('id');
$.ajax({
url: $(this).attr("data-href"),
type: 'get',
success: function (data) {
console.log(data);
$(`#${id}.replies`).html(data);
let text = $(`#${id}.showReplies`).text()
if (text == 'Show replies') {
text = 'Hide replies'
$(`#${id}.showReplies`).text(text)
} else {
text = 'Show replies'
$(`#${id}.showReplies`).text(text)
}
}
})
});
});
template
<button type="button" id="{{ comment.id }}" class="showReplies btn btn-link" data-href="{% url 'comment_replies' comment.id %}">Show replies</button>
<div class="replies" id="{{ comment.id }}" style="margin-left: 30px;">
{% include 'blog/comment_replies.html' %}
</div>
urls
path('comment_replies/<int:comment_id>/', comment_replies, name='comment_replies')
view
def comment_replies(request, comment_id):
comment = Comment.objects.get(id=comment_id)
replies = Reply.objects.filter(comment=comment)
context = {'replies': replies}
return render(request, 'blog/comment_replies.html', context)
Ok, #Swati found the solution:
$(document).ready(function () {
$(".showReplies").click(function () {
let id = $(this).attr('id');
$.ajax({
url: $(this).attr("data-href"),
type: 'get',
success: function (data) {
console.log(data);
$(`#${id}.replies`).html(data);
let text = $(`#${id}.showReplies`).text();
console.log(text);
if (text == 'Show replies') {
text = 'Hide';
$(`#${id}.showReplies`).text(text);
$(`#${id}.replies`).show();
} else {
text = 'Show replies';
$(`#${id}.showReplies`).text(text);
$(`#${id}.replies`).hide();
}
}
})
});
});
I had to add $(#${id}.replies).show();and $(#${id}.replies).hide();in if and else.
Related
In Django, how to click button on page without passing any value to view.py and then reloading current page? I have a button in the HTML:
<button type="button" class="btn btn-primary" id="refresh">refresh page</button>
I want to call a view in view.py, in which new HTML will be returned:
#csrf_exempt
def topology_show_refresh(request):
'''topology refresh'''
plan = {...}
...
return render(request, 'topology_show.html', {'plan': plan})
The plan dictionary will be used in the new page.
{% if plan.try == 'first' %}
<script type="text/javascript">
var max_lane_num = {{plan.max_lane_num}};
var flag = 0;
</script>
{% else %}
<script type="text/javascript">
var max_lane_num = {{plan.lane_second}};
var flag = 1;
</script>
{% endif %}
In my way, I use ajax to jump to this view, but I have no idea how to handle the return, e.g., pass the plan to HTML.
$(function(){
$("#refresh").click(function(event){
url = 'refresh/';
$.post(url, {}, function(ret){
//do something
//how to pass "plan" dictionary to HTML
});
});
});
You are very close to the task of reloading page,
Use 'location.reload(true)' instead of 'window.location.reload();'
And handle the response data by success() function.
Try this :
$(function(){
$("#refresh").click(function(event){
$.ajax({
type: "POST",
url: 'refresh/',
success:function(response) {
location.reload(true);
//do something with 'response'
}
});
});
I'm new in Js. This is my code:
<button class="btn btn-primary" data-id = "#item.Id" id="accept">Accept</button>
var tempId;
$('button.accept').click(function () {
tempId = $(this).attr('data-id')
$.ajax({
type: "POST",
url: "/TabRequest/AcceptRequest",
data: { 'id': tempId },
success: function (msg) {
}
});
})
As you can see I'm trying to post "data-id" to Action. When I click to to button, does nothing. Can anybody help me?
You need
$('button#accept')
instead of
$('button.accept')
Since accept is an ID for the button, use # as selector and you can use . for class selector.
you can see reference for jQuery seletors
I have a page that has a few divs connected in a flowchart via JS-Graph.It. When you click one of the divs, I want it to 1) generate text in a special div 2) generate a popup via click functions attached to the two classes "block" and "channel" in each div. This works when the page is static.
When I add ajax so on click of a button and add more divs, only one of the two classes appears in the HTML source. "Channel" is no longer visible and the function to generate a pop-up on click of a channel class div does not work anymore...
AJAX call:
$("#trace").bind('click', $.proxy(function(event) {
var button2 = $('#combo').val();
if(button2 == 'default') {
var trans = 'Default View';
}
if(button2 == 'abc') {
var trans = 'abc';
}
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button2=' + $('#combo').val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
success: function(data) // Variable data constains the data we get from serverside
{
JSGraphIt.delCanvas('mainCanvas');
$('.test').html('<h1>' + trans + '</h1>'); // Clear #content div
$('#mainCanvas').html(''); // Clear #content div
$('#mainCanvas').append(data);
JSGraphIt.initPageObjects();
}
});
return false; // keeps the page from not refreshing
}, this));
DIV class: (works in index.php but not transactions.php)
// Boxes
while($row = sqlsrv_fetch_array($result))
{
echo '<div id="'.$row['id'].'_block" class="block channel" style="background:';
Functions:
$(document).on('click', '.block', $.proxy(function(event) {
var input = $(event.target).attr('id');
var lines = input.split('_');
var button = lines[0];
$.ajax({
url: 'srv.php',
data: 'button=' + button,
dataType: 'json',
success: function(data)
{
$('#content').html('');
$('#content').append(data);
}
});
return false;
}, this)); // End Application Details
$(".channel").click(function () {
alert('channel');
});
Something about registering with pages, I'm not sure exactly how it works. The fix should be to change your channel click function to be the same as your first and use the .on('click') option.
found some related reading material. https://learn.jquery.com/events/event-delegation/
I have a scenario like this.
Initially loaded when page is navigated to #Action.
Once the select action is performed data-bind="with tag is loaded"
User click on "Do Something" action is performed. Which replaces the whole "parentNode"
Now When the user clicks back, and the sammy.js notices the hash tag #Action/:id, I need to load the #Action to get back the main View and then select the id to load the data-bind="with" tag again.
How can I do this?
Currently the page does go back to "Action/:id" but since main view is not loaded it doesn't do anything. I have used "this.redirect("#Action") then selected the node, but the doesn't work.
<div id="parentNode">
<ul data-bind="foreach: items">
<li data-bind="click: $root.selectItem">
<h2><span data-bind="text: Sometext"></span></h2>
</li>
</ul>
<div data-bind="with: selectedItem">
<a data-bind="click: loadSomething">Do Something</a>
</div>
</div>
In my viewmodel i have this:
viewModel.selectItem= function (item) {
location.hash = "Action/" + item.id();
}
viewModel.loadSomething = function () {
location.hash = "Action/" + viewModel.someSelectedItem().id() +"/SubAction";
}
$.sammy(function () {
this.get('#Action', function () {
$.ajax({
url: '#Url.Action("GetMainView")',
type: "GET",
data: self.someId(),
dataType: "json",
success: function (result) {
$("#parentNode").html(result.message);
}
});
this.get('#Action/:id', function () {
var id = this.params["id"];
var matchItem = ko.utils.arrayFirst(viewModel.MainItems(), function (item) {
return item.id() == id;
});
viewModel.someSelectedItem(matchItem);
});
this.get('#Action/:id/SubAction', function () {
var id = this.params['id'];
$.ajax({
url: '#Url.Action("ViewSomething")',
type: "GET",
data: { id: id },
success: function (result) {
$('#parentNode').html(result.message);
}
});
});
});
Sample Code: https://skydrive.live.com/redir?resid=33048714B5BF3B4B!913
Steps to Reproduce:
Select "SubItems" under any of the items listed (Item 1, Item 2, Item 3)
Select any of the Sub Items that Label (Sub Item 1, Sub Item 2)
Partial View will be shown with "Sub Item {x}" with "Next View" link
Click "Next View" link.
"Next Partial View" will be shown.
Press the back button.
The thing I am trying to do is to load the SubItems and Select "Sub Item 1" view.
List item
I'm not sure this will work, but could you create a separate helper function to load the main view. Then it would be the case of the following:
this.get('#Action', function () {
LoadMainView();
}
this.get('#Action/:id', function () {
if($('#parentNode').length == 0) {
LoadMainView(function() {
var id = this.params["id"];
var matchItem = ko.utils.arrayFirst(viewModel.MainItems(), function (item) {
return item.id() == id;
});
viewModel.someSelectedItem(matchItem);
})
}
}
Your LoadMainView function would then accept a callback and be something like this:
function LoadMainView(callback) {
$.ajax({
url: '#Url.Action("GetMainView")',
type: "GET",
data: self.someId(),
dataType: "json",
success: function (result) {
$("#parentNode").html(result.message);
if(typeof callback == "function") {
callback();
}
}
});
}
I haven't been able to test this in your solution (I get an error opening it), but I believe that's the general structure to do what you are asking.
I have made an Ajax function but i am getting a big prolem in that.
I was displaying the contents on click of the link..
The links are fetched from the database and also the url of the links are fetched from the datbase.
I have wriiten ajax to call the contents dynamically on click of the link
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>
Now FetchUrlByHobbyName is the function called from the Controller thart returns the url
//Ajax routine to fetch the hobbyinfo by hobbyname
[HttpPost]
public ActionResult FetchUrlByHobbyName(string data)
{
HobbyMasters hobbymaster = new HobbyHomeService().FetchHobbyMasterByHobbyName(data);
string url = hobbymaster.InformationUrl;
if (HttpContext.Request.IsAjaxRequest())
return Json(url);
return View();
}
And in my View i have written the link like this:
#foreach (var item in Model)
{
<li >#Html.ActionLink(item.HobbyName, "Hobbies")
</li>
}
i tried this :
#Html.ActionLink(item.HobbyName, "Hobbies", null, new { id = "alink" })
and then calling Ajax on click of 'alink' but with this my ajax function doesnot get called.
Now the problem is the ajax function is getting called on click of every link on the page..
I want to assign a unique Id to it but i am not understanding how to do that
please Help me...
For that specific link, assign an id. E.g
<a id="someID" href="url">Link</a>
and than bind the click only with that link.
$('#someID').click(function (e)) ....
If I understood you correctly this helps you
The text of the link
<script type="text/javascript">
function myAjaxFunction(){
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
</script>
Try to give a css class selector to you action link like this...
#Html.ActionLink("some link", "Create", "Some_Controller", new { }, new { #class = "test" })
then User jquery for it..
<script type="text/javascript">
$(document).ready(function () {
$('.test').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>