Ajax call to Django function - javascript

I'm trying to delete a list of images selected via checkbox via Ajax, which have been uploaded via Django Ajax Uploader. I've successfully obtained a list of the images but I'm not sure how to pass it Django function via Ajax. Can anyone please advise on:
How can I pass the list of selected images to a Django function to delete the images?
How should I handle the CSRF for the ajax portion?
html
<!DOCTYPE html>{% load static from staticfiles %} {% load i18n %}
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Demo</title>
<script src="{% static 'js/jquery.min.js' %}"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<style>
input.chk {
margin-left: 70px;
}
</style>
</head>
<body>
<div class="wrapper">
<div id="content" class="clearfix container">
{% load i18n crispy_forms_tags %}
<form method="post" action="." enctype="multipart/form-data">
{% csrf_token %} {% crispy form %} {% crispy formset formset.form.helper %}
<div class="image-upload-widget">
<div class="preview">
</div>
<div class="file-uploader">
<noscript>
<p>{% trans "Please enable JavaScript to use file uploader." %}</p>
</noscript>
</div>
<p class="help_text" class="help-block">
{% trans "Available file formats are JPG, GIF and PNG." %}
</p>
<div class="messages"></div>
</div>
<input type="submit" name="save" class="btn btn-primary pull-right" value="Submit">
<input type="button" id="delete" class="btn btn-primary pull-left" value="Delete Selected Files">
</form>
</div>
</div>
<script src="{% static 'js/fileuploader.js' %}"></script>
<link href="{% static 'css/fileuploader.css' %}" media="screen" rel="stylesheet" type="text/css" />
<script>
$(function() {
var uploader = new qq.FileUploader({
action: "{% url 'planner:ajax_uploader' %}",
element: $('.file-uploader')[0],
multiple: true,
onComplete: function(id, fileName, responseJSON) {
if (responseJSON.success) {
url = '<label for="' + fileName + '"><img src="' + {{MEDIA_URL}} + responseJSON.url + '" alt="" /></label>';
checkbox = '<p><input type="checkbox" class="chk" id="' + fileName + '" name="' + fileName + '" value="0" /></p>';
$('.preview').append(url);
$('.preview').append(checkbox);
} else {
alert("upload failed!");
}
},
onAllComplete: function(uploads) {
// uploads is an array of maps
// the maps look like this: {file: FileObject, response: JSONServerResponse}
alert("All complete!");
alert(checkbox);
},
params: {
'csrf_token': '{{ csrf_token }}',
'csrf_name': 'csrfmiddlewaretoken',
'csrf_xname': 'X-CSRFToken',
},
});
});
</script>
<script>
$("#delete").on('click', function() {
var allVals = [];
$(":checkbox").each(function() {
var ischecked = $(this).is(":checked");
if (ischecked) {
allVals.push(this.id);
}
});
});
</script>
</body>
</html>

Once you got the list of images to delete, you pass it on to an Ajax call that will be handled by a Django view, like so:
function submitData(data) {
var csrftoken = getCookie('csrftoken'); // from https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax
$.ajax({
type: 'POST',
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
data: JSON.stringify(data),
url: {% url 'image_handler' %}
}).done(function(data) {
console.log(data.deleted + ' images were deleted');
}).error(function(data) {
console.log('errors happened: ' + data);
});
}
Then, in your views.py:
def image_handler(request):
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
str_body = request.body.decode('utf-8')
changes = json.loads(str_body)
for change in changes:
pass # `change` contains the id of the image to delete
data = {'status': 200,
'deleted': len(changes)}
return JsonResponse(data)
It works pretty nicely :)

Related

Reload flask page after form submission success with JQuery

I have a page that uses a form with POST method that passes a file to my flask application. I have read that my app.route cannot handle both a send_file and a redirect. So my workaround is to refresh the page after the post request is successful.
Here is my HTML with my script at the bottom:
{% extends "base.html" %}
{% block head %}
<!-- {# <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/leaf.css') }}"> #} -->
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/base.css') }}"> -->
{% endblock %}
{% block content %}
<div id="vo_budget_file_settings">
{# Upload Final CRO Budget File #}
<p>Please upload the final CRO budget File</p>
<form class="" action="/generatecleanbudgetfile" method=POST enctype=multipart/form-data>
<input type="file" name="data_file" accept=".xls, .xlsx, .xlsm"/>
<input type="submit" value="Begin Format" onclick="loading();"/>
</form>
</div>
<!-- funtion to show css spinner on button click -->
<script type="text/javascript">
function loading(){
$(".loader").show();
}
</script>
<script type="text/javascript">
// Reload page 60 seconds after form submission
$("vo_budget_file_settings").onsubmit = setTimeout(function () {
window.location = "/bugetformatter";
}, 60000);
console.log(window.location);
</script>
{% endblock %}
Here is my app:
#app.route('/bugetformatter')
def data_request_portal():
return render_template('CROBudgetFormatter.html', title='CRO Budget Formatting Tool')
#app.route('/generatecleanbudgetfile', methods=['GET', 'POST'])
def clean_budget():
file = request.files.get('data_file')
app.logger.info('Conversion has started')
try:
if request.method == 'POST':
file = request.files.get('data_file')
file.seek(0)
buffer = budget_cleaner(file)
buffer.seek(0)
app.logger.info('Conversion Complete')
return send_file(
buffer,
as_attachment=True,
attachment_filename=f'stripped_budget_{dt.today().strftime("%m.%d.%Y")}.xlsx',
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
except:
return render_template('error_type.html', title='Unable to process uploaded budget.')
Question:
Is there a script that behaves like a callback and will only reload the window once the request is completed and my file downloads to the browser?
Right now I'm using the 60 timer to reset after the form is submitted, but I would like it to be tied to the file download just in case the job takes longer than that.
your app needs to be
#app.route('/generatecleanbudgetfile', methods=['GET', 'POST'])
def clean_budget():
file = request.files.get('data_file')
app.logger.info('Conversion has started')
try:
if request.method == 'POST':
file = request.files.get('data_file')
file.seek(0)
buffer = budget_cleaner(file)
buffer.seek(0)
app.logger.info('Conversion Complete')
return send_file(
buffer,
as_attachment=True,
attachment_filename=f'stripped_budget_{dt.today().strftime("%m.%d.%Y")}.xlsx',
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
return 1
except:
return render_template('error_type.html', title='Unable to process uploaded budget.')
and your html file needs to be:
{% extends "base.html" %}
{% block head %}
<!-- {# <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/leaf.css') }}"> #} -->
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/base.css') }}"> -->
{% endblock %}
{% block content %}
<div id="vo_budget_file_settings">
{# Upload Final CRO Budget File #}
<p>Please upload the final CRO budget File</p>
<form class="formdata" action="/generatecleanbudgetfile" method=POST enctype=multipart/form-data>
<input type="file" name="data_file" accept=".xls, .xlsx, .xlsm"/>
<input type="button" value="Begin Format" onclick="submit();"/>
</form>
</div>
<!-- funtion to show css spinner on button click -->
<script type="text/javascript">
$("form.formdata").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: "POST",
url: '/generatecleanbudgetfile',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
window.location.reload();
},
error: function() {
alert('Error occured');
window.location.reload();
}
});
});
</script>
{% endblock %}
Hope this helps you.

Can't get image upload to work with Flask and JQuery

The following code allows you to submit forms and return a variation of the text from Flask using AJAX and JQuery:
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
#app.route('/')
def index():
return render_template('form.html')
#app.route('/process', methods=['POST'])
def process():
email = request.form['email']
name = request.form['name']
if name and email:
newName = name[::-1]
return jsonify({'name' : newName})
return jsonify({'error' : 'Missing data!'})
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="{{ url_for('static', filename='js/form.js') }}"></script>
</head>
<body>
<div class="container">
<br><br><br><br>
<form class="form-inline">
<div class="form-group">
<label class="sr-only" for="emailInput">Email address</label>
<input type="email" class="form-control" id="emailInput" placeholder="Email">
</div>
<div class="form-group">
<label class="sr-only" for="nameInput">Name</label>
<input type="text" class="form-control" id="nameInput" placeholder="First Name">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<br>
<div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
<div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
</div>
</body>
</html>
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
name : $('#nameInput').val(),
email : $('#emailInput').val()
},
type : 'POST',
url : '/process'
})
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
}
else {
$('#successAlert').text(data.name).show();
$('#errorAlert').hide();
}
});
event.preventDefault();
});
});
But when I slightly modify the code to do the same thing with a uploaded file's name it doesn't work. All I have done is changed the type of form so that it takes in files and then made it so that it reverses the filename rather than the inputted text from the previous version. Do you know what I am doing wrong here?
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
#app.route('/')
def index():
return render_template('form.html')
#app.route('/process', methods=['POST'])
def process():
filename = request.files['file'].filename
if filename:
newName = filename[::-1]
return jsonify({'name' : newName})
return jsonify({'error' : 'Missing data!'})
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="{{ url_for('static', filename='js/form.js') }}"></script>
</head>
<body>
<div class="container">
<br><br><br><br>
<form method="POST" action='/process' enctype="multipart/form-data">
<div>
<label for="file">Choose file to upload</label>
<input type="file" id="file" name="file">
</div>
<div>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
<br>
<div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
<div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
</div>
</body>
</html>
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
file : $('#file')
},
type : 'POST',
url : '/process'
})
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
}
else {
$('#successAlert').text(data.name).show();
$('#errorAlert').hide();
}
});
event.preventDefault();
});
});
If you use an object of the type FormData to serialize and transfer the data of the form it should work.
$(document).ready(function() {
$('form').submit(function(event) {
let formData = new FormData(event.target);
$.ajax({
data: formData,
type : 'POST',
url : '/process',
contentType: false,
processData: false
})
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
} else {
$('#successAlert').text(data.name).show();
$('#errorAlert').hide();
}
});
event.preventDefault();
});
});

Jquery Ajax submit() not firing in django model form

I've tried looking up online, rewriting the code but the submit() won't fire but when I use a click event, it fire an calls the callback and the ajax() runs. I cannot figure out what's really wrong with the code even after going through so many tutorials and documentation online.
Here's the code:
HTML template with the form
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- site icon -->
<link rel="icon" href="{% static 'img/question.png' %}">
<!-- Bootstrap core CSS -->
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<!-- Font Awesome -->
<link href="{% static 'css/font-awesome.min.css' %}" rel="stylesheet">
<!-- Endless -->
<link href="{% static 'css/endless.min.css' %}" rel="stylesheet">
</head>
<body>
<div class="login-wrapper">
<div class="text-center">
<span>
<img src="{% static 'img/question.png' %}" style="height: 100px; width: 100px; border-radius: 50%;">
</span>
</div>
<div class="text-center">
<h2 class="fadeInUp animation-delay8" style="font-weight:bold">
<span class="text-success">CitiSpy User Login</span>
</h2>
</div>
<div class="login-widget animation-delay1">
<div class="panel panel-default">
<div class="panel-heading clearfix">
<div class="pull-left">
<i class="fa fa-lock fa-lg"></i> Login
</div>
</div>
<div class="panel-body">
<div id="login-form-main-message"></div>
<form class="form-login" id="login_form" method="POST">
{% csrf_token %}
<div id="form_content">
{{ form.non_field_errors }}
<div class="form-group">
{{ form.email.errors }}
<label for="{{ form.email.id_for_label }}">{{ form.email.label }}</label>
{{ form.email }}
</div>
<div class="form-group">
{{ form.password.errors }}
<label for="{{ form.password.id_for_label }}">{{ form.password.label }}</label>
{{ form.password }}
</div>
<div class="seperator"></div>
<hr/>
<div class="form-group">
<!-- <button class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" type="submit" id="id_submit">
<i class="fa fa-sign-in"></i>
Login
</button> -->
<a type="submit" class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" id="login_submit" href="#"> -->
<i class="fa fa-sign-in"></i>
Login
</a>
</div>
</div>
</form>
</div>
</div><!-- /panel -->
</div><!-- /login-widget -->
</div><!-- /login-wrapper -->
<!-- Jquery -->
<script src="{% static 'js/jquery-1.10.2.min.js' %}"></script>
<!-- Bootstrap -->
<script src="{% static 'bootstrap/js/bootstrap.js' %}"></script>
<!-- Pace -->
<script src="{% static 'js/uncompressed/pace.js' %}"></script>
<!-- Popup Overlay -->
<script src="{% static 'js/jquery.popupoverlay.min.js' %}"></script>
<!-- Slimscroll -->
<script src="{% static 'js/jquery.slimscroll.min.js' %}"></script>
<!-- Modernizr -->
<script src="{% static 'js/modernizr.min.js' %}"></script>
<!-- Cookie -->
<script src="{% static 'js/jquery.cookie.min.js' %}"></script>
<!-- Endless -->
<script src="{% static 'js/endless/endless.js' %}"></script>
<!--login js-->
<script src="{% static 'js/accounts/login_1.js' %}"></script>
</body>
</html>
JavaScript
$(document).ready(function(){
function 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 = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var $csrf_token = {
name: "csrfmiddlewaretoken",
value: getCookie('csrftoken')
};
var $myId = $("#login_form >#form_content > .form-group > button").attr('class');
console.log($myId);
$("#login_form").submit(function(event){
console.log("I am in submit");
event.preventDefault();
var $form_data = $(this).serializeArray();
$form_data.push($csrf_token);
$.ajax({
type: 'POST',
data: $form_data,
cache: false,
dataType: 'json',
url: '/accounts/userLogin/',
beforeSend: function(){
$("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /> Please wait...</div>");
$("#form_content").css("display", "none");
},
success: function(data){
if (data.status === "ok"){
if (data.to === "verify") {
//redirect to account verification
} else {
if (data.to === "user") {
//redirect to user account
$("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /> Success! login you in, please wait...</div>");
$("#form_content").css("display", "none");
}else{
$("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /> Success! login you in, please wait...</div>");
$("#form_content").css("display", "none");
location.href = '/em_dept/dashboard/';
}
}
}
},
error:function(xhr,errmsg,err){
console.log("error error error!!!");
console.log(xhr.status + ": " + xhr.responseText);
}
});
// return false;
});
});
The View rendering the form
#method_decorator(csrf_protect, name='post')
class UserLogin(LoginView):
"""docstring for UserLogin"""
template_name = 'accounts/login.html'
# authentication_form = LoginForm()
def get(self, request):
'''a func to work on the request.POST'''
print("getting the form for you ")
form = LoginForm()
return render(request,self.template_name,{'form':form})
def post(self, request):
form = LoginForm(request.POST)
print("go the data for you")
if request.is_ajax():
print("entered form")
if form.is_valid():
print("form valid")
email = form.cleaned_data['email']
try:
user = User.objects.get(email=email)
print("user obj", user)
if user.check_password(form.cleaned_data['password']):
# 0-super admin, 1-dept admin,2-dept staff, 3-end user
print("correct password")
if user.account_type == 4:
if user.last_login == None or user.last_login == '':
to = "verify"
else:
to = "user"
else:
if user.account_type == 2:
to = 'dept_admin'
elif user.account_type == 3:
to = 'dept_staff'
elif user.account_type == 1:
to = 'super_user'
else:
to = None
res = {'status':'ok', 'error':False, 'acc_type':to, 'data':user.email}
else:
print("incorrect password")
res = {'status':'fail', 'error':'incorrect password'}
except Exception as e:
print("User not found!", e)
res = {'status':'fail', 'error':'account not found'}
else:
print("form valid")
res = {'status':'fail', 'error':form.errors}
return JsonResponse(res)
<a type="---" is just a type hinting having submit there does not trigger form submit.
Why is the actual submit button commented out?
<!-- <button class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" type="submit" id="id_submit">
<i class="fa fa-sign-in"></i>
Login
</button> -->```
I would uncomment this and go from there.
try to use on('submit') instead of submit().
What version of jquery do you use ?
it should be <Input type='submit'not<a>thats why your click worked before...

Laravel 5.3 impossible to put script on view (autocomplete field)

I’m currently working on Laravel 5.3 for my internship.
And as you guessed, I have an annoying issue let me explain it:
On a page, I have to put an « autocomplete » field but It’s not working at all.
I have this error I can’t solve:
[Vue warn]: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed. app.js:139
Furthermore, I need to keep the larvel « template » like the top bar with the login name, etc…
I tried a lot of solutions found on the internet but nothing worked.
I’m totally desperate, do you have any solutions ?
ps: Sorry for the awful grammar, I'm french and I'm learning, thanks for your comprehension.
selectcr.blade.php
#extends('layouts.app')
#section('content')
<!DOCTYPE html>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Selection de Compte-Rendu</div>
<div class="panel-body"> Selectionnez le client:
<input id="intervenant-name" type="text" class="form-control pd-l-50" placeholder="Recherche par nom d'entreprise">
<script src="{{asset('js/jquery-1.12.4.js')}}"></script>
<script src="{{asset('js/jquery-ui.js')}}"></script>
<script>
(function () {
src = "/prefcard/maker-search-intervenant";
$("#intervenant-name").autocomplete({
source: function (request, response)
{
$.ajax({
url: src,
dataType: "json",
data:
{
term: request.term
},
success: function (data)
{
response(data);
}
});
},
min_length: 2,
select: function (event, ui)
{
//console.log(ui.item.value);return false;
var test = ui.item.value ? ui.item.value : '';
if (test != '')
{
var url = '/prefcard/maker-search-intervenant';
var formAutocomplete = $('<form action="' + url + '" method="post">' +
'<input type="hidden" name="_token" value="{{ csrf_token() }}">' +
'<input type="text" name="term" value="' + ui.item.value + '" />' +
'</form>');
$('body').append(formAutocomplete);
formAutocomplete.submit();
}
}
});
})();
</script>
</div>
</div>
</div>
</div>
</div>
#yield('javascript')
#endsection
SelectCRController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class SelectCRController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('selectcr');
}
public function searchIntervenant(Request $request) {
$query = $request->get('term', '');
$results = DB::table('intervenant')->where('intervenantEntreprise', 'LIKE', '%' . $query . '%')->orWhere('intervenantFonction', 'LIKE', '%' . $query . '%')->take(5)->get();
$data = array();
foreach ($results as $result) {
$data[] = array('value' => $result->intervenantEntreprise . ' ' . $result->intervenantEmail, 'id' => $result->id);
}
if (count($data))
return $data;
else
return ['value' => 'No Result Found', 'id' => ''];
}
public function postSearchIntervenant(Request $request) {
//Do whatever you want to search accordingly name and then return
return view('dashboard')->with('intervenant', $intervenant);
}
}
web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('/', function () {return view('welcome');});
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::get('/configuration', 'ConfigurationController#index');
Route::get('/selectcr', 'SelectCRController#index');
Route::get('/prefcard/maker-search-intervenant', 'SelectCRController#searchIntervenant');
Route::post('/prefcard/maker-search-intervenant', 'SelectCRController#postSearchIntervenant');
Route::get('/intervenant', function () {return view('intervenant');});
Route::get('/api/intervenant/{id?}', 'IntervenantController#index');
Route::post('/api/intervenant', 'IntervenantController#store');
Route::post('/api/intervenant/{id?}', 'IntervenantController#update');
Route::delete('/api/intervenant/{id?}', 'IntervenantController#destroy');
Route::get('/utilisateur', function () {return view('utilisateur');});
Route::get('/api/utilisateur/{id?}', 'UtilisateurController#index');
Route::post('/api/utilisateur', 'UtilisateurController#store');
Route::post('/api/utilisateur/{id?}', 'UtilisateurController#update');
Route::delete('/api/utilisateur/{id?}', 'UtilisateurController#destroy');
Route::post('register', 'Auth\RegisterController#register');
//Route::auth();
app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
<link href="/css/app.css" rel="stylesheet">
<!-- Scripts -->
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
</head>
<body>
<div id="app">
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<!-- Collapsed Hamburger -->
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- Branding Image -->
<a class="navbar-brand" href="{{ url('/') }}">
{{ config('app.name', 'Laravel') }}
</a>
</div>
<div class="collapse navbar-collapse" id="app-navbar-collapse">
<!-- Left Side Of Navbar -->
<ul class="nav navbar-nav">
</ul>
<!-- Right Side Of Navbar -->
<ul class="nav navbar-nav navbar-right">
<!-- Authentication Links -->
#if (Auth::guest())
<li>Login</li>
#else
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
{{ Auth::user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="{{ url('/logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
</li>
#endif
</ul>
</div>
</div>
</nav>
#yield('content')
</div>
<!-- Scripts -->
<script src="/js/app.js"></script>
</body>
</html>
UPDATE
Now and with some modifications the error disappeared but the scripts are not working at all.
<!DOCTYPE html>
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Selection de Compte-Rendu</div>
<div class="panel-body"> Selectionnez le client:
<input id="intervenant-name" type="text" class="form-control pd-l-50" placeholder="Recherche par nom d'entreprise">
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script src="{{asset('js/jquery-1.12.4.js')}}"></script>
<script src="{{asset('js/jquery-ui.js')}}"></script>
<script>
(function () {
src = "/prefcard/maker-search-intervenant";
$("#intervenant-name").autocomplete({
source: function (request, response)
{
$.ajax({
url: src,
dataType: "json",
data:
{
term: request.term
},
success: function (data)
{
response(data);
}
});
},
min_length: 2,
select: function (event, ui)
{
//console.log(ui.item.value);return false;
var test = ui.item.value ? ui.item.value : '';
if (test != '')
{
var url = '/prefcard/maker-search-intervenant';
var formAutocomplete = $('<form action="' + url + '" method="post">' +
'<input type="hidden" name="_token" value="{{ csrf_token() }}">' +
'<input type="text" name="term" value="' + ui.item.value + '" />' +
'</form>');
$('body').append(formAutocomplete);
formAutocomplete.submit();
}
}
});
})();
</script>
#endsection
#yield('javascript')
1) You have a Vuejs error (add tag plz). Looks like you need to move script tags out of vuejs container.
2) !DOCTYPE html must be at the top of your document, not in the middle.
Blade is powerful to "inject" your view into a skeletonized html page. If you need some clean way to call your layout/app.blade.php, I made an example right below :
layout/app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>#yield('title')</title>
#yield('links')
</head>
<body>
#yield('content')
<!-- Here is the perfect place for the javascript libraries that you think will be used in ANY page -->
<script src="jquery/jquery.min.js"></script> <!-- for example if you use jQuery -->
<script src="bootstrap/js/bootstrap.min.js"></script> <!-- same if you need Bootstrap-Twitter-3 in any pages -->
<!-- And then, your specific scripts are hooked below -->
#yield('scripts')
</body>
</html>
Then, it is as simple as it looks to "inject" your content inside your <body> tag, like following :
selectcr.blade.php (juste an example)
#extends('layout.app')
<!-- Some additionnals css, specific to this page -->
#section('links')
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
#ensection
#section('title')
My awesome title
#endsection
#section('content')
<div class="container">
<div class="row">
<div class="col-lg-12">
<h3>Greetings user !</h3>
</div>
<div class="col-lg-12">
<div class="form">
<input type="text" />
<button type="submit">Go !</button>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
alert('This is my custom javascript !');
</script>
#endsection
So, whenever Blade encounters a #section tags, it automatically injects its content right inside the place it belongs, meaning in every #yield that represent this section.
Hope it helps.
Move #yield('javascript') out of the section put if after the #endsection tag, you could also just use #end.
Comment out all scripts within your section Tag also! because this is what the error is saying.
TRY:
All your script code should be inside
#section('scripts') .... #endsection.
And also please close content section before your javascript.
Solved it, I made a special "app.blade.php" just for the specified view and put all my scripts in it.
Not very beautiful, but It's working.

TokenMismatchException in laravel 5.2 ajax call

i am getting token mismatch exception every thing is seem correct.
this is my view code
#extends('layouts.master')
#section('content')
<div class="bg"></div>
<div class="login-sec clearfix">
<h1 class="lg-logo">YOU ARE JUST ONE STEP AHEAD</h1>
<div class="login-box clear">
<form id="websiteform" action="#">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="col-md-12 form-field">
<label for="">Project Name</label>
<input type="text" name="project" id="project">
</div>
<div class="col-md-12 form-field">
<label for="">Website URL</label>
<input type="url" name="website_url" id="website_url">
</div>
<div class="col-md-12 form-field">
<button type="submit" class="btn-green btn-large">Add Your Website</button>
</div>
</form>
</div>
</div>
#stop
and form source head section and footer is
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="csrf-token" content="4ryCSznz0mPSBcwXvbmZZHkZGcxZpyDy2dQ1VAoc" />
<link href="http://localhost:8080/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="http://localhost:8080/js/jquery.min.js"></script>
<script src="http://localhost:8080/js/bootstrap.min.js"></script>
<script src="http://localhost:8080/js/main.js"></script>
and my ajax call in main.js
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#websiteform').submit(function(e){
e.preventDefault();
var pro=$('#project').val();
var url=$('#website_url').val();
$.ajax({
type: "POST",
url: "project_save",
data: {project: pro, url: url},
success: function(data)
{
if(data.success==false)
{
alert(data.error);
}
else{
window.location = "dashboard";
}
},
error:function(){}
});
});
});
and route and controller function
Route::post('/project_save','WebsiteController#project_save');
public function project_save()
{
if(Request::ajax()){
$validator = Validator::make(Request::all(), [
'project' => 'required|max:255',
'url' => 'required',
]);
if($validator->fails()){
return Response::json(['success'=>false,'error'=>$validator->errors()->toArray()]);
}
$Website = new Website;
$Website->project_name = Request::get('project');
$Website->website_url = Request::get('url');
$Website->user_id = Auth::id();
$Website->save();
return Response::json(['success'=>true]);
}
}
this is my code and i am getting tokenmismatach exeption.
Change your \App\Http\Middleware\VerifyCsrfToken.php, add this code to function tokensMatch:
if ($request->ajax()) {
return true;
}
If you do not want CSRF protection for a particular url then you can add the urls in App\Http\Middleware\VerifyCsrfToken.php like this
protected $except = [
"project_save"
];
Try this
$_token = "{{ csrf_token() }}";
$.post( 'myurl', { param1: $param1, param2: $param2, _token: $_token })
.done(function( data )
{
console.log('Done!');
});
Carefully do a check on the following :
I had a similar issue and it was an easy fix.
Add this in your HTML meta tag area :
<meta name="csrf-token" content="{{ csrf_token() }}">
Then under your JQuery reference, add this code :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
If you are using the HTML form submit (not AJAX) then you need to put :
{{ csrf_field() }}
inside your form tags.

Categories

Resources