Userfrosting - Get Working, Post blank screen with no error in log - userfrosting

I'm creating my first Userfrosting app and trying a few simple things but falling at the first hurdle. I am trying to create a form which adds bands to a database table:
CREATE TABLE `uf_band` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`band_name` text NOT NULL,
`band_description` longtext NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`modified_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
initialize.php:
$table_band = new \UserFrosting\DatabaseTable($app->config('db')['db_prefix'] . "band", [
"band_name",
"band_description",
"created_at",
"modified_at"
]);
index.php for the routes:
$app->get('/bands/new/?', function () use ($app) {
$controller = new UF\BandController($app);
return $controller->newBand();
});
The New Band form using GET works fine.
BandController.php
public function newBand(){
if (!$this->_app->user->checkAccess('uri_bands')){
$this->_app->notFound();
}
$this->_app->render('bands/new.twig', []);
}
and if I add this to the newBand Controller to test, it writes to the database when I load the new band form, which is fine:
$new_band = new Band([
"band_name" => "band_name",
"band_description" => "band_description"
]);
$new_band->save();
$id = $new_band->id;
The problem is the Save using Post. Even if I hard code in the values and do not even try to read the POST data, all I get is a blank screen. There are no error messages and nothing in the apache error.log:
index.php
$app->post('/bands/new/?', function () use ($app) {
$controller = new UF\BandController($app);
return $controller->saveBand();
});
BandController.php
public function saveBand(){
$new_band = new Band([
"band_name" => "band_name",
"band_description" => "band_description"
]);
$new_band->save();
$id = $new_band->id;
}
If I replace my POST route with
$app->post('/bands/new/?', function () use ($app) {
echo 'post';
})
I still just get a blank screen.
Here's bands/new.twig though I think the problem is before this:
{% extends "layouts/layout-dashboard.twig" %}
{% set page_group = "dashboard" %}
{% block page %}
{% set page = page | merge({
"title" : "Add New Band",
"description" : ""
}) %}
{{ parent() }}
{% endblock %}
{% block content %}
<h1>{{page.title}}</h1>
<p>{{page.description}}</p>
<div class="row">
<div class="col-lg-6">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-users"></i>Add New Band</h3>
</div>
<div class="panel-body">
<form class="form-horizontal" role="form" name="bands" action="{{site.uri.public}}/bands/new" method="post">
<div class="form-group">
<label for="input_band" class="col-sm-4 control-label">Band Name</label>
<div class="col-sm-8">
<input type="text" id="input_title" class="form-control" name="band_name" placeholder="Please enter the band name">
<!--<p class="help-block">Enter the band name here</p>-->
</div>
</div>
<div class="form-group">
<label for="input_title" class="col-sm-4 control-label">Description</label>
<div class="col-sm-8">
<textarea type="text" id="input_title" class="form-control" name="band_description" placeholder="Please enter a description of the band. This may be displayed publically"></textarea>
<!--<p class="help-block">This will become the new title for all users in the selected group.</p> -->
</div>
</div>
<div class="form-group">
<label for="input_group" class="col-sm-4 control-label">Genre</label>
<div class="col-sm-8">
<select id="input_group" class="form-control select2" name="genre_id">
{% for group in groups %}
<option value="{{group.id}}">{{group.name}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success text-center">Add Band</button>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block page_scripts %}
<script>
$(document).ready(function() {
// Load the validator rules for this form
var validators = {{validators | raw}};
ufFormSubmit(
$("form[name='add_band']"),
validators,
$("#userfrosting-alerts"),
function(data, statusText, jqXHR) {
// Reload the page on success
window.location.reload(true);
}
);
});
</script>
{% endblock %}
Thanks for any thoughts. With no error messages, this is driving me nuts!

Seems like you have forgotten the csrf token.
You can add this hidden input field:
<input type="hidden" name="{{csrf_key}}" value="{{csrf_token}}">
and read more here.

Related

How to stay data on dropdown list after page reloading in laravel 5.7?

I am creating task like dependent dropdown but i want to stay data as it is after reloading of page. I am successful to achieve this task for first dropdown but i am confuse how can i stay data for second dropdown Plz need help. I am putting value in session and check in option value but i am confuse in second option value that how can i check session value in javascript option value.
Blade :
<?php $reason_id=Session::get('reason_id');?>
<div class="row">
<div class="col-lg-4">
<span><label><b>Reason for return</b></label></span>
</div>
<div class="col-lg-8 mt-1">
<div class="form-group">
<select class="form-control" id="reason" name="reason">
<option readonly>Select reason</option>
#foreach($reason as $id => $p_reason)
<option value="{{ $id }}" #if($reason_id==$id) selected="selected"#endif>{{$p_reason}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<span><label><b>Reason Details</b></label></span>
</div>
<div class="col-lg-8 mt-1">
<div class="form-group">
<select class="form-control" id="reason_detail" name="reason_detail">
</select>
</div>
</div>
</div>
javascript:
$(document).ready(function(){
$('#reason').change(function(){
var ID = $(this).val();
if(ID){
$.ajax({
type:"GET",
url:"{{url('get-reason-details')}}?reason_id="+ID,
success:function(res){
if(res){
$("#reason_detail").empty();
$("#reason_detail").append('<option>Select Reason Detail</option>');
$.each(res,function(key,value){
$("#reason_detail").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#reason_detail").empty();
}
}
});
}else{
$("#reason_detail").empty();
}
});
controller:
public function set_session(Request $req)
{
$data=$req->all();
Session::put('reason_id',$data['reason']);
Session::put('reason_detail_id',$data['reason_detail']);
$data=DB::table('product_details')->select('product_details.*')->where('product_id',$data['product_id'])->first();
$reason=DB::table('reason')->pluck('description','reason_id');
return view('returnproduct',['reason'=>$reason],['data'=>$data->product_id]);
}
public function get_reason($id)
{
$data=DB::table('product_details')->select('product_details.*')->where('product_id',$id)->first();
$reason=DB::table('reason')->pluck('description','reason_id');
return view('returnproduct',['reason'=>$reason],['data'=>$data->product_id]);
}
public function get_reason_details(Request $req)
{
$reason_detail_id=Session::get('reason_detail_id');
$reason_details = DB::table("reason_details")
->where("reason_id",$req->reason_id)
->pluck("reason_detail","reason_detail_id");
return response()->json($reason_details);
}

What am I doing wrong with this AJAX in django?

I am trying to implement AJAX in django. I have the following file login.html
This file contains the form and ajax script
{% extends 'services/base_visitor.html' %}
{% block title %}Log In{% endblock %}
{% block login_active %}active{% endblock %}
{% block body %}
<div class="container-fluid" style="position: absolute;top:20%;left:35%;width:30%;">
<div class="panel panel-default">
<h3>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspLog In</h3>
<center>
<div class="panel-body">
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<!-- action="{% url 'login_user'%}" -->
<form class="form-horizontal" role="form" action="{% url 'login_user'%}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<!-- <label class="control-label col-sm-2" for="id_username">
</label> -->
<div class="col-sm-10">
<strong><span class="glyphicon glyphicon-user"></strong>&nbsp&nbsp&nbsp
<input id="id_username" maxlength="30" name="id_username" type="text" placeholder="USERNAME" style="font-family: Courier New;font-size: 15px;border: none; border-bottom: 2px solid black;">
<div id="data"></div></span>
</div>
</div>
<div class="form-group">
<!-- <label class="control-label col-sm-2" for="id_password">
</label> -->
<div class="col-sm-10">
<strong><span class="glyphicon glyphicon-asterisk"></strong>&nbsp&nbsp&nbsp
<input id="id_password" maxlength="30" name="id_password" type="password" placeholder="PASSWORD" style="font-family: Courier New;font-size: 15px; border: none; border-bottom: 2px solid black;"></span>
</div>
</div>
</center>
<div class="form-group">
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
<div class="panel-footer">
Don't have an account? Click here to register.
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
$("#id_username").change(function(){
alert("The text has been changed.");
});
$("#id_username").change(function () {
var username = $("#id_username").val();
console.log(username);
$.ajax({
type:"POST",
url: '/ajax/validate_username/',
data:{
str:username,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
dataType: 'json',
success: function (data) {
// alert("done")
$("#data").html(data);
}
});
});
</script>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
{% endblock %}
Following is my urls.py
look for validate_username
from django.conf.urls import url
from . import views
from django.contrib import admin
from django.urls import path
from services import views as user_views
app_name = 'services'
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('base/', user_views.base, name='base'),
path('login/', user_views.login_user, name='login_user'),
path('index/', user_views.index, name='index'),
path('login/', user_views.logout_user, name='logout_user'),
# path(r'^signup/$', views.SignUpView.as_view(), name='signup'),
url(r'^ajax/validate_username/$', user_views.validate_username, name='validate_username'),
]
Following is my views.py
I check if the user is already present, if yes, then I return Success else I return Not Success.
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout
from .forms import UserForm
from .models import UserProfile, Customer, Seller, User
from django.http import *
def validate_username(request):
if request.method == 'POST':
username = request.POST.get('str',None)
# print(username)
data = {
'is_taken': user.objects.filter(username=username).exists()
}
if data.is_taken:
return HttpResponse("Success!")
else:
return HttpResponse("NOT Success!")
Whenever the user enters any text in username field my ajax request should come in action. However, this intended action is not done. Anyone, please clarify.
I also tried to print alerts using jquery, but it also doesn't seem to be working.
I think the problem is the binding try this:
window.onload = function() {
// add your code change here
$("#id_username").change(function(){
alert("The text has been changed.");
});
$("#id_username").change(function () {
var username = $("#id_username").val();
console.log(username);
});
}
or
$(document).ready= function() {
// add your code change here
$("#id_username").change(function(){
alert("The text has been changed.");
});
$("#id_username").change(function () {
var username = $("#id_username").val();
console.log(username);
});
}

How to work with pagination in Laravel Algolia search

Pagination is not working. It shows empty page on clicking 2 page.It is not fetching the second page from the search query. And also token is not showing on
2nd page url. Is this is the reason then how to add csrf_token to pagination
Route.
I am using algolia to search
Route::get('posts/search','PostController#search')->name('posts.search');
Controller
public function search(Request $request){
if($request->has('q')) {
$request->flashOnly('q');
$results = Post::search($request->q)->paginate(5);
} else {
$results = [];
}
return view('posts.search')->with('results', $results);
}
View
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Search for Posts</h1>
<form action="{{ route('posts.search') }}" method="get">
{{ csrf_field() }}
<div class="input-group">
<input type="text" name="q" class="form-control input-lg" placeholder="Search for a post..." value="{{ old('q') }}"/>
<span class="input-group-btn">
<button class="btn btn-default btn-lg" type="submit">Search</button>
</span>
</div>
</form>
<hr />
#foreach ($results as $post)
<div class="row" style="margin-top: 20px;">
<div class="col-md-8">
<h3>{{ $post->title }}</h3>
</div>
<div class="col-md-4">
#if ($post->published)
<h4><span class="label label-success pull-right">PUBLISHED</span><h4>
#else
<h4><span class="label label-default pull-right">DRAFT</span><h4>
#endif
</div>
</div>
<div class="row">
<div class="col-md-12">
<p>
{{ str_limit($post->content, 250) }}
</p>
</div>
</div>
#endforeach
#if (count($results) > 0)
<hr />
<div class="text-center">
{{ $results->links() }}
</div>
#endif
#endsection
Try this one may be help
// Making sure the user entered a keyword.
if($request->has('q')) {
// Using the Laravel Scout syntax to search the posts table.
$results = Post::search($request->get('q'))->paginate(15);
}
Update my answer sometimes help this
return view('posts.search',['results' => $results]);
Try :
{{$results->appends(request()->query())->links()}}
insted of
{{ $results->links() }}

Laravel 5.5 redirect to url with anchor and with data

In my footer.blade.php i have the following code about subscribing
<!--Subscription-->
#if(Session::has('success'))
<div class="form-group has-success">
<input class="form-control form-control-success" type="text" id="input-success">
<div class="form-control-feedback">{{ Session::get('success') }}</div>
</div>
#elseif(Session::has('failed'))
<div class="form-group has-danger">
<input class="form-control form-control-danger" type="text" id="input-danger">
<div class="form-control-feedback">{{ Session::get('failed') }}</div>
</div>
#else
{!! Form::open(['route'=>'subscribe.store', 'class' => 'subscribe-form', 'novalidate' => 'novalidate']) !!}
<div class="clearfix">
<div class="input-group input-light">
{!! Form::email('email', old('email'), ['class'=>'form-control ', 'placeholder'=>'Your e-mail']) !!}
<span class="input-group-addon"><i class="icon-mail"></i></span>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input type="text" name="b_c7103e2c981361a6639545bd5_1194bb7544" tabindex="-1">
</div>
<button class="btn btn-primary" type="submit">
<i class="icon-check"></i>
</button>
</div>
{!! Form::close() !!}
<span class="form-text text-sm text-white opacity-50">Subscribe to our Newsletter to receive early discount offers, latest news, sales and promo information.</span>
#endif
In my controller i have the following function which receives the email and subscribes it correctly
public function registerNewsletter( Request $request )
{
$email = $request->input( 'email' );
$isSub = Newsletter::hasMember($email);
if($isSub) {
return redirect()->back()->with('failed', 'You have been already registered in our Newsletter system.');
} else {
Newsletter::subscribe($email);
return redirect()->back()->with('success', 'You have been registered in our Newsletter system.');
}
}
Although everything works good, i would like to page to scroll down to the footer because now it reloads and stays on top.
I've found the return redirect()->to(app('url')->previous(). '#hashid');
But there is no way to pass data among the id of the footer.
And also i've tried
return redirect()->back()->with('failed', 'You have been already registered in our Newsletter system.'). '#sitefooter';
and it didn't scroll down.
Any idea or workaround?
I've just tested this code. It will redirect you, scroll down to the anchor and will pass the data:
session()->flash('someVariable', $someData);
return redirect(url()->previous() . '#hashid');
To get stored data:
$someData = session('someVariable');
Or in a view:
{{ session('someVariable') }}

Django form ajax submit concurrently

I have some field created by Django form and there are some other data I want to post to other form using jQuery(Ajax).
Is there any way to post them to different tables with two different ways at the same time?
form.py
class MyForm(forms.ModelForm):
class Meta:
model = models.Planning
fields = ['title','description','open','owner','upload_time']
template
<form id="myform" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.management_form }}
<div id="select_country">
<p style="display: inline;">country</p>
<select id="city">
<option selected disabled hidden>please choose</option>
{% for x in areas %}
<option value="{{x.area_country}}">{{x.area_country}}</option>
{% endfor %}
</select>
<select id="areas" name="my_areas"></select>
<br>
<div class="my_detail">
</div>
<br>
</div>
<div id="content_loi" class="col-lg-4">
<div class="col-lg-12" id="list"></div>
<div class="col-lg-12"">
<label>title:{{form.title}}</label>
<p><b>description:</b>{{form.description}}</p>
<button type="submit" class="btn btn-default" style="margin:0 auto;">submit</button>
</div>
</div>
</form>
I want to store the chosen areas and foreign key to another table with ajax
view
def make_list(request):
template = get_template('index.html')
areas = models.Area.objects.values('area_country').distinct()
max_my_id = models.RoutePlanning.objects.all().aggregate(Max('my_id'))
my_id = int(max_my_id['my_id__max']) + 1
#city = request.POST.get('my_areas')
if request.method == 'POST':
form = forms.MyForm(request.POST,initial={'owner':username,'route_id':my_id,'route_upload_time':datetime.now()})
if form.is_valid():
form.save()
return HttpResponseRedirect('/make_player')
else:
loi_form = forms.MyForm(initial={'owner':username,'route_id':my_id,'route_upload_time':datetime.now()})
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)

Resources