Flask, Ajax, get value in url for ajax url - javascript

In python, I have
#app.route('/update_account/<account_id>', methods=['POST'])
def update_account(account_id):
In html form, I have:
<form id="update_account_form" name="update_account_form" action="{{ url_for('update_account', account_id=account._id) | safe }}" method="POST">
URL: http://<domain>/edit_account/5b9fbe55fb6fc072da02e2f6
In AJAX, I have:
$(function () {
$('#update_account_form').submit(function (event) {
event.preventDefault();
account_id = 5b9fbe55fb6fc072da02e2f6
$.ajax({
url: '/update_account/'+account_id,
data: $('#update_account_form').serialize(),
type: 'POST',
success: function (response) {
My question is, how do I read the value of 5b9fbe55fb6fc072da02e2f6 from the url to use it in my AJAX call.
Do I use some jQuery regex system to read the url and work out the id, or is there some other clever way that I can pass the id from the html url via ajax to flask on the server side?

Use split after getting url.
$(function () {
$('#update_account_form').submit(function (event) {
event.preventDefault();
var url = window.location.href;
account_id = url.split("/").pop();
...........

Related

How to handle AJAX POST request in Django

I have a sort of twitter like button function in my app such that, when the button is clicked, it triggers an AJAX call and performs the action specified in the views. However, when i click the button, it does not perform action in views. The code reaches the 'like view' but does not execute anything after 'if request.POST:'. Please help.
Menu.html
<form action="{% url 'like'%}" id="plt_{{menu.id}}" data-id="{{menu.id}}" method="post">
{%csrf_token%}
<input name="menu_id" type="hidden" value="{{ menu.id }}">
<div class="like-button" id="btn_{{menu.id}}"></div>
</form>
<script>
$('.like-button').on('click', function () {
var id = $(this).attr('id');
id = id.replace('btn_','');
$(this).toggleClass('animate').promise().done(function () {
var link = $("#plt_"+id).attr('action')
$.ajax({
type: 'POST',
url: link,
headers: {'X-CSRFToken': '{{ csrf_token }}'},
})
});
});
</script>
Views.py
def like(request):
print('reached') //this prints
if request.POST:
menu = Menu.objects.get(pk=request.POST.get('menu_id'))
//execute code to like
return HTTPResponse('')
Maybe you want to check
if request.is_ajax() and request.method== "POST":
request.POST is a dict .Empty here because body is empty in your request.
Empty dicts are treated like False by python like
if {}:
print("Hello World")
Above won't print anything
But below works
if {"hi" : "there"}:
print("Hello World")
And docs suggests this check is wrong if request.POST:
It’s possible that a request can come in via POST with an empty POST
dictionary – if, say, a form is requested via the POST HTTP method but
does not include form data. Therefore, you shouldn’t use if
request.POST to check for use of the POST method; instead, use if
request.method == "POST" (see HttpRequest.method).
It is fairly simple, use serialize() of jquery. Serialize function will take all the values from the form, even csrftokenmiddleware which is hidden input type. So, doing so you will be able to handle post request successfully. Use sthg like this:
<script>
$('.like-button').on('click', function () {
var id = $(this).attr('id');
id = id.replace('btn_','');
$(this).toggleClass('animate').promise().done(function () {
var link = $("#plt_"+id).attr('action');
var data = $("#plt_"+id).serialize(); // It will serialize all form data
$.ajax({
type: 'POST',
url: link,
data: data
});
});
});
</script>
In views.py do as you do for other request. serialize()

How to use javascript to append the header of request before loading that page

I have 2 html files belong to two different controllers
This is belong to Index action of SignupController
Index.html
<div class="signup-small-font pull-right">Forgot password?</div>
When click at this link , it will go to that url and make a request to get the view of the ResetPassword Action of AccountController and get the resetPAssword.html
Now what i want is before making that request , i need to append a custom header in the request for the server side .
I was using ajax javascript :
function appendHeader(urlCulture){
$.ajax({
type: 'GET',
url: urlCulture,
headers: {
"Culture": 'zh'
},
})
}
What should i do in the index.html anchor link to call this function before requesting for the resetPassword.html
Like what I want is when I click at it , it will navigate to Account/Resetpassword and use the response getting from javascript file to render instead of a normal response
In your html file
<div class="signup-small-font pull-right"><a onclick="appendHeader(urlCulture)" href="#">Forgot password?</a></div>
In your js
function appendHeader(urlCulture){
$.ajax({
type: 'GET',
url: urlCulture,
headers: {
"Culture": 'zh'
},
success: function(res) {
window.location = 'Account/ResetPassword';
}
})
}
Give it a try. Im not quite sure if this is what you want to do.
you are using routes, you need to get the url from the javascript function
there is an example of that here:
Get local href value from anchor (a) tag
you could make something similar:
<div class="signup-small-font pull-right"><a onclick="return appendCustomHeader(this);" href="/Account/ResetPassword">Forgot password?</a></div>
in your js function like the previous reply you could make something like this:
function appendCustomHeader(element){
var url = element.href; // to get full url
$.ajax({
type: 'GET',
url: url,
headers: {
"CustomHeader": 'YourCustomHeader'
},
success: function(res) {
// here you make anything else with your response
}
})
return false;
}
I've not tested it, I hope it works for you.
it seems you can disable href redirecttion returning false,
see this:
How can I disable HREF if onclick is executed?

Submit form with jQuery (json encoded, ajax, parse original url/method)

I found a lot of questions about submitting forms without json and submitting forms statically specifying the url and method in the javascript code.
But all I am really looking for is a way to make all my forms send an ajax request in the exact way the form specified it in the first place with the only difference being that I want the data to be json encoded.
For instance a form like this
<form role="form" action="api/login" method="POST">
<input name="email" value="my#email.com" type="text"/>
<input name="password" value="mypassword" type="text"/>
<button type="submit">Login</button>
</form>
should automatically generate an ajax request like this when submitted:
POST /api/login HTTP/1.1
Content-type: application/json
{
"email": "my#email.com",
"password": "mypassword"
}
without me having to specify the method or url in the javascript code again.
And I don't want to write new code for every form I write. I'd simply like to have one snippet that automatically applies the above mentioned to any form.
You try something like this
$(document).on('submit','form',function(e){
e.preventDefault();
$form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: getObject($form.serializeArray()),
success: function (response) {
//Success Handler
}
});
return false;
});
function getObject(data) {
var paramObj = {};
$.each(data, function(_, kv) {
if (paramObj.hasOwnProperty(kv.name)) {
paramObj[kv.name] = $.makeArray(paramObj[kv.name]);
paramObj[kv.name].push(kv.value);
}
else {
paramObj[kv.name] = kv.value;
}
});
return paramObj;
}
$(function() {
$('form').submit(function(){
$.post(
$(this).attr('method'),
$('form').serialize(),
function (data) {
proccessmyData(data);
}
);
return false;
});
});
you can write function for success call back with proccessmyData(data)

submit a form with jQuery function

i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.

Execute php url with JS

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Categories