stay on page after submission of ajax form - javascript

I have a small popbox window which users are supposed to use to send a message to another user. After clicking the send button I send the data to views.py in my flask application.
At that point I would like the popbox to close and nothing else. Instead what happens is that I get a print out on my site with
{
"data": null
}
my ajax command is
<script type='text/javascript'>
$(".send_recommend").click(function() {
var data = $("form").serialize();
$.ajax({
url: "/send_recommend",
type: "GET",
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
data: { send_dummy_id: document.getElementById("send_dummy_id").value, data: data },
});
});
</script>
and the flask part of this looks like
#app.route('/send_recommend', methods=['GET', 'POST'])
def send_recommend():
if request.method == 'GET':
ret_data = {"data": request.args.get('data')}
#do something here
return jsonify(ret_data)
The html looks like
<div class='popbox' style="display: inline">
<button class="btn btn-primary open" href="#" data-id="{{ data['arxiv_id'] }}" role="button"><span class="glyphicon glyphicon-share"></span>Recommend this paper</button>
<div class='collapse_popbox'>
<div class='box'>
<div class='arrow'></div>
<div class='arrow-border'></div>
<form action="/send_recommend" method="GET" style="padding:10px;" align="right">
<p>
{{ form.From(size=30, readonly=true) }}
</p>
<p>
{{ form.To(size=30, placeholder='To') }}
</p>
<p>
{{ form.message(rows=3, cols=29, placeholder='Message') }}
</p>
<button class="btn btn-primary send_recommend">Send</button>
<button class="btn btn-default close1">Dismiss</button>
<input id="send_dummy_id" name="send_dummy_id" value="" type=hidden>
</form>
</div>
</div>
</div>
Basically my question is how can I prevent ajax from any feedback on the website? I used ajax because I do not want to reload the website after the form is submitted. Maybe ajax is the wrong tool?
thanks
fl

Prevent the default behavior on the item clicked like so:
<script type='text/javascript'>
$(".send_recommend").click(function(evt) {
evt.stopPropagation();
evt.preventDefault();
var data = $("form").serialize();
$.ajax({
url: "/send_recommend",
type: "GET",
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
data: { send_dummy_id: document.getElementById("send_dummy_id").value, data: data },
});
});
</script>

$(".send_recommend").click(function(е) {
e.preventDefault();
...
});
or just end the function with return false;

Just remove the return jsonify(ret_data) line form your send_recommend() route.
#app.route('/send_recommend', methods=['GET', 'POST'])
def send_recommend():
if request.method == 'GET':
ret_data = {"data": request.args.get('data')}
#do something here
Because you are returning the JSON data back to your template.

Related

method PUT of AJAX with Laravel 9

I am learning laravel, when I want to update an object and I use ajax to send data to update action with put method (routing also to set) but my update action side is not receiving it request that ajax send like so
! Code
<form id="formEdit" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="card-body">
<div class="form-group">
<label for="name">Name</label>
<input value="{{$role->name ?? ''}}" type="text" class="form-control" id="name" name="name" placeholder="Enter name">
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="float-right btn btn-primary">Lưu lại</button>
</div>
</form>
```
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function sendAjax(url, formData, type, method = 'post'){
var result = $.ajax({
url: url,
method: method,
typeData: 'json',
data: formData,
processData: false,
contentType: false,
async: false
});
return resultAjax(result, type);
}```
```
<script>
$('#formEdit').submit(function(event){
event.preventDefault();
var eleValidate = ['name'];
var data = new FormData($('#formEdit')[0]);
var url = "{{route('role.update', $role->id)}}";
var result = sendAjax(url, data, 'edit', 'put');
if(result){
renderError(result, eleValidate);
}else{
removeError(eleValidate, 'formEdit');
}
});
</script>
```
Route::put('/role/update/{id}', 'update')->name('role.update');
public function update(Request $request, $id)
{
if($request->ajax()){
$role = RoleModel::find($id);
dd($request);
}
}
Payload
dd($request)

AJAX POST not actually sending POST data with Django

I want to submit a form to my Django back end using an AJAX post. I have multiple forms on the page but only want the one the user submits to be the one that sends.
The form is held in a modal:
<div class="modal-body">
<div class='content-section'>
<form method="POST" id="form{{ prod.id }}" class="showform" value="{{ prod.id }}" >
<input type="hidden" value="{{ prod.id }}" name="prodid">
{% csrf_token %}
<fieldset class='form-group'>
{{ form|crispy}}
</fieldset>
</form>
</div>
</div>
<div class="modal-footer">
<div class='form-group'>
<button class="btn btn-outline-info submit-form" value={{prod.id}} form="form{{ prod.id }}"
>Save
To Profile</button>
</div>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
When the submit button is pressed, it triggers the following AJAX :
$(document).on('click', '.submit-form', function () {
var thisButton = $(this)[0]
var prodID = $(this).val();
var form = $("form" + prodID);
$.ajax({
type: 'post',
headers:{
"X-CSRFToken": '{{ csrf_token }}'
},
url: '/ajax/validate_showadd/',
dataType: 'json',
contentType: 'json',
data: {
'form': form.serialize(),
"prodID":prodID,
},
success: function (data) {
console.log("sent")
},
error: function(data) {
console.log("error")
}
});
return false;
});
However, within Django whenever I try access any of these values it just returns 'None' and the QueryDict for the POST request is empty.
Thank you

Using Ajax to post a form, no response

Django version 1.11.1
I have a form on my template, wanna use ajax to post it which can only change the form, my form code like:
<form action="" class="poster" id="posterForm">
{% csrf_token %}
<input type="file" accept="image/png,image/gif,image/jpeg" id="img_input" class="file_btn">
<input type="button" class="file_front_btn" value="选择图片" name="image">
<input type="text" name="title" id="title" class="title_area" placeholder="标题(不超过20字):">
<span class="img_root">已选图片:<span id="img_root" class="hidden">无</span></span>
<textarea name="content" id="content" name="content" class="content_area" placeholder="输入内容(不超过2000字):"></textarea>
<div id="title_error"></div>
<div id="content_error"></div>
<input type="button" class="submit" id="submitBtn" value="发布">
<div id="img_error"></div>
</form>
And my jQuery:
$(function(){
$('#submitBtn').on('click', function(){
$.ajax({
cache: false,
type: "POST",
url:"{% url 'community:poster' %}",
data:$('#posterForm').serialize(),
async: true,
success: function(data) {
if(data.status == 'success'){
$('#posterForm')[0].reset();
alert("发布成功")
}else if(data.status == 'fail'){
$('#img_error').html(data.msg)
}
},
});
});
})
And my views is:
class PosterView(View):
def post(self, request):
poster_form = PostForm(request.POST)
if poster_form.is_valid():
poster = poster_form.save(commit=True)
return HttpResponse("{'status':'success'}", content_type='application/json')
else:
return HttpResponse("{'status':'fail', 'msg':{0}}".format(poster_form.errors), content_type='application/json')
I use a ModelForm to commit the form, the forms is:
class PostForm(forms.ModelForm):
class Meta:
model = Posts
fields = ['image', 'title', 'content']
urls:
urlpatterns =[
url(r'^allpost/$', AllPosts.as_view(), name='allpost'),
url(r'^poster/$', PosterView.as_view(), name='poster'),
]
I can't see where the problem is, but when I click the submit button, nothing happened, no fail status.

Cannot POST / error when clicking Submit button

I am developing a login page for our mobile app using Phone gap. But whenever I clicked the Submit button, an error 'Cannot POST /' appears. Why is that so? Please see my code below.
index.html
<body>
<div class="main-info2">
<h3>Sign In</h3>
<div class="in-form">
<form id="login_form" method="post"">
<input type="text" placeholder="Username" required=" " id="email" />
<input type="password" placeholder="Password" required=" " id="password" />
<div class="check-sub">
<input type="submit" value="Login" id="login">
</div>
</form>
</div>
</div>
<div class="copy-right">
<p>Design by W3layouts</p>
</div>
</div>
<!-- //main -->
</body>
login.js
$(document).ready(function(){
do_login();
});
function do_login() {
$("#login").click(function () {
var email = $('#email').val();
var password = $('#password').val();
var dataString="email="+email+"&password="+password+"&login=";
if($.trim(email).length>0 & $.trim(password).length>0){
$.ajax({
type: 'POST',
url: "http://localhost:1234/cleverpro/login.php",
dataType: 'json',
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").html('Connecting...');},
success: function(data){
if(data == "success"){
console.log("hay nako!");
alert("hala");
}else if(data == "failed"){
$("#login").html('Login');
console.log("hastang sayupa");
alert("halajud");
}
}
});
}else{
return false;
console.log("walay sulod uy");
}
});
}
login.php
<?php
include "db.php";
if(isset($_POST['login'])){
$email=mysql_real_escape_string(htmlspecialchars(trim($_POST['email'])));
$password=mysql_real_escape_string(htmlspecialchars(trim($_POST['password'])));
$login=mysql_num_rows(mysql_query("select * from `user` where `email`='$email' and `password`='$password'"));
if($login!=0){
echo "success";
}else{
echo "failed";
}
}
?>
I didn't know where did I gone wrong with this. Please help me.
First of all it would be better to use on('submit', handler) instead on click. (see Whats the difference between onclick and onsubmit?)
When you clicks "Login", default form send action happens after your javascript code finishes. It means that form POST happens to 'action' of your form that is not set in your form and is '/' by default.
You need to preventDefault action, somethink like this
$('#login_form').on('submit', function(e) {
e.preventDefault();
//Your code
});

My twitter typehead and django-haystack solr config is not returning any results

Not very good with anything javascript, jquery. I am trying to return results from solr and run it through the typehead and have a dropdown list in a google or bing type fashion. Iv'e been kinda messing around with it but I'm deadlocked. I created a drop down list but it doesn't look nice. Heres my code
views.py
def search_title(request):
posts = SearchQuerySet().models(Post).autocomplete(content_auto=request.GET.get('search_text', ''))
context = {
"posts": posts
}
# context.update(csrf(request))
return render(request, "posts/ajax_search.html", {"posts": posts})
posts/urls.py
urlpatterns = [
url(r'^$', post_list, name='list'),
......
url(r'^search_f/$', search_title),
....
]
ajax_search.html
{% if posts.count > 0 %}
{% for post in posts %}
<div>{{ post.title }}</div>
{% endfor %}
{% else %}
<li class="list-group-item"> None to show</li>
{% endif %}
snippet of nav.html
<form method="GET" action="{% url 'posts:search-page' %}" class="navbar-form navbar-right" role="search">
<div>
<div class="input-group">
<input type="text" class="form-control" autocomplete="off" name="q" id="search" placeholder="search" value="{{ request.GET.q }}">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">search</button>
</span>
</div><!-- /input-group -->
<div class="list-group" id="search-results" style="margin: 5px 0 0 0; width: 172px">
</div>
</div><!-- /.col-lg-6 -->
</form>
ajax.js
$(function(){
$('#search').keyup(function() {
$.ajax({
type: "GET",
url: "/posts/search_f/",
data: {
'search_text': $('#search').val(),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data);
}
$('#search-results').typeahead({
name: 'user-search',
remote: '/posts/search_f/%QUERY' // you can change anything but %QUERY
});
I also need it to to be done so I won't get an error like this
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
I recently spent hours trying to resolve this on google chrome only to have it resolove itself
EDIT
I did some research and even though it didn't work I feel like I'm on the right track
$(function() {
$("#search").typeahead({
source:function(query,process) {
$.ajax({
url:'posts/search_f',
type:'GET',
data: {
'search_text': $('#search').val(),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
//dataType: 'JSON',
async: true,
success: function(data) {
console.log(data)
}
})
}
})
});

Categories