Run Django function from Javascript command - javascript

I'm trying to have Django to run a function when I tell it based off a JavaScript button. How do I accomplish this? Where do I write the Django function?
JavaScript in main.html:
function mainFunction(){
alert("Beginning API Main Function");
$.ajax({
type: 'POST',
url: 'livestream/postdata/',
success: function(){alert('DONE!');},
error:function(){alert('ERROR!');},
});
alert("ENDING API MAIN FUNCTION");
}
Urls.py:
url(r'^postdata$', 'livestream.views.postdata', name='postdata')
Views.py:
def postdata(request):
r = ...api... (I know that the api works)
print(r.text)
When I run the function 'mainFunction()' I get the two alerts and then another that says 'ERROR'. Why is this?

Set up a route in your urls.py file
url(r'^action/$', 'yourproject.views.action', name='action')
In your views.py file, you would create that action.
def action(request):
# do your magic!
Then, when someone interacts with that button, do an ajax call that hits the URL at /action.

You add a listener to the button which makes an ajax call when fired. In your view.py you handle the response for that ajax call.

#HieuNguyen
Thank You for answering my question. It was through chat, so I'll write down, what worked.
in ajax need a '/' before lifestream. /livestream/postdata/
url(r'^postdata/$', 'livestream.views.postdata', name='postdata')
in views.py
before function I needed #csrf_exempt
return HttpResponse(r)

Related

How do I send data to my ajax method from my controller?

I want to update a element based on things that are happening in the code server side.
For instance, when I invoke my "Start" function by clicking a button on my page it should change the text inside the element to "Downloading", and then once it's done it should change the text to "Done".
I have this script on my page which invokes a action and updates the text after making a successful request.
<script>
function StartDownload() {
$.ajax({
url: '#Url.Action("Start", "MyPage")', success: function (result) {
$("#badge").removeClass("badge-danger").addClass("badge-info").html("Downloading");
}});
};
</script>
as you can see, right now it's just making a request and on success it changes the class and it changes the text to "Downloading".
The goal is to change it to "Downloading" once it invokes the method, and then once the method finishes I want to change the text to "Done".
And I'm not sure how to do that, I need to some how listen for multiple calls in my ajax method but I have no idea how to do that.
What's the proper way of achieving this?
I was thinking of doing something like this but I'm not sure if that's valid
public ActionResult Start()
{
//Post data back to the ajax to tell it to change to "Downloading"
StartDownload();
//Post data back to the ajax to tell it to change to "Finished"
return View();
}
It is pretty simple in fact.
Except success $.ajax() has a lot of other "events", which you can use.
beforeSend for example may be your choice, because it executes just before ajax call
You can find more events here:
https://api.jquery.com/jquery.ajax/

How to run a python script inside javascript and refresh the view in django

I have a python script that takes in some data and manipulates it. However i need it to run on the client side inside the javascript to process some data and refresh the view.
The python file that manipulates data works well as I have tested it inside the IDLE shell
DataManipulation.py
class ModifyData(object):
#Bunch of functions to manipulate data
below is the function used to render the view with url '.../test' which also works perfectly.
views.py
def test(request):
template = 'app/test.html'
file = 'documents/Sample.csv' #File to be loaded
args = {'test': file }
return render(request, template, args)
After loading this page, i use a javascript library that displays the data on the page in a table, the user can then manipulate the data like multiply a column by 3, but where I am stuck is how to take my DataManipulation.py file to modify the data and updates the page with the updated column on a button click
Since executing python client side is not an option, you have two options.
re-write ModifyData in Javascript and use it client side.
When a user does something like multiply a column by 3:
Use client side JS to make an ajax request to the server
Have your server call ModifyData, and then return the data to the client
have client update view with new data
I would recommend porting your python code to JS, but if that isn't possible #2 will always work. How you implement will just depend on how you manage data in the client.
I think you should pass the data into template, and then use javascript to manipulate the data, after that you can use ajax to update your page without refresh, example:
<!--html-->
<button onclick="deleteUser({{ request.user.pk }})">Submit</button>
<!---->
function deleteUser(userid) {
var post_data = {
'userid': userid,
}
$.ajax({
type: "POST",
url: "/deleteuser",// the view function to post
data: post_data,
contentType: 'application/json;charset=UTF-8',
success: function(result) {
// do something after post
...
}
});
}
the view function:
# url(r'^/deleteuser$', views.delete_user)
def delete_user(request):
if request.method == 'POST':
# do something
userid = request.POST.get('userid')
user = User.objects.get(pk=userid)
# dict contain response data
response_data = {...}
# return response
return HttpResponse(json.dumps(response_data),content_type='application/json')

Django submit a form->redirect to a new page->auto update new page

Ok as the title describes, Im trying to create a webpage(test.html) where in after the form is submitted it should redirect me to a new page(say status.html).And after this page loads It should shows some continuous updates on the submitted task. I was able to accomplish this on a single page , when Im trying to redirect this to a new page Im out of luck.
test.html
<form action="status/" method="POST" id="start-form">
.....
<input type="submit" value="Start" class="tbutton">
views.py
def status_page(request):
print("Inside redirect")
return HttpResponseRedirect(request,'my_app/status.html')
url.py
url(r'^test/status/$', 'status_page'),
jav.js
$('#start-form').on('submit',function(event){
event.preventDefault();
status();
});
function status() {
$.ajax({
url : "status_page/", // the endpoint
type : "POST", // http method
data:{' ': '',}, // data sent with the post req
headers: {Accept: "application/json"},
success : function(json) {
//on success display the rendered page,so what coding is needed here?
},
error : function(xhr,errmsg,err) {
//error handling code }
});
}
On execution the new page is not loaded, but if I bypass javascript then the form action gets executed and the new page rendering through the view happens. But with JavaScript, on success what happens ? how does the return statement from the view get captured in the success and how is the page displayed?
I need to use javascript and AJAX as once the new page is loaded I need to display continuous updates on the same page. So basically how do I implement redirection to a new page with the above code using javascript and Django? Any help will be truly appreciated!
In your views.py, HttpResponseRedirect is used incorrectly. If you want to redirect to a new page, then you should use,
return HttpResponseRedirect('/url-where-you-want-to-redirect/')
As HttpResponseRedirect expects url paramter instead of template name.
See here: https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponseRedirect
Better approach would be to return a JSON response from your status_page view and then in success method of ajax, you can go to next URL:
window.location.href = '/url-where-you-want-to-redirect/';
I hope this helps.

AJAX call how to retrieve my javascript variable

I work with Rails 4 and basically I am searching a value on my html webpage traversing the DOM with jquery.
I store the value in a variable named key and I want to use this value to then make a request that would look like this :
Record.find(id: key).name
I perform an AJAX call and it works well (I checked it rendering status json ok). But now how can I use/retrieve the parameter key in my controller ?
I have a User and a Record model. In the app/views/usersdirectory I have the partial _form.html.erb in which I am doing some javascript.
var key = $('input#record_id').val();
And I want this variable to be available in the method search of my user controller, so that I can make a request with the parameter key.
So I am doing an AJAX call that looks like this :
$.ajax({
url: "/search",
type: "POST",
data: {
value: key
},
complete: function(){
console.log('success');
}
});
And in my config routes file I wrote this route :
post '/search' => 'users#search'
In my User controller I wrote the method like this :
def search
#record = Record.find(params[:key])
end
Is #record available in my partial ? How can I print in my view the result of my request ?
Can anyone tell me if I am doing right or wrong for my AJAX call ? Thanks for any help. If I forgot to mention any information you might need tell me and I'll edit my post.
I added a complete function in my AJAX call, that is supposed to show successif the AJAX call had been done and in my console log I have this message 'success' that appears
For 404 not found the url must be wrong.
And to get the param key in your controller you must change data to data: {key: key} or if you use data: {value: key} then your action must change the name of the param like #record = Record.find(params[:level])
Basically, you are not using the right param name in your controller which is why the issue arises. Hope it helps.
To answer your second question:
#GDMN, you need to get your basics right! Every ajax has a success and failure callback.You could return json from your action which will be used by success callback and you could do whatever you want from there. Essentially in rails you might want to render a js file like this
Create a file named search.js.erb and use your javascript code in it like below
$('.some_id_or_class').html("<%= #record.name %>")
that will simply replace the element of that class with the value that is returned by #record.name
put the full url
url: "http://yoursite.domain/search",

Path for ajax url in Wordpress

How to call an ajax url in wordpress. Through a javascript file
I was using http://example.com/site/wp-content/plugins/pluginname/upload.php..
This is working but now I have changed the structure.
Now I want to make a call to a function inside a class
e.g
class A{
function xyz(){
include('upload.php');
}
}
Now, I am not calling upload.php through the javascript file but loading it inside the xyz function in the class.
So I want a way to call the xyz function from the javascript file.
Thanks
Read this link http://codex.wordpress.org/AJAX_in_Plugins. Do you need to register wordpress hook wp_ajax.
Add to your php code:
add_action( 'wp_ajax_xyz', array($this, 'xyz') );
In javascript
var data = {
action: 'xyz'
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
Did you see this questions:
how to call ajax on frontend of wordpress
Wordpress: how to call a plugin function with an ajax call?
And i think Getting Started with AJAX & WordPress Pagination helps you too.

Categories

Resources