I'm doing a chat app in python Django and I Want to implement Link preview while typing that ink in chat box. Anybody familiar with this please help.
You can use a Link preview API service - [1]: https://www.linkpreview.net/
Try this code .
$.ajax({
url: "https://api.linkpreview.net",
dataType: 'jsonp',
data: {q: "message URL", key: 'your API key'},
success: function (response) {
let data=response;
console.log(data);
}
});
Related
I'm using Flask and JQuery to try to achieve this but pls feel free to suggest any other stack(React/Angular) if that's super easy.
I have the below AJAX in a poll.js file
$(document).ready(function(){
$('#poll').click(function(){
$('#poll').text("Working...")
$.ajax({
url: '/poll',
data: $('form').serialize(),
type: 'GET',
success: function(response){
console.log(response);
$('#poll').text("Poll")
},
error: function(error){
console.log(error);
$('#poll').text("Poll")
}
});
});
});
and my poll function in app.py is as below:
#app.route('/poll', methods=['GET'])
def poll():
call an api and return the json response
now on the UI if i click the poll button its text changes to working and it calls the function which eventually hits the API.
While this is happening, if click the home menu or navigate elsewhere on the page, i loose the AJAX call.
How do i make the ajax call continue working i.e. calling the api and updating the UI even if we try to redirect to another page or click anywhere else?
I suggest to load the data on initial page load and then refresh after set interval. to achieve this following should give you a kick start
<script type="application/javascript">
jQuery(document).ready(function($){
/* change this
$('#poll').click(function(){
$('#poll').text("Working...")
$.ajax({
url: '/poll',
data: $('form').serialize(),
type: 'GET',
success: function(response){
console.log(response);
$('#poll').text("Poll")
},
error: function(error){
console.log(error);
$('#poll').text("Poll")
}
});
});
*/
//to this it will start with page load and refresh $('#poll') every 5 seconds
var setInt = setInterval($(function(){
$('#poll').text("Working...")
$.ajax({
url:'path to script',
data: $('#form').serialize(), //your html must have form with id="form" for this
type: 'GET',
success: function(response){
console.log(response);
$('#poll').text("Poll")
},
}).fail(function(xhr,ajaxOptin,thrownError){
//console.error(xhr.responseText);
console.error(thrownError);
});
}), 5000);
});
</script>
What I Am Trying To Do: Receive data from AJAX to Flask. Eventually, I would like to send token data (Which will come from stripe) to the flask side
The Problem: I can't print any data to the console. So I'm assuming data is not being passed through.
I am unable to receive data from my Ajax call. I have been searching for some time now and I haven't found a fix. I've seen multiple different solutions for others but none of them worked for me. I'm am trying to implement a custom Stripe payment flow.
What I plan to do eventually is to pass in all the data I need (in the token) through the 'data' parameter in JSON format. Here are the different sides of code
index.html
var handler = StripeCheckout.configure({
key: 'test_key',
image: 'image_url',
locale: 'auto',
token: function(token) {
$.ajax({
url: '/charge',
data: {
'token': '(data im trying to access/print in app.py)'
},
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log("ERROR");
console.log(error);
},
dataType: "json",
contentType: "application/json"
});
}
});
app.py
from flask import Flask, request
import json
#app.route('/charge', methods=['POST'])
def charge():
# Grab token information
token = request.form['token']
# The line below never prints to console
print(token)
# This test print statement below never prints to console
print("This print statement never runs")
Nothing prints to the console. I've wasted so much time on this so any leads or pointers would be greatly appreciated!
UPDATES
I did some updates suggested by #Daniel Roseman but nothing at all prints to the console.
Try the following code
In javascript:
var data = {token: token}
$.ajax({
url: '/charge',
data: JSON.stringify(data),
type: 'POST',
success: function (response) {
console.log(response);
},
error: function (error) {
console.log("ERROR");
console.log(error);
},
dataType: "json",
contentType: 'application/json;charset=UTF-8',
});
In controller [charge method]:
from flask import Flask
from flask import render_template, request, jsonify
#app.route('/charge', methods=['POST'])
def charge():
# Grab token information
token = request.json['token']
# This is the expected token from json
print(token)
# This test print statement below now prints to console
print("This print statement now runs surely")
# return JSON
return jsonify(
code=0,
msg="Success"
)
You're not posting JSON.
Instead of accessing request.get_json(), you can just access the individual elements from the request.form dictionary. In this case:
token = request.form['token']
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 want to send an email from python using the below codes i wrote/reffered
<script>
$(document).ready(function() {
$("#form1").submit(function(){
$("#form1").validationEngine();
if($('div input[type=text]').val() != "")
{
var textfield2=document.getElementById("textfield2").value;
var textarea=document.getElementById("textarea").value;
var dataS=$("#form1").serialize();
$.ajax({
type: "POST",
crossDomain: 'true',
url: "mail.py",
success: function( ){
alert("completed");
},
error: function(){
alert(dataS);
}
});
}
return false;
});
});
</script>
For the mail part , i reffered the below google code
from google.appengine.api import mail
mail.send_mail(sender="Example.com Support <support#example.com>",
to="Albert Johnson <Albert.Johnson#example.com>",
subject="Your account has been approved",
body="""
Dear Albert:
Your example.com account has been approved. You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.
Please let us know if you have any questions.
The example.com Team
""")
Now the question is , on ajax call .. How can i recieve the HTML parameters in the mail.py script? pls help i'm new to python
Within a cgi script, if you instantiate a cgi.FieldStorage(), it is automatically filled with the GET or POST parameters. If you want to post content, then just add a data property to your ajax request object:
$.ajax({
...
data: {param1: 'value1', param1: 'value2', ...}
...
})
In your python script it should the be enough to do:
import cgi
store = cgi.FieldStorage()
par1 = store.getfirst('param1')
...
One more thing -
Ask yourself: do you really want to submit the form when the page is loaded? (Your're using the 'ready' event). Wouldn't it be better to wait until somebody has entered somehting in the form?
My Ajax code:
var upfile = $("#file-id").val().split(/[\/\\]/).pop();
$.ajax({
type: 'POST',
url: '/upload/',
data:{"upfile":upfile},
success: function(data) {
if (data['success'] === "true") {
}
},
dataType: 'json'
});
return false;
Django code:
In simple form submit action request.FILES.get('upfile') works. I can read the content of file using read() But in ajax, it is not working. even request.POST.get('upfile') gives me the filename string.
How to solve this issue?
It's normal, by default a form submitted with Ajax will not upload files. You need o have a look to some file upload jquery plugins (there's a few of them, I can not suggest one as I did not try any of these yet)