I am trying to update a webpage so that when the delete button is pressed the attached row is removed from the table and the message_uid value is sent to the Flask route so I can process the request to actually change the message's status in the database. However the request does not send. I can get the row to be removed and have attempted to use a form to update instead but would need the delete function to not return any other value than edit the update section in the HTML.
route
#bp.route("/delete", methods=['GET','POST'])
def delete():
data = request.get_json()
data=delete(data, g.user)
return Response(dumps(data), mimetype="application/json")
inbox.html
<h1><b>Messages: </b></h1><div id="update"> </div>
<div class="table-responsive"
<table class="table table-bordered table-hover table-striped">
<tr>
<th></th>
<th>Status</th>
<th>Actions</th>
<th>Date</th>
<th>From</th>
<th>To</th>
<th>Subject</th>
<th>Body</th>
<th>References</th>
</tr>
{% for m in messages %}
{%if m.status!="deleted"%}
<tr >
<td><a class="btn btn-light" id="view" onClick="window.open('{{url_for('open_messages',message_id=m.message_uid)}}','View','resizable,height=500,width=500'); return false;" >View</a>
<input type="hidden" name="message_uid" value={{m.message_uid}} id="message_uid" /> <input type="submit" class="btn-sm btn-secondary" value="Delete" /></td>
<td>{{m.date}}</td>
<td>{{m.sender}}</td>
<td>{{m.recipient_username}}</td>
<td>{{m.subject}}</td>
<td>{{m.body}}</td>
<td>{{m.references}}</td>
</tr>
{%endif%}
{% endfor %}
</table>
<script>
$(document).on("click",".delete", function(e) {
e.preventDefault()
var id = $(".message_uid").val();
delete_id(id);
$(this).parents("tr").remove();
});
function delete_id(id) {
data = {
"id": id
}
console.log(data)
$.ajax({
type:"POST",
url: "/delete",
contentType: "application/json",
data: JSON.stringify(data),
success: function(data){
//displays dates if set
$("#update").html("Message Deleted");
console.log(data)
}
});
};
</script>
database processing
def delete(message_uid, user):
text="MATCH (m:MESSAGE) WHERE m.UID='{message_uid}' SET m.{user}_status='deleted' RETURN m".format(message_uid=message_uid, user=user)
verify=neo_execute(text)
return verify
Related
I am building a web app using Django. I am not that familiar with javascript/html since it is not my domain of specialty.
What I am doing is searching for a name that will be looked up in the api and it will return it with other information.
I'll post the codes which I think is realted to my issue. If you need anything more, I can provide it.
views.py
from django.shortcuts import render
from .models import customer
import requests
def get_customer(request):
all_customers = {}
if 'name' in request.GET:
name = request.GET['name']
url = 'https://retoolapi.dev/aSIZJV/customer__data?FirstName=%s'%name
response = requests.get(url)
data = response.json()
customers = data
for i in customers:
customer_data = customer(
uid = i['id'],
f_name = i['FirstName'],
m_name = i['MiddleName'],
l_name = i['LastName'],
phone = i['Phone'],
email = i['Email'],
DOB=i['DateOfBirth'],
EID=i['EmiratesID']
)
customer_data.save()
all_customers = customer.objects.all().order_by('-id')
return render (request, 'customer.html', { "all_customers": all_customers} )
customer.html
{% extends 'base.html'%}
{% load static %}
{% block content %}
<div class = "container">
<div class = "text-center container">
<br>
<h2 class = "text-center">Search for the desired customer</h2>
<br>
<form method="GET">
<input type='button' value='Remove Table Body' onclick='removeTableBody()'/>
<!-- I am trying to remove the table body using the line above, but it is not working-->
<input type = "text" name = "name" placeholder="Search..." class = "text-center">
<button type = "submit" class = "btn-danger btn-sm">SEARCH CUSTOMER</button>
</form>
</div>
<br><br>
<div class="container">
<h1>Customer Table</h1>
<div id="toolbar">
<select class="form-control">
<option value="">Export Basic</option>
<option value="all">Export All</option>
<option value="selected">Export Selected</option>
</select>
</div>
<table id="table"
data-toggle="table"
data-search="true"
data-filter-control="true"
data-show-export="true"
data-click-to-select="true"
data-toolbar="#toolbar">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="ID">ID</th>
<th data-field="FirstName" data-filter-control="input" data-sortable="true">First Name</th>
<th data-field="MiddleName" data-filter-control="input" data-sortable="true">Middle Name</th>
<th data-field="LastName" data-filter-control="input" data-sortable="true">Last Name</th>
<th data-field="Phone" data-filter-control="select" data-sortable="true">Phone</th>
<th data-field="Email" data-filter-control="select" data-sortable="true">Email</th>
<th data-field="DateOfBirth" data-filter-control="select" data-sortable="true">Date Of Birth</th>
<th data-field="EmiratesID" data-filter-control="select" data-sortable="true">EmiratesID</th>
</tr>
</thead>
<tbody>
{% for customer in all_customers %}
<tr>
<td class="bs-checkbox "><input data-index="0" name="btSelectItem" type="checkbox"></td>
<td>{{customer.uid}}</td>
<td>{{customer.f_name}}</td>
<td>{{customer.m_name}}</td>
<td>{{customer.l_name}}</td>
<td>{{customer.phone}}</td>
<td>{{customer.email}}</td>
<td>{{customer.DOB}}</td>
<td>{{customer.EID}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
<!-- partial -->
static/website/dist/script.js
var $table = $('#table');
$(function () {
$('#toolbar').find('select').change(function () {
$table.bootstrapTable('refreshOptions', {
exportDataType: $(this).val()
});
});
})
var trBoldBlue = $("table");
$(trBoldBlue).on("click", "tr", function (){
$(this).toggleClass("bold-blue");
});
var $table_empty = $('#table');
$(function removeTableBody() {
$('#table tbody').empty();
})
// I wrote the line above to empty the table
When I press the button to empty the rows in the table, I see this on the terminal:
[15/Dec/2021 15:34:05] "GET /style.css HTTP/1.1" 404 2283
[15/Dec/2021 15:34:05] "GET /script.js HTTP/1.1" 404 2283
This a view of how the table looks:
enter image description here
I want to get new responses everytime I send a GET request.
Judging by the fact that your .css and your .js are reporting 404 not found, I'm going to assume that it's an issue with your static root. I think by default the STATIC_ROOT in your settings file will be /static, but your js is apparently at /static/web/dist, so you should either update your STATIC_ROOT to /static/web/dist or specify the path from /static in your base.html when you're loading the files.
(Edit)
Also. Your View is requesting data from another website and saving all the data it receives as new model instances. You're getting duplicates on your page because you have duplicates in your database, not because of the javascript.
Your javascript is set up to reload the page every time you hit Search Customer, so, the javascript failing to clear the table is definitely irrelevant to your duplicate problem.
Lastly, your removeTableBody function is inside $( ) which means the function only exists inside the scope of those brackets. So if you click your clear table button, I'm sure it would post to your console that the removeTableBody function doesn't exist. Remove the $( ).
I have a .Net MVC project that fills a table with data using a bootstrapTable from bootstrap v3. I want to add a delete button to each row.
The bootstrapTable takes json data and loads it. The json is built like this:
public virtual JsonResult Search(FormCollection searchArgument)
{
IEnumerable<MyData> myListData = GetMyListData(searchArgument);
var jsonResult = Json(myListData, JsonRequestBehavior.AllowGet);
return jsonResult;
}
So the jsonResult is just a list of all of my MyData. My view that shows the result looks like this:
#model MyNamespace.Web.Models.MyListViewModel
<div class="col-md-12">
#{
ViewBag.Title = "Index";
Layout = MVC.Shared.Views._Layout;
<div class="row">
<div class="col-md-12">
<form role="form" id="formsearch">
<input id="fromsearch" name="fromsearch" type="hidden" value="true" />
<div class="form-group">
#Html.LabelFor(m => m.Status, "Status:")<br />
#Html.DropDownList("status", new SelectList(Model.Status, "Value", "Key", Model.SelectedStatus), new { #class = "selectButton" })
</div>
<input type="button" id="btnsearch" value="Search" />
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table id="table" class="table">
<thead>
<tr>
<th data-field="MyDataNumber" data-sortable="true">Number</th>
<th data-field="MyDataCreatedate" data-sortable="true">Created</th>
<th data-field="Status" data-sortable="true">Status</th>
</tr>
</thead>
</table>
</div>
</div>
}
</div>
<script>
$("#btnsearch").click(function () {
$('#table').bootstrapTable('showLoading');
$.ajax({
type: "POST",
url: "#Url.Action(MVC.MyController.ActionNames.Search, MVC.MyController.Name)",
data: $('#formsearch').serialize(),
dataType: "json",
success: function (data) {
$('#table').bootstrapTable('hideLoading');
$('#table').bootstrapTable({
data: data,
striped: true,
pagination: true,
pageSize: 25,
pageList: [10, 25, 50, 100, 200],
search: false
});
$('#table').bootstrapTable('load', data).on('click-row.bs.table', function (e, row, $element) {
Showdetail(JSON.stringify(row));
});
},
error: function (err) {
console.log(err)
}
});
});
function Showdetail(jsonrow) {
var obj = JSON.parse(jsonrow);
window.location = "#Url.Action(MVC.MyController.ActionNames.ShowMyData, MVC.MyData.Name)?myDataId=" + obj.Id;
}
</script>
#section AddToHead
{
#Styles.Render("~/bundles/bootstrap-table/css")
}
#section scripts
{
#Scripts.Render("~/bundles/bootstrap-table")
}
So the javascript function ("#btnsearch").click gets the json data from public virtual JsonResult Search and sends that to bootstrapTable which loads the data in the table. What I want to do is to add a new header in my table, like this:
<table id="table" class="table">
<thead>
<tr>
<th data-field="MyDataNumber" data-sortable="true">Number</th>
<th data-field="MyDataCreatedate" data-sortable="true">Created</th>
<th data-field="Status" data-sortable="true">Status</th>
<th></th>
</tr>
</thead>
</table>
And then in the last column add a delete button that has the id of that row (#Model.Id for instance) so that I can call the controller to delete the row from the database and then reload the table so that the row also disappears from the GUI.
I could easily do it with an ActionLink but since I don't loop through all objects and then draw them out on the page, I can't just add an ActionLink to the page. All the rendering of the rows is done in the bootstrapTable.
I looked at this question and answer and it seemed promising but it's not quite what I'm doing and I can't get my head around what I would need to do to get it working for me: Bootstrap table - dynamic button in row.
According to documantation and examples here:
https://live.bootstrap-table.com/example/column-options/events.html
Add to your scripts:
<script>
var $table = $('#table')
function operateFormatter(value, row, index) {
return [
'<a class="remove" href="javascript:void(0)" title="Remove">',
'<i class="fa fa-trash"></i> Delete',
'</a>'
].join('')
}
window.operateEvents = {
'click .remove': function (e, value, row, index) {
//edit here for ajax request to delete row.id record
$.ajax({
type: "POST",
url: "#Url.Action(MVC.MyController.ActionNames.Delete,MVC.MyController.Name)",
data: {id:row.id},
dataType: "json",
success: function (data) {
//when success remove row
$table.bootstrapTable('remove', {
field: 'id',
values: [row.id]
})
},
error: function (err) {
console.log(err)
}
});
}
}
</script>
and edit your html table:
<table id="table" class="table">
<thead>
<tr>
<th data-field="MyDataNumber" data-sortable="true">Number</th>
<th data-field="MyDataCreatedate" data-sortable="true">Created</th>
<th data-field="Status" data-sortable="true">Status</th>
<th data-field="operate" data-formatter="operateFormatter" data-events="operateEvents">Actions</th> <!--add this col-->
</tr>
</thead>
</table>
I have a ViewModel with a parameter List. In the View, the user should be able to add or remove from that list such that the added or removed users are reflected in the POST for that parameter. In JQuery, after clicking an "Add" button, an ajax call returns a UserModel variable, but a simple .append doesn't add to the list.
The other questions I've seen on this issue deal with Partial Views, but this situation updates the table of UserModel without needing a Partial View. It seems like there should be an easy way to do this. Does anyone know how to add the returned UserModel to the List in JQuery so that the List will be returned to the Post with the added models?
<script>
$("#bUser").on('click', function () {
var $addedRecipient = $("#AddedRecipient");
if ($addedRecipient.val() != null && $addedRecipient.val() != "") {
$.ajax({
type: "GET",
url: '#Url.Action("GetFullRecipient", "Message")',
data: { CompanyID: $("#CompanyID").val(), Employee: $addedRecipient.val() },
success: function (data) {
$("#Recipients").append(data);//Not adding to Recipients (Model.List<UserModel>) - is there a simple solution like this?
var bRow = $('<tr></tr>'),
bCell = $('<td style="display:none"></td>').append(data.UserID);
bRow.append(bCell);
bCell = $('<td align="center"></td>').append(data.UserFirstName);
bRow.append(bCell);
bCell = $('<td align="center"></td>').append(data.UserEmail);
bRow.append(bCell);
bCell = $('<td align="center"><input type="button" class="btn btn-info removeRecipient" value="Remove"></td>');
bRow.append(bCell);
$("#bTable tbody").append(bRow);//Works with returned data
$addedRecipient.val("");
},
error: function () {
alert("Recipient could not be added.");
}
});
}
});
</script>
this code worked perfect for me, you just have to go through this list, obviously you have to put the #model directive and a type list Recipient.
#model List<...Models.Recipient>
<input type="button" id="btnAdd" class="btn btn-primary" value="Add"
onclick="myfunction()"/>
<script>
function myfunction() {
$.ajax({
type: 'GET',
contentType:"application/json; charset=utf-8",
url: '#Url.Action("GetFullRecipient","Message")',
data: { CompanyID: $("#CompanyID").val(), Employee:
$addedRecipient.val()},
success: function (response) {
$("#containerData").html(response);
},
error: function (result) {
alert(result);
}
});
}
</script>
<div id="containerData">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Desc_Prod</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>#item.UserID</td>
<td>#item.UserFirstName</td>
<td>#item.UserEmail</td>
<td><a class="btn btn-danger" href="#Url.Action("DeleteRow","Message", new {item.UserID})">Delete</a></td>
</tr>
}
}
</tbody>
</table>
</div>
The answer here followed the link in freedomn-m's comment. Iterate through the Razor table using a for loop, then use a HiddenFor with the model parameter's ID and a CheckBoxFor as the model parameter's selecting field, and have a submit button with a unique name and value. When a button input is clicked and the value fits a given string, loop through the model and add a user that's not there or subtract a user that is there and return to the View.
<div class="row">
<div class="col-lg-12">
<table class="table table-bordered" id="bTable">
<thead>
<tr>
<th style="display:none"></th>
<th style="display:none"></th>
<th class="text-center">Recipient</th>
<th class="text-center">E-mail</th>
<th class="text-center">Select</th>
</tr>
</thead>
<tbody>
#if (Model.Recipients.Any())
{
for (var i = 0; i < Model.Recipients.Count; i++)
{
<tr>
<td style="display:none">#Html.HiddenFor(m => m.Recipients[i].RecipientUserID)</td>
<td style="display:none">#Html.HiddenFor(m => m.Recipients[i].RecipientCorporateID)</td>
<td align="center">#Model.Recipients[i].RecipientName</td>
<td align="center">#Model.Recipients[i].RecipientEmail</td>
<td align="center">#Html.CheckBoxFor(m => m.Recipients[i].RemoveRecipient)</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
I am rendering datawith thymeleaf attribute. But i am implementing "Search" button now, and want to do it without reload.
I have attribute depatments which render List<Department> from db
I know, how to do it via ajax, but then i need to replace attribute with RestController, who will give me JSON.
Is it posible to fetch data from attribute without reloading page? Ajax, or js, or something else?
Thanks
Yes, you can achieve this by using fragment and ajax. In your controller
#GetMapping("/url")
public ModelAndView getResultBySearchKey()
{
List<depatments> areaList= new ArrayList<>();//results from db
ModelAndView mv= new ModelAndView("search::search_list");
mv.addObject("searchList",areaList);
return mv;
}
and in your search.html add bellow code. And don't forget to use inline javascript.
function loadSearchResult()
{
$.ajax({
type: 'get',
url: /*[[ #{'/url'} ]]*/,
success: function(data){
/*<![CDATA[*/
$('.search_list').html(data);
/*]]>*/
},
})
}
<button class="btn btn-primary btn-sm"
th:onclick="'loadSearchResult();'">Search</button>
<div class="row">
<div class="col-md-12 search_list">
<div class="table-responsive" th:fragment="search_list">
<table
class="table table-bordered ">
<thead>
<tr>
<th>SL No.</th>
<th>Actions</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<!-- your desired rows-->
</tbody>
I am newbie to ajax jquery and trying to understand the code and trying to implement it. I would let you know what exactly i want to do and what i am doing.
I have a search box where i input the "sku" and i get the tables and the information of that particular sku.
I have this in my routes.php
Route::get('bestsellers', array('as'=>'bestsellers', 'uses' =>'SalesFlatOrderItemsController#index'));
In my controllers i have
class SalesFlatOrderItemsController extends \BaseController {
$sku_query = Input::get('sku');
if($sku_query){
$orders = SalesFlatOrder::join('sales_flat_order_item as i','sales_flat_order.entity_id','=','i.order_id')
->select((array(DB::Raw('DATE(i.created_at) as days'), DB::Raw('sum(i.qty_ordered) AS qty_ordered'), DB::Raw('sum(i.row_total) AS row_total'),'i.item_id', 'i.name','i.sku')))
->where('i.sku','=',$sku_query)
->groupBy('i.sku')
->orderBy('qty_ordered','Desc')
->paginate(10);
}
return View::make('sales_flat_order_items.bestsellers')->with('orders', $orders);
}
And In bestsellers.blade.php , i have
<input type="text" id="sku" placeholder="Search the sku..." name="sku">
<input type="hidden" id="search_sku" name="search_sku" value="">
<button type="button" id="searchSubmit" class="btn btn-info">Search</button><div class="spin-area" id="spin-area">
<thead>
<tr class="odd gradeX">
<th>Sku</th>
<th>Product Name</th>
<th>Items Ordered</th>
<th>Total</th>
</thead>
#foreach ($orders as $item )
<tr class="odd gradeX">
<td>{{ $item->sku }}</td>
<td>{{ $item->name }}</td>
<td>{{ round( $item->qty_ordered,2) }}</td>
<td>{{ round( $item->row_total,2) }}</td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
</div>
This is for the input sku should be entered and ajax should help to get the information of sku on the same page. So ajax is as below
<script>
$(document).ready(function(){
$('#searchSubmit').on('click',function(){
var data ="sku="+$('#sku').val();
$.ajax({
type:"GET",
data:data,
url:"/bestsellers",
dataType:"JSON",
success:function(data){
alert('success');
}
})
});
});
</script>
Can somebody let me know what is going wrong with my code, Before this i have used traditional way of post and get request, it works, but not ajax call.
Please help.
Thanks.
try this
$(document).on('click','#searchSubmit',function(){
var data ="sku="+$('#sku').val();
$.ajax({
type:"GET",
data:data,
url:"{{URL::to('/bestsellers')}}",
dataType:"JSON",
success:function(data){
alert('success');
// data variable will have the data returned by the server. use it to show the response
}
})
});