Datatable : click on button does not open view - javascript

I have a datatable which displays overview data correctly.
I added a button which should go to my controller and from there open a new view displaying the details of the selected row.
The click works, I arrive at the method on my controller. But my details view doesn't open.
This is my javascript:
$("#search-logs tbody").on('click', 'button', function () {
var self = this;
var tr = $(self).closest('tr');
var dtRow = datatable.row(tr[0]);
var rowData = dtRow.data();
var processId = rowData[0];
$.get("#Url.Action("Details","Logs")", { id: processId });
});
And this is the code in my controller:
[HttpGet]
public ActionResult Details(int id)
{
return View();
}
Can anyone tell me what I am doing wrong?

you can try:
$("#search-logs tbody").on('click', 'button', function () {
var self = this;
var tr = $(self).closest('tr');
var dtRow = datatable.row(tr[0]);
var rowData = dtRow.data();
var processId = rowData[0];
location.href = '#Url.Action("Details","Logs")?id='+ processId;
});

The problem with your code is that you are calling an ajax get function, that is returning a View, instead of a simple HTTP response. To render this view, you need to redirect your page to that url, instead of doing an ajax request.
$("#search-logs tbody").on('click', 'button', function () {
var self = this;
var tr = $(self).closest('tr');
var dtRow = datatable.row(tr[0]);
var rowData = dtRow.data();
var processId = rowData[0];
location.href = '#Url.Action("Details","Logs")?id='+ processId;
});
Also if you still want to use get request, mostly to check if the id exists as it can return 404 Not found, you can the ajax function like this,
$("#search-logs tbody").on('click', 'button', function () {
var self = this;
var tr = $(self).closest('tr');
var dtRow = datatable.row(tr[0]);
var rowData = dtRow.data();
var processId = rowData[0];
$.get("#Url.Action("Details","Logs")", { id: processId },
function(data, statusText, xhr){
if(xhr.status == 200) location.href = '#Url.Action("Details","Logs")?id='+ processId;
else alert('Sorry, this id does not exist');
});
});

You can open the constructed link in a new window or load in current window
//opens in new window
window.open(newUrlCreated, '_blank');
//opens in current window
window.open(xhr.data);
window.location.href=newUrlCreated;
there are a lot of ways to achieve that.
You can add an onclick="operate(row['info'], row['info'])" to your button which calls a function with specified data
from the datatable row, you will not bother to search for clicked button and row.
function operate(selectedRow, data, ...){
//logic of button for row
}

Related

How to override javascript function "_title_changed" in webclient odoo

My goal is to change the Page title using the company name. I am trying to change the function but still there's no effect. Any idea on how to achieve this?
var session = require('web.session');
var AbstractWebClient = require('web.AbstractWebClient');
AbstractWebClient.include({
_title_changed: function () {
this._super();
var company_name = session.user_companies.current_company[1];
document.title = company_name;
console.log('_title_changed function');
},
});
What I am lacking was odoo.define().
This is what I did:
odoo.define('my_module.AbstractWebClient', function (require) {
"use strict";
/**
* AbstractWebClient Override Method for Page Title
*/
var session = require('web.session');
var AbstractWebClient = require('web.AbstractWebClient');
AbstractWebClient.include({
_title_changed: function () {
this._super();
var company_name = session.user_companies.current_company[1];
document.title = company_name;
console.log('_title_changed function');
},
});
return AbstractWebClient;
});

Javascript foreach loop calls ajax several times

So I am trying to create to do list with several boards. Each board have add item button. If I click add item button it opens modal where to insert task info. But if I click add item button several times and then insert info to modal and press save ajax fires as many times i clicked add item button. How can I prevent from that?
var addNewItems = document.querySelectorAll("#addNewItem");
var addNewSubmits = document.querySelectorAll("#listItemSave");
addNewItems.forEach(function(addNewItem) {
addNewItem.addEventListener("click", function(e) {
var newItemModal = this.nextElementSibling;
newItemModal.classList.toggle("hidden");
var addNewBtn = newItemModal.querySelector("#listItemSave");
//current board
var board = this.closest("div.list");
//current list
var list = board.querySelector(".todo--items");
addNewBtn.addEventListener ("click", function(e) {
//current board id
var boardId = board.dataset.boardid;
//current title
var title = newItemModal.querySelector("#listTitle");
var titleValue = title.value;
//current content
var content = newItemModal.querySelector("#listTextarea");
var contentValue = content.value;
$.ajax({
type: "POST",
url: "add.php",
data: { content: contentValue , title: titleValue , listid: boardId },
success: function(data, textStatus, jqXHR) {
$("#todoItems-" + id + "").append(data);
}
});
});
});
});
You could use a variable, lets say busy, to validate that an AJAX request isn't already on going.
You could set this variable in the beforeSend callback of AJAx and then updated it back to false in the finally callbac :
var addNewItems = document.querySelectorAll("#addNewItem");
var addNewSubmits = document.querySelectorAll("#listItemSave");
addNewItems.forEach(function (addNewItem) {
addNewItem.addEventListener("click", function (e) {
var newItemModal = this.nextElementSibling;
newItemModal.classList.toggle("hidden");
var addNewBtn = newItemModal.querySelector("#listItemSave");
//current board
var board = this.closest("div.list");
//current list
var list = board.querySelector(".todo--items");
var busy = false;
addNewBtn.addEventListener("click", function (e) {
//current board id
var boardId = board.dataset.boardid;
//current title
var title = newItemModal.querySelector("#listTitle");
var titleValue = title.value;
//current content
var content = newItemModal.querySelector("#listTextarea");
var contentValue = content.value;
if (!busy) {
$.ajax({
type: "POST",
url: "add.php",
beforeSend: () => {
busy = true;
}
data: {
content: contentValue,
title: titleValue,
listid: boardId
},
success: function (data, textStatus, jqXHR) {
$("#todoItems-" + id + "").append(data);
},
complete: () => {
busy = false;
}
});
}
});
});
});
This is a pretty simple solution but it works.
You can use addNewBtn.onclick = function () {} instead to overlap the previous listener in this case.
But it's not recommended to register listeners inside another listener. Try to move it out of there.

How to achieve recursive call - jquery

I have a custom created dialog module.
I am passing a mvc view called Cart to this module.
The cart view has a link called 'Create New Contat' clicking on which the view(Cart) will be replaced with another view(Contact) using an ajax call. The contact view has a button called cancel. When the user clicks on Cancel the old view(Cart) will replace the existing view(contact).
The problem I am facing is after replacing the view none of the links or buttons work on the view.
Can some body pls directed me towards a better way of doing this.
Pasted below is the code.
$(document).on('click', '.ddlCart li', function(e) {
var ddlselectedVal = $(this).attr('id');
var selectedListinsCount = selected_Listings.length;
var SelectedMlsnums = selected_Listings.join();
var agentId = $("#AgentId").val();
var Action;
var EnvironmentURL = $("#EnvironmentURL").val();
var postData = { AgentId: agentId, Mlsnums: SelectedMlsnums, ActionTypeValue: “PreAddToCart” };
var close = function (event, ui) {
$('#dvModalDialog').dialog("close");
}
var open = function (event, ui) {
var url = EnvironmentURL + "MLSReports/Stats/SearchContacts";
$("#btncart_cancel").on("click", function () {
$('#dvModalDialog').dialog("close");
});
$("#btncart_submit").on("click", function () {
var url = EnvironmentURL + "MLSReports/Stats/Cart";
//Send the data using post and put the results in a div
$.post(url, {
AgentId: agentId, Mlsnums: SelectedMlsnums, ActionTypeValue: "AddToCart"
},
function (data) {
// Replace current data with data from the ajax call to the div.
$("#dvModalDialog").empty().append(data);
});
});
$("#lnkCreateNewcart").on("click", function () {
var url = EnvironmentURL + "MLSReports/Stats/Cart";
//Send the data using post and put the results in a div
$.post(url, {
ActionTypeValue: "preAddorEditContact"
},
function (data) {
//debugger;
// Replace current data with data from the ajax call to the div.
$("#dvModalDialog").empty().append(data);
$("#btnCancelContact").on("click", function () {
////********** replace the view (Contact) with the view (Cart).
// In the cancel event I am loading the previous page.I am having problem here. after post none of the controls work.
$.post(url, {
ActionTypeValue: "PreAddToCart"
},
function (data) {
//debugger;
// Replace current data with data from the ajax call to the div.
$("#dvModalDialog").empty().append(data);
})
});
});
});
};
if (ddlselectedVal == "AddtoCart") {
var rd = Mod.ReportsDialog({ title: 'Add To Cart', close: close, open: open });
rd.url = EnvironmentURL + "/MLSReports/Stats/Cart";
rd.targetElement = '#dvModalDialog'// '#dvSendEmail'
rd.formName = '#frmCart'
rd.postData = postData
rd.open();
}
});

Enyo JS : Set moon.DataGridList collection dynamically

Is there away to set a grid collection dynamically after an ajax call ?
.....
create: function () {
this.inherited(arguments);
this.onFetchItemList();
},
onFetchItemList: function(){
var prof = this.userProfile;
obj.getBrowse(prof,function onBrowseCallback(list){
this.set("collection", new enyo.Collection(list));
});
}
.....
I get this method is undefined when I try to use the set function
this.$.gridList.set("collection" ,new enyo.Collection(list));
same error here as well :
this.$.gridList.collection.set('collection',this.shows);
Fixed, simply mistake on my part , whoops :)
onFetchItemList: function(inSender, inEvent){
var prof = this.userProfile;
var _gridList = this.$.gridList;
var shows = new enyo.Collection();
obj.getBrowse(prof,function onBrowseCallback(list){
ameba_lastListViewed = [];
ameba_lastListViewed = list;
shows = new enyo.Collection(list);
_gridList.set('collection',shows);
}

A div on click redirect to another HTML page and call a javascript to show a particular div

I have two html files namely FIRST.html and SECOND.html
FIRST.html has DIVs with IDs A1 to A100, SECOND.html has DIVs with IDs B1 to B100
On clicking a particular DIV in FIRST.html, I want to redirect the user to SECOND.html and show the corresponding DIV.
For example, if a user clicks DIV id=A10 in FIRST.html, he should be redirected to SECOND.html and be shown the DIV id=B10.
I need thoughts on how this could be done, I would like to know if we could pass some parameters from one page to another and then call a javascript using those parameters.
Thank you!
You could try something like this:
Add this to FIRST.html
$(document).ready(function() {
$('div').click(function () {
id = $(this).attr('id').substring(1);
window.location = 'SECOND.html?id=' + id;
});
var getVar = location.search.replace('?', '').split('=');
$('div[id$=' + getVar[1] + ']')[0].scrollIntoView();
});
Add this to SECOND.html
$(document).ready(function() {
$('div').click(function () {
id = $(this).attr('id').substring(1);
window.location = 'FIRST.html?id=' + id;
});
var getVar = location.search.replace('?', '').split('=');
$('div[id$=' + getVar[1] + ']')[0].scrollIntoView();
});
//FIRST.html
$("#A10").click(function () {
document.location.href = "SECOND.html?id=B10";
})
//SECOND.html
$(function () {
//Prepare the parameters
var q = document.location.search;
var qp = q.replace("?", "").split("&");
var params = {};
$(qp).each(function (i, kv) {
var p = kv.split("=");
params[p[0]] = p[1];
});
var idToOpen = params["id"]
$("#" + idToOpen).show();
})
//You can add some other parameters
document.location.href = "SECOND.html?id=B10&message=SomeMessage";
//Get it like this
$(function () {
//Prepare the parameters
var q = document.location.search;
var qp = q.replace("?", "").split("&");
var params = {};
$(qp).each(function (i, kv) {
var p = kv.split("=");
params[p[0]] = p[1];
});
var idToOpen = params["id"]
var message = params["message"]
$("#" + idToOpen).show();
alert("message")
})
in FIRST.html put this code
$('div').click(function() {
var someId = $(this).attr("id");
window.open('SECOND.html/#'+someId);
});
Or you can use your full URL path instead SECOND.html/#. Its just an idea, not tested, but you can try it. P.S. Those are two different pages, so you can put same ID's on both to try this example. It's not pure JavaScript but Jquery.

Categories

Resources