Show succes message from ajax - javascript

I have a question, So I create a sistem that update in database a row when onChange a select box. All goes well, but I want to drop a succes message if update was with succes.
My view :
<form action="" id="updateStatus" method="post">
<select id="statusSelect"
name="{{ gift.id_instant_gagnant }}"
class="form-control"
onChange="updateCadeauStatus({{ gift.id_instant_gagnant }})">
{% for key,statut in form_logistique.statut.choices %}
<option value="{{ key }}"
{% if gift.etat == key %}selected="selected"{% endif %}>
{{ statut }}
</option>
{% endfor %}
</select>
</form>
<script>
function updateCadeauStatus(id) {
var id = id;
var selectedName = $("#statusSelect option:selected").val();
var url_deploy = 'http:localhost/updateStatus'
console.log(id);
console.log(selectedName);
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
});
}
</script>
The controller :
public function updateStatus(){
$iGiftId = $_POST['id_cadeau'];
$iNewStatus = $_POST['id_status'];
$bUpdate = $this->updateStatusByGiftId($iGiftId, $iNewStatus);
return $this->render('logistique.twig');
}
The model :
public static function updateStatusByGiftId($iGiftId, $iStatusId){
$request = sprintf( ' UPDATE `%s` set etat = %d WHERE id = %d ', $table, $iStatusId, $iGiftId);
return Mysqli::query($request, $database);
}
So everything goes well but I want to drop a message after every update, too be displayed in the view. Please help me!!! Thx in advance, sorry for my english.

$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName},
success : function(data){
console.log('success');
},
error: function(){
console.log('error');
}
});

You can drop the response of the check file on ajax.
$.ajax({
url: url,
type: "POST",
...
success: function(response){
window.alert(response);
}
})
To be more specific, if you want to give a message only when you successfully changed the row. Modify the validation file (url:) and print a messagge only when you had success..
There are other ways to do that..
You can print a "message id" and get it with the script and drop a message:
$.ajax({
url: url,
type: "POST",
...
success: function(response){
if(response == '1'){
window.alert('Successfully changed!!');
}else if(response == '0'){
$("#foo").html("Error, not changed :(");
}else{
------ something else ------
}
}
})
Hope I could help !

Im not sure if you have your response in another file.
Cuz your response now is in the var data in the line with the code:
}).done(function(data){
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
}).done(function(data){
$("[SuccesDiv]").append("[Succes MSG]");
});
The text between the [ - ] is ment to put there your own element or data.
[EDIT]
I did'nt look good...
You are not looking when it is changed.
To do that, do this:
$("select").on("change", function(){
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
}).done(function(data){
$("[SuccesDiv]").append("[Succes MSG]");
});
});

Related

calling ajax inside form before submit showing `Uncaught ReferenceError`

I am trying to call an ajax function from inside a form to extract value for the drop down.
mypython.py
#app.route('/new_data', methods = ['POST', 'GET'])
def new_data():
#Filter data and return the data(data_list,filter_function_url) to myhtml.html file
myhtml.html
<div>
<form ....method="POST" action="{{url_for('submit_new_data')}}" method="POST" enctype="multipart/form-data">
....
....
<select id="selected_data" onchange='get_subdata_filters("{{ filter_function_url }}")'>
<option disabled selected>Please Select Partner State</option>
{% for f in data_list %}
<option value="{{f}}">{{f}}</option>
{% endfor %}
</select>
</form>
</div>
myjsfile.js
This does work fine the value from the id selected_data from the html file and the selected_option_data_filter_url got from html filter_function_url does get displayed properly on the console without any error
function get_subdata_filters(selected_option_data_filter_url) {
var selected_data = document.getElementById("selected_data").value;
// make the user selected data into a dictionary/json
var new_selected_data = {
s_data:selected_data
};
console.log(new_selected_data);
console.log(selected_option_data_filter_url);
}
When I add an ajax call inside my js function upto select
function get_subdata_filters(selected_option_data_filter_url) {
var selected_data = document.getElementById("selected_data").value;
// make the user selected data into a dictionary/json
var new_selected_data = {
s_data:selected_data
};
console.log(new_selected_data);
console.log(selected_option_data_filter_url);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: selected_option_data_filter_url,
traditional: "true",
async:false,
timeout: 40000,
data: JSON.stringify({new_selected_data}),
dataType: "json",
success: function(fselected_data){
console.log(fselected_data)
};
});
}
I get this error
Uncaught ReferenceError: get_subdata_filters is not defined when I check the console
What is doing wrong?
How can I correct this?
There is an error in your ajax call.
Remove the ; after the success and add an ; after your console.log()
function get_subdata_filters(selected_option_data_filter_url) {
var selected_data = document.getElementById("selected_data").value;
// make the user selected data into a dictionary/json
var new_selected_data = {
s_data:selected_data
};
console.log(new_selected_data);
console.log(selected_option_data_filter_url);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: selected_option_data_filter_url,
traditional: "true",
async:false,
timeout: 40000,
data: JSON.stringify({new_selected_data}),
dataType: "json",
success: function(fselected_data){
console.log(fselected_data);
}
});
}

Refresh content in a for loop using jquery in Django

I am creating a website that allows users to search for a list of papers. Once a list of papers is returned, the user can click "like" or "dislike" to one or more papers. The like count should dynamically update as the user click the like button.
I am using jquery to handle the dynamic update of the like count. However, I am not sure how to tell the success function in the ajax WHICH id to update. The reason is that the id is generated on the fly, and it is determined by which papers are returned as search results to the user.
So far, I have the following in the template:
{% for result in results %}
<li >
{{ result.title}},
<span class="like_span fa fa-thumbs-up"></span>
<strong id="like_count_{{ result.pk }}">{{result.likes}} </strong>
</li>
{% endfor %}
As you can see, i specify the id of the part where I want the dynamic update to happen as "like_count_{{ result.pk }}". I am not sure if this is the best way to go about it.
The jquery part looks like this:
<script>
$(document).ready(function(){
$(".like_button").click(function(){
$.ajax({
type: "GET",
data: {'pk': $(this).data('pid'),
'liked': $("span").hasClass('fa fa-thumbs-up') },
url: "{% url 'search:paperpreference' %}",
success: function(response) {
var pk = $(this).data('pid');
$(?????).html(response.likes )
},
error: function(response, error) {
alert(error);
}
});
});
});
</script>
Simply put, I don't know how can i specify the ????? part such that when success, the new like count is only updated to that specific paper, not the first paper in the loop.
The views.py has the following so far:
def paperpreference(request):
# if request.method == "GET":
pid = request.GET['pk']
paper = Paper.objects.get(pk=pid)
likes = paper.likes + 1
paper.likes = likes
paper.save()
data = {'likes': paper.likes}
return JsonResponse(data)
I am new to Jquery, any help would be much appreciated!
Thanks to suggestions by #dirkgroten, the like count can now be dynamically updated by the following jquery function. The trick is to move the pk declaration to before the ajax.
<script>
$(document).ready(function(){
$(".like_button").click(function(){
var pk = $(this).data('pid')
$.ajax({
type: "GET",
data: {'pk': pk,
'liked': $("span").hasClass('fa fa-thumbs-up') },
url: "{% url 'search:paperpreference' %}",
success: function(response) {
$("#like_count_"+ pk).html(response.likes )
},
error: function(response, error) {
alert(error);
}
});
});
});
</script>
another option is return the id from the server.
def paperpreference(request):
# if request.method == "GET":
pid = request.GET['pk']
paper = Paper.objects.get(pk=pid)
likes = paper.likes + 1
paper.likes = likes
paper.save()
data = {'likes': paper.likes,'pid':pid}
return JsonResponse(data)
<script>
$(document).ready(function(){
$(".like_button").click(function(){
var pk = $(this).data('pid')
$.ajax({
type: "GET",
data: {'pk': pk,
'liked': $("span").hasClass('fa fa-thumbs-up') },
url: "{% url 'search:paperpreference' %}",
success: function(response) {
$("#like_count_"+ response.pid).html(response.likes )
},
error: function(response, error) {
alert(error);
}
});
});
});
</script>

JQuery tokenfield with django not working

I am trying to incorporate a search field in a django registration form. I would like to use a bootstrap tokenfield that searches a django model for possible matches to the search string. I've been struggling with this for a couple of days now. Here is my code below.
<div class="form-inline" id="keywords_div">
{% csrf_token %}
<input type="text" name="search_text" class="form-control" id="tokenfield" placeholder="Enter keyword" style="width: 50%" />
<button type="button" id="addKeyword-btn" class="btn btn-primary">Add</button>
My JQuery code.
$(function(){
//auto complete ajax code.
$('#tokenfield').tokenfield({
autocomplete: {
//source:['red','blue','green','yellow','violet','brown','purple','black','white'],
delay: 100
},
showAutocompleteOnFocus: true,
}).keyup(function(){
alert('key pressed');
$.ajax({
url: "/user_account/auto_complete_search/",
type: 'POST',
data: {
'search_text': $('#tokenfield').val(),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: function(data){
console.log(data)
},
dataType: 'text'
});
});
});
});
Django View
#This is the function that handle the auto complete search functionality.
def autocomplete_search_view(request):
if request.method == 'POST':
search_text = request.POST['search_text']
else:
search_text = ''
keywords = Keywords.objects.filter(keyword__icontains=search_text)
#data = serializers.serialize('json', keywords, fields=('keyword'))
return HttpResponse('Query completed', content_type='application/text')
user_account/urls.py
url(r'^auto_complete_search/$', autocomplete_search_view, name='autocomplete_search'),
The error from the browser.
What am I doing wrong here?
After a very long time of searching for the answer, I eventually got it right. see the code below. I'm trying to figure out how to make the dropdown menu scrollable but code below does exactly what I wanted.
$('#tokenfield').tokenfield({
autocomplete: {
source: function(request, response){
if(request.term.length >= 5){
$.ajax({
url: "/user_account/auto_complete_search/",
type: 'POST',
data: {
'search_text': request.term,
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: function(data){
if(data != ""){
var dataArr = [];
$.each(data, function(i, jsonObj){
dataArr[i] = jsonObj.fields.keyword;
});
response(dataArr);
}
else{
response([]);
}
},
dataType: 'json'
});
}
else{
response([]);
}
},
delay: 300,
},
showAutocompleteOnFocus: true
});
Django view.
#This is the function that handle the auto complete search functionality.
def autocomplete_search_view(request):
if request.method == 'POST':
search_text = request.POST['search_text']
else:
search_text = ''
return HttpResponse([{}], content_type='application/json')
keywords = Keywords.objects.filter(keyword__icontains=search_text)
data = serializers.serialize('json', keywords, fields=('keyword'))
return HttpResponse(data, content_type='application/json')
The HTML is still the same. Hope this helps somebody in the future.

how can append db values to a href (phonegap)

this my html page nextPage.html
im lookig to display db values category_id, category_name which are from php controller in my html page. By clicking on category_name i want to go to the next html page and also my category_id will be passed to that page
pls help me.....pls
</div>
<div data-role="main" class="ui-content">
<form id="nextForm" >
<ul data-role="listview" data-inset="true" id="category">
<li>
<a></a>
</li>
</ul>
</form>
</div>
my js is nextPage.js
var base_url = "http://dev.edfutura.com/nithin/jps/edfuturaMob/";
$(document).on("pageinit", "#catlist", function() {
var submitUrl = base_url + "categorylist/get_categorylist";
//$("#loading").css("display", "block");
$.ajax({
url: submitUrl,
dataType: 'json',
type: 'POST',
success: function(response) {
// do something pls
},
error: function() {
alert("error");
}
});
controller categorylist.php
function get_categorylist() {
$cat = $this - > categorylist_model - > get_cat();
echo json_encode($cat);
}
You can save data in sessionStorage and paint it when you want:
var session = (typeof(Storage) !== "undefined") ? window.sessionStorage : null;
$.ajax({
url: submitUrl,
dataType: 'json',
type: 'POST',
success: function(response) {
if(session) {
// fill here data that you want
session.setItem("data", response.data);
}
},
error: function() {
alert("error");
}
});
To read it:
if(session) { alert(session.getItem("data"); }
Good luck

Ajax Serialize Post not working with Django, Django doesn't see data

I have a three part question:
Part 1: I'm trying to use Ajax to serialize data to Django and return values in real time, right now my ajax is just on form submit, but the part3 question will be in regards to that. Right now django doesn't receive the post data and the console message I have to see if its success or failure aren't displaying in the console. Here is my code:
<script type="text/javascript">
var frm = $('#get_info');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
//$("#SOME-DIV").html(data);
console.log('done');
},
error: function(data) {
console.log('something went wrong');
//$("#MESSAGE-DIV").html("Something went wrong!");
}
});
return false;
});
</script>
The browser bar changes to:
http://127.0.0.1:8000/vmstatus/?csrfmiddlewaretoken=HApMk9LWlxNUdlJaD4kj0WZkCTki4hin&selected_customer=35&vm_status=Get+VMs+Status&user=True
part 2: is this safe to have the middlewaretoken displayed like that and the customer_id?
part 3: how do I set this ajax function up on a time to post every 1 minute?
obviously the serialize is getting the correct data, or it wouldn't be displayed in the url post bar correct? So what am I doing wrong why is django not getting the post or acting on it?
views.py
if request.method == 'POST':
posted_data = request.POST.copy()
customer_id = int(posted_data['selected_customer'])
for customer in customers:
if customer.customer_id == customer_id:
selected_customer = ((decrypt('secretkey', customer.customer_name), int(customer.customer_id)))
customer_list.append((decrypt('secretkey', customer.customer_name), int(customer.customer_id)))
Made some modifications based on a comment. The form is successfully serializing the data now but still no django returned.
Here is the working code where the console outputs done as it was successful and the url doesnt change anymore, so I know its doing a post. However, Django still doesn't return info.
<script type="text/javascript">
$(document).ready(function() {
$('#get_info').submit(function() {
$.ajax({
type: $('#get_info').attr('POST'),
url: $('#get_info').attr('action'),
data: $('#get_info').serialize(),
success: function (data) {
console.log('done');
},
error: function(data) {
console.log('something went wrong');
}
});
return false;
});
});
</script>
I just saw a youtube video of a guy doing it like the following:
<script type="text/javascript">
$(document).ready(function() {
$('#get_info').submit(function() {
$.ajax({
type: "POST",
url: "/vmstatus/",
dataType: "json",
async: true,
data: {
csrfmiddlewaretoken: '{{csrf_token}}',
selected_customer: $('selected_customer').val()
},
success: function (json) {
console.log('done');
setInterval(returnData, 5000);
console.log(json);
},
error: function(json) {
console.log('something went wrong');
console.log(json);
}
});
return false;
});
});
var returnData = function () {
$.ajax({
type: "POST",
url: "/vmstatus/",
dataType: "json",
async: true,
data: {
csrfmiddlewaretoken: '{{csrf_token}}',
selected_customer: $('selected_customer').val()
},
success: function (json) {
console.log('done');
console.log(json);
},
error: function(json) {
console.log('something went wrong');
console.log(json);
}
});
};
</script>
for some reason though it says something went wrong. I'm not sure what im doing wrong with the ajax.
here is my form
<form id='get_info' name='queryForm'>
{% csrf_token %}
<div class="container-fluid">
<div class="row">
<center>
<div class=".col-xs-6 .col-md-4" >
<table cellpadding='10' id='table-data' class="table table-striped" >
<tbody>
<td align='left' style='font-weight: bold;' {%if date_values %}width='20%'{%else%}width='50%'{%endif%}>Customer Select</td></tr>
<td width='200' align='left'>
Customer: <select name='selected_customer' style='width:200px;' id='selected_customer'>
{% if user.is_superuser == True %}
{% if selected_customer %}
<option name='selected_customer' value="{{selected_customer.1}}" selected>{{selected_customer.0}}</option>
{%else%}
<option name='selected_customer' value='0' selected>Select Customer:</option>
{%endif%}
{%for customer in customer_list%}
<option name='selected_customer' value="{{customer.1}}">{{customer.0}}</option>
{%endfor%}
{%else%}
{%for customer in customer_list%}
<option name='selected_customer' value="{{customer.1}}">{{customer.0}}</option>
{%endfor%}
{% endif %}
</select><br><br>
<input type='submit' name='vm_status' value='Get VMs Status' style='width:270px;' class="btn btn-success" data-toggle="tooltip" data-placement="left" title="Retrieve the status of your VMs">
</td>
</table>
</center>
</div>
</div>
</div>
</form>
updated views
posted_data = request.POST.get("selected_customer", "")
video i watched https://www.youtube.com/watch?v=sYNDXrLu57k

Categories

Resources