I wanted to use facebook's like button for voting on my page. Unfortunately when 'Like' is clicked I get 3-5 requests to my function instead of only one. Is there a way to prevent this ?Sample code:
FB.Event.subscribe('edge.create', function(href, widget) {
console.log(href, widget);
});
My code:
FB.Event.subscribe('edge.create', function(href, widget) {
$.ajax({
type: "POST",
url: "/votes/register",
data: "href="+href,
dataType: 'json',
success: function(data){
$(".list-submissions").html(data["html"])
}
});
return false;
});
Or maybe I can block this from the function's side using django ? Here's my function code:
def register_vote(request):
ip = request.META['REMOTE_ADDR']
url = request.POST.get("href", "")
id = os.path.basename(url)
try:
vote = Vote.objects.filter(ip=ip, id=id)
except:
vote = None
if not vote:
vote = Vote(ip=ip, uid=id)
vote.save()
html = render_finalists(request)
ajax = simplejson.dumps({
"html": html
}, cls=LazyEncoder)
return HttpResponse(ajax, mimetype='application/javascript')
I do facing slightly same issue, have been creating like buttons on the fly using AJAX, specific to the content but 'edge.create' some how storing the event and incrementing the edge.create events and firing multiple times when I click on another FB like widget.
Have bee hitting my head so badly, no luck till yet :(
Any quick help, should be appreciated.
Finally I cracked it, just compared the response which I was getting from the response object to the one which I needed to pass and that works.
FB.Event.subscribe('edge.create', function(response) {
if ( response.toString() == shareUrl.toString() ) {} }
You might get multiple requests to you callback function if the Facebook core JS SDK has been referenced multiple times, i.e. the following script tag (or variations) are more than once:
<script src="http://connect.facebook.net/en_US/all.js"></script>
Related
I am using navigator.geolocation to get an update on location with it's provided watchPosition function with following code:
function updatePosition() {
if(navigator.geolocation) {
navigator.geolocation.watchPosition(calculateDistance);
}
else {
console.log("Geolocation is not supported by this browser.")
}
}
If then new location coordinates I fetch is under a kilometer in distance, I issue a post request and try to render another view. I use google maps API to calculate the distance with function computeDistanceBetween. Here is the code:
function calculateDistance(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var dis = google.maps.geometry.spherical.computeDistanceBetween(pos, mapOptions.center);
if(dis <= 1000 && dis >= 0 && rendered == false) {
var url = '/app/near_park/';
var csrftoken = getCookie('csrftoken');
$.ajax({
url: url,
type: "POST",
data: {
csrfmiddlewaretoken: csrftoken,
in_proximity : 1
},
success: function() {
rendered = true;
console.log("Success");
},
error: function(xhr, errmsg, err) {
console.log(xhr.status+": "+xhr.responseText);
}
});
}
}
Here is the view handling the post request:
def index_close(request):
context_dict = {}
try:
current = Owner.objects.get(user=u)
context_dict['checked_in'] = current.checked_in
except:
context_dict['checked_in'] = False
print("##########")
#return redirect(reverse('app:register'))
return render(request, 'app/index_close.html', context=context_dict)
Whenever I get a location update using the sensor utility of dev tools, I do see the print of hash marks on terminal but the redirect or render both do not work. The problem is not the index_close.html because I tried already existing and working html's also . None worked. The problem is this freaking render or redirect line that does not work. I have read numerous posts and solutions to similar problems but none worked for me. Can anybody spot the problem?
I have many POST requests and all redirect or render the html , I have a full working app. I was just adding this new feature to dynamically render new UI on location update via AJAX Post request, but it does not work.
I was looking for a way to use HTML5 (and possibly JS) to save visitor/user Longitudnal & Latitudnal data to a database. I do not wish to use packages out there as they seem a bit outdated and may break my code in future considerting their own reliance on other APIs.
I know there is a way around using AJAX, but I clearly dont know and understand it well enough to implement it.
My ask of the learned Lords is - 1. Get Loc data 2. Send it to Python in dict or json or string format from where it can be further processed and saved.
Why you may ask - Good question. I would use it for displaying weather on the homepage and local twitter trends on a 'logged-in' page.
Any assistance would be appreciated.
Cheers!
My JS code is below:
// Set up global variable
var result;
function showPosition() {
// Store the element where the page displays the result
result = document.getElementById("result");
// If geolocation is available, try to get the visitor's position
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
result.innerHTML = "Getting the position information...";
} else {
alert("Sorry, your browser does not support HTML5 geolocation.");
}
};
// Define callback function for successful attempt
function successCallback(position) {
result.innerHTML = [position.coords.latitude, position.coords.longitude];
}
// Define callback function for failed attempt
function errorCallback(error) {
if (error.code == 1) {
result.innerHTML = "You've decided not to share your position, but it's OK. We won't ask you again.";
} else if (error.code == 2) {
result.innerHTML = "The network is down or the positioning service can't be reached.";
} else if (error.code == 3) {
result.innerHTML = "The attempt timed out before it could get the location data.";
} else {
result.innerHTML = "Geolocation failed due to unknown error.";
}
}
window.onload = showPosition;
what works for me:
First I recommend you to use models.PointField on your model.
When I obtain the long/lat data on FE, I send it as form-data in the following format eg:
"{\"type\":\"Point\",\"coordinates\":[14.215641,50.0100000001]}"
Then I map it to the model field and save it. It saves well and later I am able to query google geocoder or anything with it.
In your JS code:
function successCallback(position) {
result.innerHTML = [position.coords.latitude, position.coords.longitude];
$.post('your-python-endpoint-url', {
latitude: position.coords.latitude,
longitude: position.coords.longitude
});
}
In your python:
def index(request):
if request.is_ajax():
if request.method == 'POST':
print 'Raw Data: "%s"' % request.body
return HttpResponse("OK")
Change the method name and body according to your needs and don't forget to define a route in django.
I have a JQuery event that, when a link is clicked, an AJAX POST request is sent to a Django function. There I print the recieved url and do other stuff with it. However, when it is printed (by Django) some characters in the url are changed.
The specific url this happened with was :
https://www.catholicleague.org/05press_releases/quarter%204/051110_put_on_notice.htm
Which was printed as :
https://www.catholicleague.org/05press_releases/quarter+4/051110_put_on_notice.htm
Where %20 was changed to +
Here is the AJAX and Django code:
$("a").on("click", function(e){
e.preventDefault();
if(e.target.href){
let clicked_source = e.target.href;
let csrf_tok = parent.document.getElementById("csrf_tok").value;
$.ajax({
url: "/change_origin/",
data: JSON.stringify({"clicked_source":clicked_source}),
type: "POST",
beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrf_tok );},
success: function(response) {
console.log(response.msg)
},
error:function(error) { console.log(error); }
});
}
});
def change_origin(request):
if request.method == 'POST':
received = ast.literal_eval(request.body.decode())
print(received)
clicked_source_url = received['clicked_source']
return JsonResponse({'msg': "ok"})
Where decode is used as the JSON object is received in Python as a byte-like object. And ast is used to turn the string representation of the object to an actual object (or dict) for access.
I need either:
1) A way to just send a string from Ajax to Django
2) A better way to deal with the received object as I believe using .decode() might be the one causing this issue.
EDIT: The link is the second link in the "origin" part of this article
https://www.snopes.com/fact-check/an-unmerried-woman/
I have middleware, that stores all http requests into DB.
Also I have view, that fetches data from DB and put this data into the context.
views.py
def requests(request):
http_requests = WebRequest.objects.all()
context = {
"http_requests": http_requests
}
return render(request, "requests.html", context)
How can I asynchronously update data on this page as new requests come in (so, new requests should appear on this page asynchronously)? Can I use only Django features to achieve such behavior or I need to use some javascript libraries?
It depends on how much time you want to spend on the project. As Lorenzo stated, it might make sense to create an API and have javascript-frameworks (e.g. emberjs or angularjs) handle the asynchronity. I dont think you can handle this with pure django...
If you don't have time and are in for some 'hack' you could just replace the content of your page by polling the url and replacing the whole document with the response:
$.ajax({
type: "GET",
url: "<url_to_your_requests_view>",
success: function(response){
$('body').html(response);
}
});
This is NOT clean, but should work as a quick an dirty trick...
EDIT: If you only want to exchange certain parts of your site, you can break it down to just add elements to the page:
$.ajax({
type: "GET",
url: "<url_to_your_requests_view>",
success: function(response){
var newlyAddedRows = // find your newly added rows through some jquery
newlyAddedRows.forEach(function(row){
$('#request-holder').append(row);
});
}
});
OR WITH JSON
$.ajax({
type: "GET",
url: "<url_to_your_requests_api_endpoint>",
success: function(response){
var requestRows = response.requestItems
var $requestsHolder = $('#request-holder');
$requestHolder.empty();
requestRows.forEach(function(row){
requestsHolder.append('<div class="request-row">' + <visualize your data somehow> + '</div>'); //e.g. row.timestamp if you have that in your json
});
}
});
I've passed the last 5 hours trying to find a solution that's been bugging me since yesterday. I am writing some BDD tests using behave and selenium to test the product addition functionality of my web app.
So to add a product the user have to click on a button which will launch a dialog box containing the form that will allow him to fill in the details of the product he wants to add. When the user clicks on submit the dialog box disappears and a JS code updates a datatables table with the new product using an Ajax request.
When I launch my test selenium finds the product addition form and fill in the details I provided, the problem is that when it clicks on submit basically nothing happens, my JS code isn't executed. Here's the behave code that submits the form:
#when(u'I click on Add new product')
def subscribe_click(context):
context.browser.find_element_by_id('add-submit').click()
and what follows is the JS function that really handles the form submission
function submitEditForm(form, upload_data)
{
data_serialized = $(form).serializeArray();
data = {
'csrf_token': data_serialized[0].value,
'name': data_serialized[1].value,
'description': data_serialized[2].value,
'price': data_serialized[3].value,
'image': upload_data.data ? upload_data.data.image : ""
};
$.ajax({
type: "PUT",
url: "/api/products/"+row_data[0],
data: data,
dataType: "json",
success: function(data) {
$("#edit-frm").fadeToggle("fast");
new_data = [
data['name'],
data['description'],
data['price'],
data['image']
]
$('#myTable').dataTable().fnUpdate(data.data, row_index, undefined, 1);
},
error: function (resp) {
$("#edit-frm").fadeToggle("fast");
alertify.alert("There was a problem with your request please try again.")
}
});
}
So what I want to is: is selenium even capable of running Ajax requests? And if that's not the case what do I need to do so that my test works??