How to pass JavaScript array to Django views - javascript

Background: I am trying to build a small web application, where I need to show data based on checkboxes checked by the user. I am very new to coding and somehow decided to start with Django. I did the following:
I used HTML form for checkbox that does nothing on submit
JavaScript for checkbox validation and to collect user input in an array.
I want to pass this array variable to Django views.py so I can try to filter the data and then display to the user and I am stuck. I tried Jquery (see result_output function) but I am not able to make it work.
Below are the codes.
Any help will be highly appreciated.
JavaScript:
function nextPrev(n)
{
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
//exit the function if any checkbox is not checked
if(n==1 && !validateFrom(currentTab)) return false;
//console.log(all_filter_value[0])
//console.log(all_filter_value[1])
// Hide the current tab:
x[currentTab].style.display = "none";
document.getElementsByClassName("step")[currentTab].className += " finish";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
document.getElementById("questbox").style.display="none";
result_output();
return false;
}
all_filter_value = [];
function validateFrom(p)
{
var check = 0;
var Q = document.getElementsByClassName("tab");
console.log(Q.length)
var C = Q[p].getElementsByTagName("input");
console.log(C.length);
filter_var = [];
for(i=0; i < C.length; i++)
{
if(C[i].checked==true)
{
var picked_value= C[i].value
check=check+1;
filter_var.push(picked_value);
}
}
console.log(check)
//console.log(filter_var)
console.log(all_filter_value)
if(check==0)
return false
else
document.getElementsByClassName("step")[p].className += " finish";
all_filter_value.push(filter_var);
return true
}
function result_output()
{
document.getElementsByClassName("result_window")[0].style.display="block";
$(document).ready(function () {
var URL = "{% url 'homepage' %}";
var data = {'all_filter_value': all_filter_value};
$.post(URL, data, function(response){
if(response === 'success'){ alert('Yay!'); }
else{ alert('Error! :('); }
});
});
}
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import moviedb
import pandas as pd
def homepage(request):
movies = moviedb.objects.all().values()
df = pd.DataFrame(movies)
mydict = {
"df": df
}
if request.method == 'POST':
if 'all_filter_value' in request.POST:
all_filter_value = request.POST['all_filter_value']
return HttpResponse('success')
return render(request=request,
template_name="movierec/home.html",
context=mydict)

Related

Asp.Net Core MVC don't load view

I am working on a web application with ASP.NET core and I have encountered some issues.
I'm redirecting my application when I get to a controller, to another controller that opens a page. However, when I get to the controller that returns the view that should be opened, nothing happens and the page doesn't load. The request arrives at the controller which returns the view but the page does not open. The curious thing is that when creating a menu option for the page, everything works normally and the page is loaded.
The first controller is called by Ajax code, receives the information and then calls the other controller to open the other view. Could Ajax code be causing this problem?
Ajax Code
<script>
var listaDeIds = [];
function Mostrar() {
var videos = document.querySelectorAll('#video');
var count = 0;
var lista = [];
for (var i = 0; i < videos.length; i++) {
var videoID = videos.item(i).getAttribute("name");
const shadow = videos.item(i).shadowRoot;
const childNodes = Array.from(shadow.childNodes);
childNodes.forEach(childNode => {
if (childNode.nodeName === "DIV") {
const shadowChilds = Array.from(childNode.childNodes);
shadowChilds.forEach(shadowShild => {
if (shadowShild.nodeName === "DIV") {
const shadowChildsInternas = Array.from(shadowShild.childNodes);
shadowChildsInternas.forEach(interna => {
if (interna.nodeName === "INPUT") {
if (interna.checked === true) {
lista[count] = videoID;
count = count + 1;
}
}
});
}
});
}
});
}
if (lista.length > 0) {
document.getElementById("btnplaylist").style.display = 'block';
} else {
document.getElementById("btnplaylist").style.display = 'none';
}
listaDeIds = lista;
}
$('#Playlist').click(function () {
//var url = "/Playlist/RecebeListaDeIds";
var url = "/VideoSearch/PegarListaDeIds"
var lista = listaDeIds;
$.post(url, { pListaDeIds: lista }, function (data) {
$("#msg").html(data);
});
});
</script>
Controller 1 that receives data from the screen and calls the other controller
[HttpPost]
public ActionResult PegarListaDeIds(string[] pListaDeIds)
{
if(AppUser.User != null)
{
var appCache = AppCache.Instance;
appCache.VideoId.InserirNoCache(pListaDeIds);
return RedirectToAction("CreatePlaylist", "Playlist");
}
else
{
return BadRequest("Usuário não está logado");
}
}
Controller 2 which is called by controller 1. This controller when called by another controller does not load the View.
[HttpGet]
public ActionResult CreatePlaylist()
{
return View();
}
Problem solved. I added this snippet to my Ajax code and now everything works fine.
var url = '#Url.Action("CreatePlaylist", "Playlist")';
window.location.href = url.replace();

How to persist data inside div that appended on button click in JSP using JavaScript, Spring Boot?

I have a dropdown list of cities and a button to add city into vendor model. So I want to add selected city name inside div when button clicked each time. For example, I have list of cities in dropdown and suppose I selected Bangalore and when clicked on add button then it should get added inside div and when I refresh the page, div list should be persistence. Which means, when page get reload or refreshed then added city should be displayed inside a div. Currently what I am suffering from is when I reload page then the cities I added after button clicked, gets emptied each time. So I want help regarding this. Any suggestions would be helpful for me.
Below is my api controller code to save selected city into database:
#RequestMapping(value = AkApiUrl.setdeliverycity, method = { RequestMethod.POST, RequestMethod.GET }, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> setdeliverycity(HttpServletRequest request, HttpSession session, #RequestParam("delivercityid") String delivercityid,
#RequestParam("vendorid") String vendorid) {
CustomResponse = ResponseFactory.getResponse(request);
try {
User loginuser = (User) session.getAttribute("user");
Long vid = Long.parseLong(vendorid);
User vendor = userDao.findByUserid(vid);
String vendorname = vendor.getName();
Long cid = Long.parseLong(delivercityid);
DeliveryCity city = deliverycityDao.findByDelivercityid(cid);
VendorCity vendorCity = new VendorCity();
vendorCity.setVendorcity(city);
vendorCity.setName(vendorname);
vendorCity.setVendorid(vendor);
vendorCity.setCreatedby(loginuser);
VendorCity delivercity = vendorcitydao.save(vendorCity);
if (delivercity != null) {
CustomResponse.setResponse(delivercity);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
CustomResponse.setResponseMessage(CustomStatus.SuccessMsg);
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse(null);
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
CustomResponse.setResponseMessage(CustomStatus.ErrorMsg);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
Below is script for button click to add cities into div when Ajax success:
function addcity(){
var vendorid = document.getElementById('vendordeliveryid').value;
var delivercityid = document.getElementById('vendorcitydd').value;
var url = "../api/setdeliverycity";
$.post(url,{
delivercityid : delivercityid,
vendorid : vendorid,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
debugger
console.log(data.response);
var vendor = data.response;
var vid = vendor.vendorcityid;
var city = vendor.vendorcity.city;
var citydiv = "";
var cityid = vendor.vendorcity.delivercityid;
var citylistlength = city.length;
if(citylistlength > 0) {
citydiv = citydiv+"<div>"+city+" <i class=\"fa fa-times\" onclick=\"removecity('"+cityid+"')\"></i></div>";
}else{
citydiv = citydiv+"<div style=\"text-align: center; float: left; margin-left: 40%; font-size: medium; font-weight: bolder; background: blanchedalmond;\"><span>Choose city from list</span></div>";
}
$('#citydivid').append(citydiv);
$('#cid').val(cityid);
$('#vendorcityid').val(vid);
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
You can check on page load if there is any data inside your localStorage or not .If yes you can get that datas and call your ajax to execute further codes and inside this ajax call if data are successfully appended inside your DOM your can clear previous data and save new data i.e : vendorid..etc inside localStorage.
Here , is sample code which should work :
$(function() {
//check if the localStorage is not null
if (localStorage.getItem("delivercityid") != null) {
var delivercityid = localStorage.getItem("delivercityid"); //get that value
var vendorid = localStorage.getItem("vendorid");
ajax_call(vendorid, delivercityid); //call function
localStorage.clear(); //clear from here after page load..
}
});
function addcity() {
var vendorid = document.getElementById('vendordeliveryid').value;
var delivercityid = document.getElementById('vendorcitydd').value;
ajax_call(vendorid, delivercityid)
}
function ajax_call(vendorid, delivercityid) {
var url = "../api/setdeliverycity";
$.post(url, {
delivercityid: delivercityid,
vendorid: vendorid,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
debugger
console.log(data.response);
var vendor = data.response;
//..
//other codes..
localStorage.setItem("vendorid", vendorid);
var delivercityid_datas = JSON.parse(localStorage.getItem("delivercityid")) || []; //all datas
delivercityid_datas.push(delivercityid); //push new data inside localstorage
localStorage.setItem("delivercityid", JSON.stringify(delivercityid_datas)); //reinitalze again
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}

How can I redirect to an action in .Net Core after making an Ajax call?

I have a script that makes an ajax call to an action in the controller and save some records.
The whole process is working fine but my little issue is to redirect to another page after saving records successfully.
With my code below, the records were added successfully with an alert indicating as it is described in the code "msg + "Courses were Registered"". Rather than doing that I want it to redirect to an action.
Javascript code:
<input type="submit" value="Register Courses" id="register" class="btn btn-rose" />
<script>
$(document).ready(function () {
$("#register").click(function () {
var items = [];
$('input:checkbox.checkBox').each(function () {
if ($(this).prop('checked')) {
var item = {};
item.CourseID = $(this).val();
item.CourseCode = $(this).parent().next().html();
item.CourseName = $(this).parent().next().next().html();
item.Units = $(this).parent().next().next().next().html();
items.push(item);
}
});
var options = {};
options.url = "/Course/SaveCourse";
options.type = "POST";
options.dataType = "json";
options.data = JSON.stringify(items);
options.contentType = "application/json; charset=utf-8;";
options.success = function (msg) {
alert(msg + " Courses were Registered");
};
options.error = function () {
alert("Error while Registering Courses");
};
$.ajax(options);
});
});
</script>
Controller
[HttpPost]
public IActionResult SaveCourse([FromBody]List<CourseRegModel> courseIDs)
{
var user = HttpContext.Session.GetString("currentUser");
if (user == null)
{
return RedirectToAction("Login", "Account");
}
ViewBag.student = user;
var pendingPayment = (from row in _context.BursaryTransactions where row.MatricNo == user && row.ResponseCode == "021" select row).Count();
if (pendingPayment > 0)
{
return RedirectToAction("PaymentSummary", "Student");
}
var student = _context.StStudentInfo.Include(m =>m.AdmInstProgramme.AdmInstDepartment).Include(m =>m.AdmInstClassLevels).FirstOrDefault(m => m.MatricNo == user);
var session = _context.AdmInstProgrammeTypeSession.Include(m => m.AdmInstSemesters).Include(m => m.AdmInstSessions).Include(m => m.AdmInstProgramType).Where(m => m.IsActive == true).FirstOrDefault(m => m.ProgramTypeId == student.ProgrammeTypeId);
foreach (CourseRegModel courseID in courseIDs)
{
courseID.Level = student.AdmInstClassLevels.ClassLevel;
courseID.Semester = session.AdmInstSemesters.Semester;
courseID.Session = session.AdmInstSessions.SessionName;
courseID.Department = student.AdmInstProgramme.AdmInstDepartment.Department;
_context.CourseRegModel.Add(courseID);
}
int courses = _context.SaveChanges();
return Json(courses);
}
Objective is to return RedirectToAction("MyCourses","Courses"); after SaveChanges();
If you want to redirect to another action method why would you use AJAX? But I think you can work around that by performing the redirect in the client side AJAX after it is successfully receive a response you use JavaScript to do the redirect
You can simply redirect your page inside ajax's success handler,
options.success = function (msg) {
window.localtion.href = "/Courses/MyCourses";
// or window.location.href = '#url.Action("MyCourses","Courses")';
};

Database not storing JSON variable

I have an django app in which I am trying to store the gridster widget configuration in the form of JSON variable to database.But when I click"Update" button on my webpage my database does not stores any value.
My JS Code which sends serial value to database
var gridster;
var $color_picker = $('#color_picker');
var URL = "{% url 'save-grid' %}";
gridster = $(".gridster ul").gridster({
widget_base_dimensions: [80, 80],
widget_margins: [5, 5],
helper: 'clone',
resize: {
enabled: true
}
}).data('gridster');
$(".add-button").on("click", function() {
$('#test').click();
$('#test').on('change', function(e) {
var test = document.getElementById('test');
if (!test) {
alert("Um, couldn't find the fileinput element.");
}
else if (!test.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!test.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = test.files[0];
console.log(file);
fr = new FileReader();
fr.readAsDataURL(file);
fr.onload = function() {
var data = fr.result; // data <-- in this var you have the file data in Base64 format
callbackAddButton(data);
test.value = '';
$('#test').replaceWith($('#test').clone())
};
}
})
});
function callbackAddButton(file) {
// get selected color value
var color = $color_picker.val();
// build the widget, including a class for the selected color value
var $widget = $('<li>', {
'class': 'color_' + color
})
.append($('<button>', {
'class': 'delete-button',
'text':'-'
}))
.append($(`<img src="${file}" height="60px" width="60px">`));
// add widget to the grid
gridster.add_widget($widget, 1, 1);
}
$('.js-seralize-update').on('click', function () {
var s = gridster.serialize();
updated_grid=JSON.stringify(s);
$('#log').val(updated_grid);
function updategridster(){
var data = updated_grid;
$.post(URL, data, function(response){
if(response === 'success'){ alert('Yay!'); }
else{ alert('Error! :('); }
});
}
});
$('.gridster').on("click", ".delete-button", function() {
gridster.remove_widget($(this).parent());
});
var serialization = updated_grid
serialization = Gridster.sort_by_row_and_col_asc(serialization);
$('.js-seralize-restore').on('click', function () {
gridster.remove_all_widgets();
$.each(serialization, function () {
gridster.add_widget('<li />', this.size_x, this.size_y, this.col, this.row);
});
});
My urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'myapp/save-grid$', views.save_grid, name='save-grid'),
]
My views.py
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.shortcuts import render, redirect
from django.utils import timezone
from django.utils.encoding import smart_str
from django.http import HttpResponse
from os import path
from .models import update_grid
def save_grid(request):
if request.method == 'POST':
data = json.loads(request.body)
grid = update_grid(data=data)
grid.save()
return HttpResponse('success') # if everything is OK
My Models.py
from django.db import models
from django.utils import timezone
from jsonfield import JSONField
class update_grid(models.Model):
title = models.CharField(max_length=255, blank=True)
data = JSONField()
def __str__(self):
return self.title
I am able to add JSON variable through admin.But nof able to get where I am making mistake
I am just not sure about my javascript part.Whether I have written passing of variable to django syntactically correct
Fiddle
Edit 1
My JS Script is updated as follows
var URL = "{% url 'save-grid' %}";
$('.js-seralize-update').on('click', function () {
var s = gridster.serialize();
updated_grid=JSON.stringify(s);
$('#log').val(updated_grid);
function updategridster(updated_grid){
var data = updated_grid;
$.post(URL, data, function(response){
if(response === 'success'){ alert('Yay!'); }
else{ alert('Error! :('); }
});
}
updategridster(updated_grid);
});
Now I get this error
POST http://localhost:8000/calendar_grid/save-grid net::ERR_CONNECTION_ABORTED jquery.min.js:2
I think the problem is how you are reading the data in Django since request.body returns a byte string
Try replacing this javascript line
var data = updated_grid;
with
var data = {json: updated_grid}
Then in your django view access it via request.POST like this
def save_grid(request):
if request.method == 'POST':
json_data = request.POST.get('json')
print(json_data) # Can add a print here for testing
data = json.loads(json_data)
grid = update_grid.objects.create(data=data, title='title')
return HttpResponse('success') # if everything is OK
Also if you have errors with the csrf_token this is helpful https://docs.djangoproject.com/en/2.0/ref/csrf/#ajax

Not able to send form parameters to the server

We are getting a issue wherein while submitting a form via javascript one of the parameters (invoiceCodes) is not sent to the server. Below is the snippet of the javascript code.
The flow is as follows. When user clicks on "Print" button validateTransition() method is called in which we make a ajax call. After response of that ajax we call couponPopup(url, invoiceCodes). In this function we submit newWinForm but sometimes invoiceCodes parameter is sent empty.
Also checkForInvoiceCode is true in this case which require user to input invoice codes
Is there anything wrong in the manner in which we are putting values in the form which may lead to invoiceCodes being not sent sometimes.
function couponPopup(url, invoiceCodes)
{
var selectedOrders = '';
$(".selectedOrder:checked").each(function() {
selectedOrders += $(this).val() + ',';
});
var frm = document.forms["newWinForm"];
frm.action = url;
frm.selectedShipments.value= selectedOrders;
frm.invoiceCodes.value = invoiceCodes;
console.log("Selected orders are "+selectedOrders);
console.log("Invoice codes with them in order are "+invoiceCodes);
document.getElementById("hiddenInvoiceCodes").value=invoiceCodes;
document.getElementById("hiddenselectedShipments").value=selectedOrders;
frm.submit();
return false;
}
function validateTransition() {
$('#statusChangeSuccess').hide();
$('#statusChangeFail').hide();
var selectedOrders = '';
var invoiceCodes = '';
var flag = 0;
var spaceError = 0;
var commaError = 0;
$(".selectedOrder:checked").each(function() {
selectedOrders += $(this).val() + ',';
<c:if test="${checkForInvoiceCode}">
var emptyPattern = /^\s*$/;
var commaPattern = /,/;
var inv_code = $("#invoice-code-" + $(this).val()).val().trim();
if (emptyPattern.test(inv_code)) {
spaceError = 1;
flag = 1;
}
if (commaPattern.test(inv_code)) {
commaError = 1;
flag = 1;
}
invoiceCodes += inv_code + ",";
</c:if>
});
if(selectedOrders=='') {
alert('Please select at least one order');
return false;
}
if ( flag ) {
if ( commaError ) {
alert('One or more specified codes have comma, please remove comma from them');
}
if ( spaceError ) {
alert('One or more specified codes has been left blank, please fill them up');
}
if ( !commaError && !spaceError ) {
alert('Please contact tech');
}
return false;
}
var inputdata = {"selectedShipments" : selectedOrders,
"statusCode" : "PRINT"
};
//this is where we are making an ajax call
jQuery(function($){
setTimeout(function(){
var ajaxUrl = '/product/update/';
$.ajax({url:ajaxUrl, type: "POST", dataType: 'json', data:inputdata , success: function(data) {
if(data['status'] == 'success') {
//couponPopup function is called where form is submitted
couponPopup("${path.http}/product/print/", invoiceCodes);
$('#statusChangeSuccess').html(data['message']).show();
$(".selectedOrder:checked").each(function() {
$("#row-" + $(this).val()).remove();
});
} else{
$('#statusChangeFail').html(data['message']).show();
}
}});
}, 10 );
});
return false;
}
<form id="newWinForm" name="newWinForm" action="" method="post" target="_blank" >
<input type="hidden" id="hiddenselectedShipments" name="selectedShipments" value="" />
<input type="hidden" id="hiddenInvoiceCodes" name="invoiceCodes" value="" />
</form>
Controller for the form. Invoice codes is sometimes empty even when we are sending it from client side.
#RequestMapping("/product/print")
public void printSelectedPendingOrders(#RequestParam("selectedShipments") String selectedShipments,
#RequestParam(defaultValue = "", value = "invoiceCodes", required = false) String invoiceCodes, ModelMap modelMap, HttpServletResponse httpResponse)
throws IOException, DocumentException, ParserConfigurationException, SAXException {

Categories