reload page after processing javascript output in flask - javascript

I have a javascript snipped which uses ajax to send an email address to my flask views.py script. I want to send a message to that address if the email is not in my database or otherwise reload the website and show the user information for that email address. Here is my javascript code which sends the data to my views.py
<script type='text/javascript'>
$(".send_invite_message").click(function(evt) {
var Toemail = document.getElementById('To').value
$.ajax({
url: "/send_invitation_member",
type: "GET",
async: true,
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: { email: Toemail},
success: function(data) {
///do something
},
});
});
</script>
and in flask I would like to now have the option to send an email and if the email already exists in the database to reload the site
#app.route('/send_invitation_member', methods=['GET'])
def send_invitation_member():
if request.method == 'GET':
email = request.args.get('email')
search_result = check database for email entry
if search_result:
return render_template('show_members.html')
else:
send message and return json object
However the ajax script expects a json object back, so I don't know how to reload the site and show the user information. Is there any way to do this directly in flask or do I need to extend my javascript code and load the site from there?
thanks
carl

Since there's no way for an AJAX response to directly affect the page that's calling it, you'll need to extend your javascript a little (but only a bit).
In your success function, let's add the following:
success: function(data) {
if (data['url'] != null) document.location = data['url'];
else console.log('Got a valid JSON response, but no URL!');
}
This code will redirect the page to where the JSON specifies with its 'url' key. Now all that's left is to add it to our Flask code.
#app.route('/show_members')
def show_members():
return render_template('show_members.html')
#app.route('/somewhere_else')
def some_other_route():
return "It all works!"
#app.route('/send_invitation_member', methods=['GET'])
def send_invitation_member():
email = request.args.get('email')
search_result = check database for email entry
if search_result:
destination = url_for('.show_members')
else:
destination = url_for('.some_other_route')
send message and return json object
return Response(response=json.dumps({'url': destination}, mimetype='text/json')
I find when using flask it's better to separate your routes out into different functions depending on the HTTP method. And the url_for method? It's a life saver. You can find its docs here http://flask.pocoo.org/docs/0.10/api/#flask.url_for

Related

How to get response back from the REST API and perform actions from jquery ajax call?

I am learning JS, jquery, and trying to build a login page and after giving the credentials to my application URL I should get a response back and I should be able to perform actions accordingly.
Something like: if the response is "success" then I should get an alert for success and redirect to another page (not sure how to do that) and if the response is "fail" I should throw an alert.
Below is the relevant snippet from my js file:
$.ajax({
url: "http://localhost:8588/api/userLogin",
type: "POST",
data: credentials,
dataType: "json",
contentType: 'application/json',
success: function(response) {
alert(response);
}
});
And my java controller method snipped annotated with #RestController:
#PostMapping(value = "/userLogin", consumes = "application/json")
public String userLogin(#RequestBody UserRequest userRequest) {
System.out.println(userRequest.getUserId()+ " "+ userRequest.getPassword());
User user = userService.getUser(userRequest);
return (user != null) ? "succeess" : "fail";
}
I am not getting any error
I am able to call the API but not getting the response back on UI. What am I missing?
I've taken your code and simulated simple case like yours. Most of the code looks right but as you've said there are no errors in the console and no response to client so there's problem got to be somewhere. There are certain things you've not specified here, so for more context for other people I am assuming UserRequest as
public class UserRequest {
public String username;
public String password;
}
and for the ajax request data I'm using
JSON.stringify({username: "developer", password:"pass"})
Now, I'm getting 200 response code with success message in alert at client side. Let me know if any error pops up after trying this.

Updating page elements immediately on input changes with django and AJAX inside GET request

I want to update elements in the page to tell a user in real-time how many objects will be affected by their choice of criteria in a form.
For an example to work with, the form asks for a number and the django logic will delete any model instance with a pk less than that value once the submit button is clicked - but before clicking the user wants to know how many they will be deleting:
<span id="number-changed">NULL</span> objects will be deleted
so the end result I want is that #number-changed will be populated by a value like MyModel.objects.filter(pk__lt=input_number).count().
I have set up an AJAX call on changes to the input via:
$("input").change( function() {
$.ajax({
type: "GET",
url: "{% url 'myapp:bulkdelete' %}",
data: {
csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
},
success: function (data) {
// code to update #number-changed
}
I am wondering how I implement in the view so that on successful GET the success function can use the value I retrieve. Some pseudo-code:
# views.py
class MyView(FormView):
# ...
def get(self, request, *args, **kwargs):
input_number = ???
number_changed = MyModel.objects.filter(pk__lt=input_number).count()
# presumably some super().get() call here
return ???
Questions:
Can I retrieve the current input_number via request or does it need to be passed as a url parameter when making the AJAX request?
How can I add my required information, number_changed in this case, to the return of the get() method, and how to access this inside success?
The way I have implemented AJAX with django before has being using POST requests and I simply return a JsonResponse with my required data. However, an initial get() is called when loading the page and needs to return a full HttpResponse - so ultimately is there a way to add my additional information into this, or am I going about it completely wrong.
An Ajax request is exactly the same as any other request from the point of view of the server. You can just include the data in the querystring, which you then access in the view via the request.GET dict.
jQuery will generate that querystring for you from the data parameter; note, you don't need a csrf token for a GET request. So:
type: "GET",
url: "{% url 'myapp:bulkdelete' %}",
data: {
input_number: $(this).val(),
},
...
And in the view:
def get(self, request, *args, **kwargs):
input_number = request.GET["input_number"]

How to access data passed into Flask with an AJAX call?

I am working on a project that displays hotel and airbnb data using flask and a sql database. We are trying to create a "favorite button" so the user can favorite/unfavorite listings. I've got an AJAX call to a Flask endpoint that will the make corresponding SQL queries to the "favorites" table. My problem is, I can't seem to access the data I'm passing into Flask.
Here is my AJAX call on the client-side:
function unfavoriteClicked(uid, itemid, type){
$.ajax({
type: "POST",
url: "/unfavorite",
data:{uid:uid, itemid:itemid, type:type},
contentType: 'application/json;charset=UTF-8',
success: function(data) {
console.log(data);
},
error: function(jqXHR) {
alert("error: " + jqXHR.status);
}
});
}
And here is my Flask code:
#app.route('/unfavorite', methods=["GET","POST"])
def unfavorite():
if request.method == "POST":
return request.form
return "this shouldn't happen"
Note that I've taken the SQL logic and other things out since I've figured out that I am not accessing the data correctly in Flask.
I am sure that the AJAX request goes through, because when I return something like "hello", it shows up in the console log. However, when I try to access the data dictionary I'm passing in, it returns a "500 internal server error" or some other kind of error depending on what I'm trying to access. I've tried to access a bunch of different things from looking at other stackoverflow posts (like request.form['data'], request.data, request.args, etc) but nothing seems to allow me to access the data. However, it does seem to allow me to access "request.method".
I was wondering if there is something fundamental that I am missing here that would be a reason why I cannot pass in data to Flask? Or any other suggestions for doing this "favorite" button are appreciated. Thanks!
So considering the main issue that you want to tackle is accessing the data that is been passed by your web page using Ajax. I have a solution which might work in your case.
So there are two parts in which i will explain how you can solve this problem.
1) Passing the data to your python controller/function to further process the data.
$.post("url_to_which_you_want_to_pass_data", {variable_name_to_access_in_python:any_value/variable_from_front_end},
function(response, status){
call_back_function_code
});
2) Accessing the data that has been passed from the webpage in python flask
#app.route('/unfavorite', methods=["GET","POST"])
def unfavourite:
if request.method == "POST":
any_variable_name = request.form.get("variable_name_to_access_in_python","")
print(any_variable_name) #If you want to print
return any_variable_name #If you want to see any_variable_name on web
return None
Hope it Helps! Cheers :)
I don't know if it's the best option, but its worked for me.
JavaScript:
var data = [1, 2, 3, 4]
var frontend_data = {'list':data}
$.ajax({
url: "/unfavorite",
contentType: 'application/json',
type: "POST",
data: JSON.stringify(frontend_data),
dataType: 'json',
success: function(result) {
console.log("Result:");
console.log(result);
}
});
Flask:
#app.post('/unfavorite')
def unfavorite():
data = request.get_json()
print(data['data']) #[1, 2, 3, 4]
return jsonify(data)

AJAX not changing/redirecting from login page to dashboard [flask backend]

I am using the post method for the login. My ajax function sends the data successfully to my flask backend server [I know because it returns a response to my ajax]. Supposedly, after receiving the respnse from the backend, my ajax success handler will navigate/redirect to the dashboard page but IT DOES NOT! How do I make it navigate/redirect to another page/url?It returns a 200 status code so I do not know why it does not display the dashboard page.
WHAT I HAVE TRIED:
I have tried using window.location.href, window.location.replace but to no avail, still it does not work. I have also tried changing the method to GET but its still the same. I have also set async to false because ajax would not post if I would not set it to false.
AJAX
$.ajax({
type: "POST",
url: 'http://127.0.0.1:5000/processlogin',
data: JSON.stringify(loginobject),
contentType: "application/json;charset=utf-8",
async: false,
success: function (resp) {
window.location.href = ("http://127.0.0.1:5000/dashboard");
},//success
failure: function (resp) {
alert(resp.message);
}
});
backend flask functions
This functions work 100%. Already tested it with POSTMAN. I have also queried the database using my stored procedure and it does well.
This displays the login form
#app.route('/', methods=['GET','POST'])
def login():
return render_template('login.html')
This processes the ajax's sent data. In short this is the function ajax is communicating with
#app.route('/processlogin', methods=['POST'])
def processlogin():
loginobject = request.get_json(force=True)
username = loginobject['username']
password = loginobject['password']
try:
dbpassword = callstoredproc("getpassword", (username,))[0][0]
if dbpassword == 'null':
return jsonify({'status':'error', 'message':'Username does not exist!'})
elif bcrypt.verify(password, dbpassword) == True:
return jsonify({'status':'ok'})
except Exception as e:
print(e)
And this is what I am trying to display: the dashboard html
#app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
return render_template('dashboard.html')
Remove the curved brackets and try again:
window.location.href = "http://127.0.0.1:5000/dashboard";
It works also with curved brackets so just be sure that your response arrive correctly to the success callback.
See also best answer on SO.
It should also be error instead of failure as error callback.
error: function (resp) {
alert(resp.message);
}
jsfiddle Example

Using a URL as a URL parameter in Django Rest Framework

I have a model whose unique field is an address. The thing is, I am trying to get instances of this model using AJAX.
var address = 'http://example.com/blog/2/';
$.ajax({
url: 'http://sitemy.com/api/get_content/'+encodeURIComponent(address),
type: 'GET',
dataType: 'json',
success: function(json) {
console.log('Success');
}
});
In my urls.py, I have the following code:
url(r'^api/get_content/(?P<url>.+)/$', views.get_content),
So I am trying to use this URL pattern to capture the get request. However, I am constantly getting a 404 error since the url sent from the request does not match my pattern. What gives? How can I solve this?
In case its important, in my views, I am doing the following:
def get_content(request, address):
try:
content = Content.objects.get(address=urllib.unquote(address))
except:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = ContentSerializer(content)
return Response(serializer.data)
Any help would be appreciated. Also, I welcome any general advice regarding the encoding of URLS, as that just boggles my mind for some reason. Thanks.

Categories

Resources