This question already exists:
Problem with the form return empty data in Flask [duplicate]
Closed 1 year ago.
I am building an application in Flask and JavaScript and I have a problem with the Ajax in Flask. How can I handle it in Flask i mean using if. I use if request.method=='POST' but I have the form too and when I try if 'form-submit' in request.form and print nazwa_event = request.form.get('nameOfEvent') this return me nothing I mean it is empty.
Code JavaScript:
$("#search-button_event").click(function () { // make ajax request on btn click
$.ajax({
type: "POST",
url: "/mapaa", // url to the function
data: {
nameevent: $("#name_of_event").val(), // value of the form
},
success: function (response) {
id = (response['id']);
nazwa = (response['name']);
droga = (response['route']);
droga_without = droga.replaceAll("{","")
droga_with2 = droga_without.replaceAll("}","")
var string = droga_with2.split(',');
let marker_event = L.marker(array[0]).bindPopup()
marker_event._popup.setContent(
'<form method="POST" action="/mapaa"'+
'<p>Nazwa: '+nazwa+'</p>'+
'<input name="nameOfEvent" type="hidden" value="" id="idname">'+
'<button type="submit" id="form-submit" name="form-submit" class="btn btn-warning btn-block">Dołącz do wydarzenia</button>'+
'</form>')
marker_event.addTo(mymap)
polyline_event = L.polyline(array,{color: 'red'})
marker_event.on('click',function(){
polyline_event.addTo(mymap)
})
marker_event.getPopup().on('remove', function() {
polyline_event.remove()
})
$('input[id=idname]').val(nazwa.value);
mymap.setView(array[0],14)
},
});
});
Code in Flask:
#app.route('/mapaa',methods=['GET','POST'])
def mapa():
user_id = current_user.get_id()
slownik = {}
if request.method == "POST":
if request.is_json:
req = request.get_json()
nazwa = req['name']
data_pocz = req['data_start']
data_kon = req['data_end']
typ = req['type']
dlugosc = req['len_route']
coord = req['coordinates']
event_database = Event(date_start=data_pocz, date_end=data_kon, type=typ, name=nazwa, len_route=dlugosc,admin=user_id, route=coord)
db.session.add(event_database)
db.session.commit()
print('Dodano wydarzenie')
if 'form-submit' in request.form:
nazwa_event = request.form.get('nameOfEvent')
print("Name:",nazwa_event)
else:
name_ev = request.form.get('nameevent')
all_data = Event.query.filter_by(name=name_ev).all()
for row in all_data:
date_st_string = str(row.date_start)
date_end_string = str(row.date_end)
slownik = {'id':row.id,'date_st':date_st_string,'date_end':date_end_string,'type':row.type,'name':row.name,'len_route':row.len_route,'route':row.route}
return jsonify(slownik)
return render_template('mapaa.html', title='Mapa')
It is problem with the form or name of something ?
Related
How do I pass a django model to javascript?
Specifically, I want to pass a django Movie model to javascript.
In javascript, I would like to display the id something in the movie model at the time of score with an if statement.
def index(request):
if Movie.objects.order_by('-stars').exists():
movie = list(Movie.objects.order_by('-stars'))
if TV.objects.order_by('-stars').exists():
tv = TV.objects.order_by('-stars')
print(tv)
context = {
'movie':movie,
}
return render(request, 'Movie/index.html',context)
fetchTrendingResults("all", "week")
var mediaType = document.getElementById("media_type")
mediaType.addEventListener("change", function(event) {
fetchTrendingResults(mediaType.options[mediaType.selectedIndex].value, "day")
})
function fetchTrendingResults(media_type, time_window) {
var trendingDiv = document.getElementById("trendings")
trendingDiv.innerHTML = ""
if (media_type == "score"){
var js_list = {{movie}};
}
else{
fetch(`/api/trendings?media_type=${media_type}&time_window=${time_window}`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}}
// todo:movieとTVのIDをもらってこれをURLにFethして映画とTVの情報をそれぞれでスターが高い順に表示する。
)
.then(res => res.json())
.then(data => {
for (let i=0; i<data.results.length; i++) {
var mainDiv = document.createElement("div");
mainDiv.setAttribute("class", "card");
mainDiv.setAttribute("style", "width: 18rem;");
var img = document.createElement("img");
img.setAttribute("src", "https://image.tmdb.org/t/p/w200" + data.results[i].poster_path);
img.setAttribute("class", "card-img-top");
img.setAttribute("alt", "...");
var body = document.createElement("div");
body.setAttribute("class", "card-body");
var title = document.createElement("h5");
title.setAttribute("class", "card-title");
if (data.results[i].name) {
title.innerHTML = data.results[i].name;
} else {
title.innerHTML = data.results[i].title;
}
//var text = document.createElement("p");
//text.setAttribute("class", "card-text");
//text.innerHTML = data.results[i].overview;
var link = document.createElement("a");
link.setAttribute("href", "/" + data.results[i].media_type + "/" + data.results[i].id + "/");
link.setAttribute("class", "btn btn-primary");
link.innerHTML = "View Details";
body.appendChild(title);
//body.appendChild(text);
body.appendChild(link);
mainDiv.appendChild(img);
mainDiv.appendChild(body);
document.getElementById("trendings").appendChild(mainDiv);
}
})
}
}
How do I pass a django model to javascript?
Specifically, I want to pass a django Movie model to javascript.
In javascript, I would like to display the id something in the movie model at the time of score with an if statement.
You can send model data by just returning JsonResponse from the view (and for example creating JSON dict by forlooping QuerySet, or using model_to_dict Django built-in method) or by preserving your logic and sending html you need to override - even better - you can do both ways at the same time.
So, basically you write view like this:
from django.forms import model_to_dict
from django.http import Http404
def custom_ajax_view(request):
if request.method != 'POST':
raise Http404
movies = Movie.objects.order_by('-stars')
movie_dict = {}
if movies.exists():
movie_dict = {obj.id: model_to_dict(obj) for obj in movies}
tv = TV.objects.order_by('-stars')
tv_dict = {}
if tv.exists():
tv_dict = {obj.id: model_to_dict(obj) for obj in tv}
context = {
'movie': movie,
}
html = render_to_string(
'Movie/index.html', context=context)
return JsonResponse({
'movies': movie_dict,
'tvs': tv_dict,
'html': html,
})
And then you retrieve data via Ajax method (I prefer using jQuery for that) by writing:
$.ajax({
url: CUSTOM_AJAX_URL,
type: 'post',
dataType: 'json',
success: function (data) {
// Here you retrieve your data and you can do something with it.
console.log(data)
}
});
You also can resolve your CUSTOM_AJAX_URL using template logic (post it at the end of template)
<script>
const CUSTOM_AJAX_URL = "{% url 'custom_ajax_view' %}";
</script>
<script src="{% static 'your_script_name.js' %}"></script>
Then your script should see the CUSTOM_AJAX_URL (if you use script not directly by using inline method, but including script via script tag and placing it with static method in the code). If you place it directly, you can pass URL directly to the AJAX method.
I use in my study project django rest framework.I get an error 403 Forbidden (CSRF token missing or incorrect, when I try to save using the POST method. Here is my code html
<form id = "product_form" method = "post">
{% csrf_token %}
<input type = "hidden" name = "id" id = "id">
<p>Назвние:<input name = "name" id = "name"></p>
<p><input type = "reset" value = "Oчистить"></p>
<input type = "submit" value = "Сохранить">
</form>
Here is my code js:
let productUpdater = new XMLHttpRequest();
productUpdater.addEventListener('readystatechange', () => {
if (productUpdater.readyState == 4) {
if ((productUpdater.status == 200) || (productUpdater.status == 201)) {
listLoad();
name.form.reset();
id.value = '';
} else {
window.alert(productUpdater.statusText)
}
}
}
);
name.form.addEventListener('submit', (evt) => {
evt.preventDefault();
// let vid = id.value, url, method;
let vid = id.value;
if (vid) {
url = 'http://127.0.0.1:8000/books/api_category/' + vid + '/';
method = 'PUT';
} else {
url = 'http://127.0.0.1:8000/books/api_category/';
method = 'POST';
}
let data = JSON.stringify({id: vid,nameCategory: name.value});
productUpdater.open(method, url, true);
productUpdater.setRequestHeader('Content-Type', 'application/json');
productUpdater.send(data);
})
Here is my views.py:
#api_view(['GET', 'POST'])
def api_products(request):
if request.method == 'GET':
productsAll = CategoryMaskarad.objects.all()
serializer = CategorySerializer(productsAll, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CategorySerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#api_view(['GET', 'PUT', 'PATCH', 'DELETE'])
def api_rubric_detail(request, pk):
product = CategoryMaskarad.objects.get(pk=pk)
if request.method == 'GET':
serializer = CategorySerializer(product)
return Response(serializer.data)
elif request.method == 'PUT' or request.method == 'PATCH':
serializer = CategorySerializer(product, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
product.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
Here is my urls.py:
path('api_category/<int:pk>/', api_rubric_detail),
path('api_products/', api_products),
path('api/drf-auth/', include('rest_framework.urls'))
I added the last path and logged in. In the api interface it became possible to add to the api using the post method, but with the help of js in my html I cant add data.Help me, please
I have this option. He is work.I added to js file:
name.form.addEventListener('submit', (evt) => {
evt.preventDefault();
// let vid = id.value, url, method;
let vid = id.value, url, method;
if (vid) {
url = 'http://127.0.0.1:8000/books/api_category/' + vid + '/';
method = 'PUT';
} else {
url = 'http://127.0.0.1:8000/books/api_category/';
method = 'POST';
}
let data = JSON.stringify({id: vid, nameCategory: name.value});
productUpdater.open(method, url, true);
productUpdater.setRequestHeader('Content-Type', 'application/json');
productUpdater.setRequestHeader('X-CSRFToken', csrftoken);
productUpdater.send(data);
})
and I added to html file:
<script>
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
</script>
when passing data in form to a django rest framework, you do not add the csrf_token tag before forms, rather you pass it as a header when sending api post on your endpoint.
Add this line after
try adding this function into your codes to get the values of csrftoken
let getCookie = (name)=>{
var cookieValue = null;
if(document.cookie && document.cookie !== ''){
var cookies = document.cookie.split(";");
for(var i=0; i<cookies.length; i++){
var cookie = cookies[i].trim();
if(cookie.substring(0, name.length+1)===(name+'=')){
cookieValue = decodeURIComponent(cookie.substring(name.length+1));
break;
}
}
}
return cookieValue;
}
and then change the value you use in x-csrf-token and make it
productUpdater.setRequestHeader('Content-Type', 'application/json');
productUpdater.setRequestHeader('X-CSRF-Token', getCookie("csrftoken"));
My 'Clear' and 'Refresh' buttons do not clear out my Branch and Terminal inputs on my webpage. I think it has something to do with my KnockoutJS since I bind the data to a table in the DB. Perhaps the KnockoutJS thing isn't functioning properly. The page is supposed to display the fetched data from the DB everytime 'Refresh' button is clicked too. But it seems like the code doesn't even fetch anything from the DB.
I'm new to learning the framework of asp.net so can anyone pls help me w my issue? T
I tried to look at other API functions and only tweaked a little parameters to fetch from the DB since there are different tables I need to fetch from. I also modified the Stored Procedure of the respective page for the API function to grab the data from SQL Server but still the page appears blank and the buttons aren't working.
buttons html
<div class="col-sm-5 col-md-5 col-lg-5 m-b-15">
<button id="btnRefreshForecastDetails" type="button" class="btn btn-primary btn-custom w-md waves-effect waves-light" data-bind="click: refresh"><i class="mdi mdi-refresh"></i> <span>Refresh</span></button>
<button id="btnClearAll" type="button" class="btn btn-primary btn-custom w-md waves-effect waves-light" onclick="ClearAll();"><i class="mdi mdi-close"></i> <span>Clear All</span></button>
</div>
.JS function
var ObservableModelMain = function () {
var self = this;
self.gifts = ko.observableArray();
self.refresh = function () {
StartLoadingPage();
url = sessionStorage.getItem('WebApiURL') + "IT_GetDetails?ID=" + sessionStorage.getItem('ID');
var table = $('#main-table');//table from DB
var PageSize = sessionStorage.getItem('PageSize');
var valueToPush = {};
var FinalData = [];
valueToPush.PageNumber = table.getPageNum();
valueToPush.PageSize = PageSize;
valueToPush.SortExpression = table.getSortExpression();
valueToPush.SortOrder = table.getSortOrder();
valueToPush.SearchBranchNo = _strSearchBranchNo;
valueToPush.SearchTerminalNo = _strSearchTerminalNo;
valueToPush.SearchDate = _strSearchDate;
FinalData.push(valueToPush);
valueToPush = {};
var myJSON = JSON.stringify(FinalData)
$.ajax({
url: url,
type: "POST",
data: myJSON,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
DeviceStatus = data["errorCode"];
Param = data["param"];
if (DeviceStatus == 'SUCCESS') {
var obj = JSON.parse(Param);
if (obj[0].length == 0 && obj[1][0].TotalOutput != 0) {
document.getElementById('btnRefreshForecastDetails').click();
}
else {
self.gifts(obj[0]);
}
table.updateTable(parseInt(PageSize), obj[1][0].TotalOutput);
//GetBranchList();
}
else {
swal("Error", "Fail to retrieve forecast details, " + Param, "error");
}
CloseLoadingPage();
}
});
}
};
API function
public async Task<TCR_RESPONSEMESSAGE> IT_GetForecastDetails(ITForecast[] Alldata)
{
StringBuilder sbReturnMessage = new StringBuilder();
StringBuilder sbTraceMessage = new StringBuilder();
API_COMPLETEMESSAGE tcm = null;
WebAPITraceLog wtl = null;
string reqStr = string.Empty;
string repStr = string.Empty;
string MessageSeqNo = string.Empty;
const string functionNameStr = nameof(IT_GetForecastDetails);
API_FUNCTION APIFunctionCode = API_FUNCTION.IT_GetForecastDetails;
StringBuilder sbSQLStmt = new StringBuilder();
bool asyncResult = false;
DataSet dsData = new DataSet();
bool blnResult = false;
string strTable = "tblForecastDetails";
List<SqlParameter> SqlParameters = new List<SqlParameter>();
try
{
using (SqlConnection SQLDBConn = new SqlConnection(sqlTCRSecureBODBConnStr))
{
await SQLDBConn.OpenAsync();
SqlParameters.Add(new SqlParameter("#PageNumber", Alldata[0].PageNumber));
SqlParameters.Add(new SqlParameter("#PageSize", Alldata[0].PageSize));
SqlParameters.Add(new SqlParameter("#SortExpression", Alldata[0].SortExpression));
SqlParameters.Add(new SqlParameter("#SortOrder", Alldata[0].SortOrder));
SqlParameter OutputParam = new SqlParameter("#TotalRecords", SqlDbType.BigInt);
OutputParam.Direction = ParameterDirection.Output;
SqlParameters.Add(OutputParam);
blnResult = ReadDataSetByStoredProcedure("GetForecastDetailsWithPage", SqlParameters, strTable, DEFAULT_LOG_NAME, SQLDBConn, ref dsData);
if (blnResult == false)
{
tcm = FAIL_READ_MESSAGE;
tcm.Param = "Fail to read GetForecastDetailsWithPage.";
goto ExitHandler;
}
DataTable tbl = new DataTable("tblPagerInfo");
tbl.Columns.Add("TotalOutput", typeof(long));
tbl.Rows.Add(Convert.ToInt64(SqlParameters[4].Value));
dsData.Tables.Add(tbl);
}
if (dsData != null)
{
tcm = SUCCESS_MESSAGE;
tcm.Param = JsonConvert.SerializeObject(dsData.Tables);
goto ExitHandler;
}
else
{
tcm = FAIL_READ_MESSAGE;
tcm.Param = "Fail to read GetForecastDetailsWithPage.";
goto ExitHandler;
}
ExitHandler:
tcm.Function = APIFunctionCode;
return await ProcessAPICompleteMessage(tcm, functionNameStr);
}
catch (Exception ex)
{
string errorMessages = string.Empty;
errorMessages += "Description : " + ex.Message;
LogError(DEFAULT_LOG_PATH, DEFAULT_LOG_NAME, errorMessages, GetLineNumber(ex).ToString(), functionNameStr);
tcm = EXCEPTION_MESSAGE;
tcm.Function = APIFunctionCode;
tcm.Param = errorMessages;
return await ProcessAPICompleteMessage(tcm, functionNameStr);
}
}
I expect for the "Refresh" and "Clear" buttons to work, and for the DB data from the declared table to be fetched to be displayed on the web page.
well, for starters I don't see your knockout anywhere being bound to your viewmodel, preferably below your viewmodel definition.
ko.applyBindings(new ObservableModelMain());
and secondly your clear button has a plain old javascript onclick event attribute, not a data-bind to a -also not available- self.clear = function() {...} in your knockout viewmodel
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")';
};
I wan't to pass multiple variable to a laravel controller using ajax that has multiple return value.
JavaScript
$(function(){
var standard = standardRoom();
var n_standard = standard[0];
var xSumStandard = standard[1];
var totalStandard = standard[2];
var quad = quadRoom();
var n_quad = quad[0];
var xSumQuad = quad[1];
var totalQuad = quad[2];
var family = familyRoom();
var n_family = family[0];
var xSumFamily = family[1];
var totalFamily = family[2];
var barkada = barkadaRoom();
var n_barkada = barkada[0];
var xSumBarkada = barkada[1];
var totalBarkada = barkada[2];
$('#formSubmit').on('click', function(){
$.ajax({
url: APP.baseUrl + '/check/next',
data: {'_token': window.Laravel.csrfToken, 'n_standard': n_standard, 'xSumStandard': xSumStandard, 'totalStandard': totalStandard,'n_quad': n_quad,'xSumQuad': xSumQuad,'totalQuad': totalQuad,'n_family': n_family,'xSumFamily': xSumFamily,'totalFamily': totalFamily, 'n_barkada': n_barkada,'xSumBarkada': xSumBarkada,'totalBarkada': totalBarkada},
type: 'POST',
success: function (data) {
console.log('Success')
},
});
});
});
{!! Form::open(['url' => '/request', 'id' => 'formSubmit']) !!}
<input type="submit" id="submitbutton" value="NEXT" style="width:310px;background-color:#5d0b0b">
{!! Form::close() !!}
I tried to follow an instruction on how to access multiple return value here in stack and come up with this. I don't know if this is working or not. But what I need is to just pass all the value that is in the data:
Route
Route::post('check/next', 'Reservation#getRequest');
Now what is the next step in this? How do I get this in the controller? I'm new to laravel and ajax so I'm having a hard time understanding this process
The problem is I'm getting an Undefined index: n_standard
Edit
Controller
public function getRequest(Request $request){
$n_standard = $_GET['n_standard'];
$xSumStandard = $_GET['xSumStandard'];
$totalStandard = $_GET['totalStandard'];
$n_quad = $_GET['n_quad'];
$xSumQuad = $_GET['xSumQuad'];
$totalQuad = $_GET['totalQuad'];
$n_family = $_GET['n_family'];
$xSumFamily = $_GET['xSumFamily'];
$totalFamily = $_GET['totalFamily'];
$n_barkada = $_GET['n_barkada'];
$xSumBarkada = $_GET['xSumBarkada'];
$totalBarkada = $_GET['totalBarkada'];
}
In controller, first of all you should replace $_GET to $_POST / $_REQUEST because your are sending data from ajax through POST.
or
You can also check, you are getting request value or not using below given code.
use Illuminate\Support\Facades\Request;
public function getRequest(Request $request){
$request->all()
}