Jquery Ajax submit() not firing in django model form - javascript

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...

Related

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();
});
});

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.

How to show message that user is already registered in html through php?

I have an HTML form in which a user enter his/her email id to register everything is working great it checks the valid email id and also registered the email id ! But when I applied new code to check that the user is already registered or not it didn't work !!
Below is my Html page
<!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">
<title>Sign Up - MOBTRICKS</title>
<!-- CSS -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lobster">
<link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Lato:400,700'>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Favicon and touch icons -->
<link rel="shortcut icon" href="assets/ico/fa.png">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<!-- <script type="text/javascript">
function greeting(){
alert("Welcome ! Your Email : " + document.forms["form"]["email"].value + " has been registered under our records successfully !")
}
</script> -->
</head>
<body>
<!-- Header -->
<div class="container">
<div class="row header">
<div class="col-sm-4 logo">
<h1><a href=#>PQR</a> <span>.</span></h1>
</div>
<div class="col-sm-8 call-us">
<p>Mob: <span>+91-9530803237</span> | email: <span>ab.creations27#gmail.com</span>
</p>
</div>
</div>
</div>
<!-- Coming Soon -->
<div class="coming-soon">
<div class="inner-bg">
<div class="container">
<div class="row">
<div class="col-sm-12">
<center>
<i class="fa fa-cog fa-spin fa-3x fa-fw"></i>
<span class="sr-only">Loading...</span>
<h2>We're Coming Soon</h2>
<p>We are working very hard on the new version of our site. It will bring a lot of new features. Stay tuned!</p>
<div class="timer">
<div class="days-wrapper">
<span class="days"></span>
<br>days
</div>
<div class="hours-wrapper">
<span class="hours"></span>
<br>hours
</div>
<div class="minutes-wrapper">
<span class="minutes"></span>
<br>minutes
</div>
<div class="seconds-wrapper">
<span class="seconds"></span>
<br>seconds
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Content -->
<div class="container">
<div class="row">
<div class="col-sm-12 subscribe">
<h3>Subscribe to our newsletter !!</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" role="form" action="assets/subscribe.php" method="post">
<div class="form-group">
<label class="sr-only" for="subscribe-email">Email address</label>
<input type="text" name="email" placeholder="Enter your email..." class="subscribe-email form-control" id="subscribe-email">
</div>
<button type="submit" class="btn">Subscribe</button>
</form>
***
<div class="success-message"></div>
<div class="error-message"></div>***
</div>
</div>
<div class="row">
<div class="col-sm-12 social">
<i class="fa fa-facebook"></i>
<i class="fa fa-twitter"></i>
<a href="https://github.com/ashu271994" data-toggle="tooltip" data-placement="top" title="GitHub">
<i class="fa fa-github"></i>
</a>
<i class="fa fa-google-plus"></i>
<i class="fa fa-pinterest"></i>
<i class="fa fa-envelope-o"></i>
</div>
</div>
</div>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© ASHISH BHARWAL
</li>
<li>Credits: AB-Creations
</li>
</ul>
</footer>
<!-- Javascript -->
<script src="assets/js/jquery-1.11.1.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
ipt src="assets/js/jquery.backstretch.min.js"></script>
<script src="assets/js/jquery.countdown.min.js"></script>
<script src="assets/js/scripts.js"></script>
<!--[if lt IE 10]>
<script src="assets/js/placeholder.js"></script>
<![endif]-->
</body>
</html>
Below is my Subscriber.php page
<?php
// Email address verification
function isEmail($email)
{
return (preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]| [[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if ($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'ab.creations27#gmail.com';
$subscriber_email = addslashes(trim($_POST['email']));
if (!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
// $msg="wrong answer";
// echo "<script type='text/javascript'>alert('$msg');</script>";
} else {
$host = "somehostname";
$user = "username";
$pwd = "password";
$db = "demo1";
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql_insert = "SELECT * FROM demotable WHERE subs='$subscriber_email'";
$stmt1 = $conn->prepare($sql_insert);
$stmt1->execute();
$result = $stmt1->fetchColumn();
if ($result == 0) {
$sql_insert = "INSERT INTO demotable (subs)
VALUES ('$subscriber_email')";
$stmt = $conn->prepare($sql_insert);
$stmt->execute();
$array = array();
$array['valid'] = 1;
$array['message'] = "Your Email : $subscriber_email has been registered with us ! Thanks for your subscription!";
echo json_encode($array);
} else {
$array = array();
$array['valid'] = 2;
$array['message'] = "You are already registered !!";
echo json_encode($array);
}
}
catch (Exception $e) {
die(var_dump($e));
}
}
}
?>
Now what is happening when I tried to add an invalid email id then it shows Invalid Email id in marked in HTML page but when I added a new user then add the data in my table and show message but in case of the user who is already registered it didn't show any message !! I also tried to make new functions having "echo json_encode($array)"; But this also won't work !! Tell me what am I missing or what's my mistake !! I am trying to sort it from the last 3 days !!
my scripts.js code below
$('.subscribe form').submit(function(e) {
e.preventDefault();
var postdata = $('.subscribe form').serialize();
$.ajax({
type: 'POST',
url: 'assets/subscribe.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else if (json.valid == 1){
$('.error-message').hide();
$('.success-message').hide();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
else {
$('.error-message').hide().empty();
$('.success-message').hide().empty();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
});
Try changing
$result = $stmt1->fetchColumn();
to
$result = $stmt1->num_rows;
see if that works.
Finally got it working. The error was simple but yet difficult to find. lolz
$sql_insert = "SELECT * FROM demotable WHERE subs='$subscriber_email'";
should be like
** $sql_insert = "SELECT COUNT(*) FROM demotable WHERE subs='$subscriber_email'";**
Thank you all for your views. :)

Ajax search feature not working in django App

I'm following a tut from Mike hibbert and have tried to modify it a bit to suit my needs but it's not working. I wanted to use his way because my way was breaking the DRY rule, I had to write search logic for each of my views I thought it might be the order my js But I dont think it is. I could be wrong, as I am fairly new to prgramming. I'm not sure but i think the issue may be with my search being on the nav which I nav in an include. Heres my code
views.py
def search_title(request):
if request.method == "POST":
search_text = request.POST['search_text']
else:
search_text = ''
posts = Post.objects.filter(
Q(title__contains=search_text)|
Q(content__contains=search_text)
)
context = {
"posts": posts
}
return render(request, "posts/ajax_search.html", context)
my nav.html
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{% url 'posts:list' %}">HiSPANIC HEiGHTS</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<form method="POST" action=" " class="navbar-form navbar-right">
<div class="input-group">{% csrf_token %}
<input type="text" name="search" id="search" placeholder="search" value="{{ request.GET.q }}" class="form-control"
style="width: 350px">
<ul id="search-results">
</ul>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary"><span style="font-size:1.4em" class="glyphicon glyphicon-search"></span> </button>
</span>
</div>
</form>
<ul class="nav navbar-nav">
<li>Home</li>
<li>Sewp</li>
{% if user.is_authenticated %}
<li>Admin</li>
<li>Create</li>
{% endif %}
</ul>
</div><!--/.nav-collapse -->
</div>
base.html
{% load staticfiles %}
<html>
<head>
<title> {% block head_title %} try django 1.9 {% endblock head_title %}</title>
<link rel="stylesheet" href='{% static "css/base.css" %}'/>
<!-- 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">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
{% include "includes/nav.html" %}
{% include "includes/messages_display.html" %}
<div class="container">
{% if title == "posts" %}
<div class="jumbotron" style="margin-top: 80px">
{% block jumbotron %}{% endblock jumbotron %}
</div>
{% endif %}
{% block content %}{% endblock content %}
</div>
<!-- Latest compiled and minified JavaScript -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous">
</script>
<script src="{% static 'js/ajax.js' %}"></script>
<script src="{% static 'js/jquery.bootstrap-autohidingnavbar.js' %}"></script>
<script>
$("nav.navbar-fixed-top").autoHidingNavbar();
</script>
ajax.js
$(function(){
$('#search').keyup(function() {
$.ajax({
type: "POST",
url: "/posts/search/",
data: {
'search_text': $('#search').val(),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data);
}
my posts/urls.py
urlpatterns = [
url(r'^$', post_list, name='list'),
url(r'^tag/(?P<slug>[\w-]+)/$', tag_list, name="tag_list"),
url(r'^create/$', post_create, name='create'),
url(r'^sewp$', sewp, name='sewp'),
url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'),
url(r'^(?P<id>\d+)/delete/$', post_delete, name='delete'),
url(r'^search/', search_title),
]
I see no errors in the network, I've switched back and forth from GET to POST, just trying to tweak things to make it work but nothing has changed. My jquery is from a CDN but I don't think that's an issue, but I am a newb and could be wrong. any help with this will be appreciated
Move your search url definition to the top of the urlpatterns list, so it doesn't get masked by the post_detail wildcards:
urlpatterns = [
url(r'^$', post_list, name='list'),
url(r'^search/', search_title),
url(r'^tag/(?P<slug>[\w-]+)/$', tag_list, name="tag_list"),
url(r'^create/$', post_create, name='create'),
url(r'^sewp$', sewp, name='sewp'),
url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'),
url(r'^(?P<id>\d+)/delete/$', post_delete, name='delete'),
]
From the docs:
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
And your post_detail regexp certainly matches search/.
I think you may be required to have $ at the end of your search url string.
url(r'^search/$', search_title),
This lets django know it's the end of the string. Unless you've confirmed that you've actually been able to dispatch to the search_title view.

Ajax call to Django function

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 :)

Categories

Resources