Progress Bar depending on progressing in backend in django - django

I am using django template and i have a button , when user click on this some actions performed in backend. For that time period i want to show a progress bar. here is my code for that button.
$("#bulk_shortlist").click(function(){
data=$('#limit option:selected').val()
$.ajax({
url: "{{ settings.SITE_ADDR }}/hire/bulk_shortlisting/",
type: 'POST',
data: {
'limit': data,
'id': {{ job_id }},
'functional_area': options["functional_areas"],
'min_exp':options["min_exp"],
'max_exp':options["max_exp"],
'min_sal':options["min_salary"],
'max_sal':options["max_salary"],
'age_cond':options["age_cond"],
'gender':options["gender"],
'industries':options["industries"],
'languages':options["languages"],
'adskills':options["adskills"],
'location':options["location"],
'education':options["education"]
},
success: function(response1) {
alert(response1);
},
failure: function(response1) {
alert('Got an error ..... Pleas try again later ');
}
});
});
</script>
I am very new in django , please help me out . Thanks in advance.

Related

Django Paypal integration - Rendering button not working when changing language

I've integrated Paypal to my website and everything worked as expected. However when i added a new language (greek) i got a problem when pressing pay with paypal button. When change back to english everything works and button is rendering with no probs.
The error i got from paypal is:
Code i'm using:
<div id="paypal-button-container">
<!--Paypal button will load-->
</div>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
style: {
color: 'blue',
shape: 'rect',
label: 'pay',
height: 40
},
// Set up the transaction
createOrder: function(data, actions) {
console.log('kostas');
console.log(actions);
return actions.order.create({
purchase_units: [{
amount: {
value: amount,
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Show a success message to the buyer
console.log(details);
sendData();
function sendData() {
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify ({
orderID: orderID,
transID: details.id,
payment_method: payment_method,
status: details.status,
}),
})
.then((response) => response.json())
}).render('#paypal-button-container');
Since is the first attempt to work with paypal i would appreciate any help if you can give me any hint on the below error or any idea on how to troubleshoot.
Many Thanks
when i added a new language (greek) i got a problem when pressing pay with paypal button.
You don't show the code you are adding, so it's impossible to say what specifically is triggering the error, but it appears it may be something in the order creation call, which is not the correct place for changing button text.
To change the language of the buttons to something other than the default (auto-detected based on the browser's language), use the locale query string parameter on the SDK src line.
Here is the documentation: https://developer.paypal.com/docs/checkout/reference/customize-sdk/#locale

Pass an ID from Ajax to a Django view

I have a Django view that accepts an ID and returns a Json Response. Now on Ajax, I want to call the django view with an ID.
Here is my AJAX:
$(document).ready(function () {
$("#button").click(function () {
var id = 25;
$.ajax({
type: "POST", # Added here. Now error message changed
url: "/account/check_id/"
data: {
id: id,
},
dataType: "json",
success: function (data) {
if (data.is_taken) {
alert("ID is available");
}
},
});
});
});
Additional Data:
url:
path('check_id/<int:id>/', hrViews.check_id, name='check_id'),
view:
def check_id(request, id, *args, **kwargs):
However, when I click on button, I get error message
GET http://localhost:8000/account/check_id/?id=25 404 (Not Found). The ?id= is causing the error. How to remove it?
EDIT
After adding type: "POST", got message
POST http://localhost:8000/account/check_id/
How to pass ID here?
Note. Based on w3schools, the data{} is used to pass information to server. So I think that I should pass my ID here. However, my url does not get the ID from data. Please correct me on this if my assumption is wrong.
So I made some changes and this is what worked for me.
$(document).ready(function () {
$("#hold").click(function () {
var id = 25;
$.ajax({
url: "/account/check_id/" + id,
dataType: "json",
success: function (data) {
if (data.is_taken) {
alert("ID is available");
}
},
});
});
});
Removed the type: "POST", then concatinate on URL with my ID. It works so I will go with this based on my use case.

csrf error while trying to delete an object with ajax

I have all the objects from my db rendered on my template by an ajax function.
Near every object there's a button that should delete it from the db but since I'm working on Django it raise a csrf_token missing or incorrect error.
I'm not using a form so I don't know how to include the csrf_token.
var $orders = $('#orders')
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/MyApp/list-api/?format=json',
success: function(orders) {
$.each(orders, function(i, order){
$orders.append('<li>name: '+order.name+', drink:
'+order.drink+'</li>')
$orders.append("<button data-id=" +(order.pk)+"
class='remove'>X</button>")
});
},
error: function() {
alert('errore caricamento ordini');
}
});
$orders.delegate('.remove', 'click', function(){
$.ajax({
type: 'DELETE',
url: 'http://127.0.0.1:8000/MyApp/list-api/' +
$(this).attr('data-id')
});
});
When I press a remove button a new request appears in the network panel of the browser, the response states :detail: "CSRF Failed: CSRF token missing or incorrect." The console gives a 403 forbidden error.
Any help or hints are really appreciated.

flask endpoint for ajax call

I'm making an ajax call to my server while pressing submit button.
Button is present in page http://127.0.0.1:5000/post/15.
Jquery function invoked and the endpoint definition for submit_comment in python respectively:
function submit_comment(post_id) {
var uname = $('input[name="uname"]').val();
var comment = $('textarea[name="comment"]').val();
$.ajax({
url: "/submit_comment",
data: {name: uname, comment: comment, post_id: post_id},
method: "POST",
datatype: 'json',
success: function(response) {
console.log('reaches here');
addElement(response);
console.log('Is it me');
},
error: function(error) {
console.log('reached Error');
console.log(error);
}
});
}
py
#main.route('/submit_comment', methods = ['POST', 'PUT'])
def submit_comment():
entry = request.get_json(force=True)
print 'comment:', entry
....
Main is the blueprint. But I'm getting following 404 error.
127.0.0.1 - - [24/Aug/2017 10:30:55] "POST /post/submit_comment HTTP/1.1" 404 -
I am wondering from where this post got appended into the endpoint.
Can someone help me to understand the error and resolve it?
Thanks,
Deepak
I don't know a lot, but I know that the Flask docs on ajax say to query for the script root like this:
$SCRIPT_ROOT = {{ request.script_root|tojson }};
and then use that as part of the request URL.
An example from an ajax call I've used ($.getJSON being a jquery function for $.ajax)
$.getJSON($SCRIPT_ROOT + '{{ url_for("help_email") }}',

Migrating from twitter anywhere api

I m using twitter anywhere api for allowing user to sign in with twitter and get their twitter data to store it my table.Since twitter anywhere api is going to expire soon how can i migrate this functionality to oauth.
my javascript:
<script src="https://platform.twitter.com/anywhere.js?id={{twitterappid}}&v=1"></script>
<script type="text/javascript">
var twt_connected = 0;
var Uuid = '2334443224';
$(function(){
if ($('#twtlogin').length) {
// do something
twttr.anywhere(function(twitter) {
if(twitter.isConnected()){
//alert('Welcome, you are connected');
currentUser = twitter.currentUser;
screenName = currentUser.data('screen_name');
jQuery.ajax({url:"/twitter/Uuid="+Uuid+"/" ,
type: "POST",
data: {user: JSON.stringify(currentUser) },
dataType: "json",
success: function(result) {
}});
document.getElementById("twtlogin").innerHTML = '<img src="/images/icon_tconnected.gif" width="153" height="37" alt="Connected" />';
}
});
}
});
$("#login").click(function(e){
e.preventDefault();
if (twt_connected == 0){
$.post("/twt-click-time/Uuid="+Uuid+"/","clicked",function(data){})
twttr.anywhere(function (T) {
T.bind("authComplete", function (e, user) {
document.getElementById("twtlogin").innerHTML = '<img src="/images/icon_tconnected.gif" width="153" height="37" alt="Connected" />';
twt_connected = 1;
currentUser = T.currentUser;
screenName = currentUser.data('screen_name');
jQuery.ajax({url:"/twitter/Uuid="+Uuid+"/" ,
type: "POST",
data: {user: JSON.stringify(currentUser) },
dataType: "json",
success: function(result) {
}});
});
T.signIn();
});
}
});
</script>
I m using django at my backend.
I'm doing this right now for flask. The easiest option is just to plug-in some server side oauth calls.
It's a reasonably large amount of code so I won't copy and paste the whole thing here, but the github page for simplegeo's oauth2 actually has a "logging into django with twitter" walkthrough that should help out.
After having gone through a few options, I think I like twython best. It's just this to do the first step of the oauth:
from twython import Twython
t = Twython(app_key='key',
app_secret='secret',
callback_url='http://google.com/')
auth_props = t.get_authentication_tokens()
print auth_props