Ajax call in jquery to refresh database models in Django - javascript

I have a search feature I built for an administrative account in Django on the front-end that queries matched users to the admin with an option to remove them from the database. Currently, they click the button, and they are redirected to the view that handles the backend logic for removing the associated object by the primary key from the database. I am wanting to have the user remove the object on button click and then update the div that the users display in after object has been removed without the page refreshing. How can I go about this?

Here a super generic example.
You can do something like:
in your views.py:
def delete_element(request, element_id):
element = get_object_or_404(ElementClass, id=element_id)
element.delete()
return HttpResponse("success")
in your urls.py:
url(r'^element_delete/(?P<element_id>\d+)/$', 'app.views.delete_element', name="name_element_delete"),
in your template:
<script>
$(".delete-button").click(function(){
var element = this;
var url = $(this).data('url');
$.ajax({
type: 'GET',
url: url,
success: function(){
// do what you want with 'element' var
},
error: function(){
alert("Error on delete, please try again");
},
});
});
</script>

Related

How I can send data from Flask to JavaScript?

Hello I am new and building an application in Flask and Javascript. I have a problem with sending data from Flask do JavaScript.
I have code in routes.py
#app.route('/mapaa',methods=['GET','POST'])
def mapa():
user_id = current_user.get_id()
slownik = {}
if 'event_form' in request.form:
name = request.form['name_event']
all_data = Event.query.filter_by(name=name).all()
for row in all_data:
date_st_string = str(row.date_start)
date_end_string = str(row.date_end)
slownik = {'id':row.id,'date_st':date_st_string,'date_end':date_end_string,'type':row.type,'name':row.name,'len_route':row.len_route,'route':row.route}
return jsonify(slownik)
return render_template('mapaa.html', title='Mapa')
I want to send jsonify(slownik) to my code in JavaScript but I dont want to do it with render_template bacause it refresh a page and I need this data to display it on the map using JavaScript. I tried return jsonify(slownik) but it return me the data on new page. How I can send the data when the user click event_form button to JavaScript without refreshing page?
You can use ajax for sending post request without refreshing the page.
Note- include jquery before this
<script src="https://code.jquery.com/jquery-3.1.0.js" ></script>
javascript code
$("#id_of_btn").click(function () { // make ajax request on btn click
$.ajax({
type: "POST",
url: "/mapaa", // url to the function
data: {
name: $("#id_of_input_tag").val(), // value of the form
},
success: function (response) {
console.log(response); // response contains the json
},
});
});
make sure you don't use form tag.
Edit:
If you want to send more data via forms, you could use
data: $('form').serialize()
this will take the name attribute of input tag and add it in the request.data
So if you have this
<input type="text" id="element_id" name="username" >
You can use the value of name attribute like this request.data['username']
follow this tutorial

How to use PHP variable in Jquery Ajax success request

I have page which shows number of routes. User click one and it sends an ajax request and save the selected route in database.
On the same page in different tab, I am running query which gets related information of the selected route. So i have Where clause in my query.
The problem is how I can feed in the ID of selected route to Where clause in my query in different tab
Here is code.
JQuery - When user click/select the route
$(document).ready(function () {
// capture the ID of clicked route
$(".collection-routeselection").click( function(){
route_id = $(this).attr("value");
jQuery.ajax({
url: '../data/collecting.php?action=route-selection?routeid='+route_id,
type: 'POST',
dataType: 'text',
data: {'routeid':route_id},
success: function(data, textStatus, jqXHR) {
$("#tab1").removeClass("active");
$("#tab2").addClass("active");
},
error: function(jqXHR, textStatus, errorThrown){
//Display error message to user
alert("An error occured when saving the data");
}
});
});
So i send the selected route using ajax to update database table.
$insert_web1 = $mysqli_scs->prepare("INSERT INTO collectiontracking_ctr (idrou_ctr,tab_ctr,created_ctr,modified_ctr) VALUES (?,'tab1',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)");
//bind paramaters
$rouid = "";
if (isset($_POST['routeid'])) {
$rouid = $_POST['routeid'];
}
$insert_web1->bind_param("i",$rouid);
$insert_web1->execute();
All working perfect so far..now I have another query on the same page (in different tab) which should have a where clause of selected route.
My question is how can i bind the selected route id to the where clause on second query.
$select_stmt = mysqli_prepare($mysqli_scs, "SELECT id_rou,idjtp_job
FROM routes_rou
WHere id_rou =?");
I want to populate ? with selected route ID.
Thanks
Assuming the value you are interested in is route_id, you should be able to store that in a variable that is accessible to tab #2 if it isn't already. Since it's on the same page this should be trivial especially since you're using jquery.
I apologize if I'm misunderstanding the question. If so please elaborate.

How to invoke a Django function without redirecting to a new page?

I am working on bookmarking of articles. I want to add the article in bookmarks when a button Add To Bookmarkis clicked.
Using Django, the conventional way of doing it would be redirecting to the bookmarks page by passing the slug of the article, and handling the information in the views.py.
Currently, under bookmarks page function in views.py, I have set of code which saves the article to bookmark object of the current user,
user_instance = get_object_or_404(User,username = request.user.username)
userprofile_instance = get_object_or_404(UserProfile,user = user_instance)
new_readlater = Bookmarks.objects.get_or_create(user = userprofile_instance, article_slug = slug)
Where,
User is the inbuilt Django user.
UserProfile is extended User model.
Bookmarksis a OneToMany relation to UserProfile.
class Bookmarks(models.Model):
user = models.ForeignKey(UserProfile, default = 1)
read_later = models.CharField(default = "", max_length = 120)
I know, that bookmark function can be invoked by redirecting to the bookmark page url and hence bookmarks can be saved. But I don't want to redirect to the bookmark page, instead want to add it in the article page itself. How can I invoke the same bookmark saving function that handles the bookmark information on button click?
If I understand you question, what you need to do is make an ajax POST call when you submit the button in the webpage:
$.ajax({
url: "url_to_call",
type: "POST",
data: { csrfmiddlewaretoken: "{{ csrf_token }}", //django needs this
data_item: mydata},
timeout:0,
success: function(data){//do something when done
//data will be the string returned by HTTPResponse
}
}
And in your views.py return a HTTPResponse
response = HttpResponse("Here is some data to send back to the webpage")
This will keep you on the same page, without redirecting

Ajax request 'onError' handler

There is one feature on my site: delete without page refresh. The user just presses 'delete' and the browser will send Ajax-request. It will load 'delete' script with id parameter.
All work well. But it is not very good because of referential integrity of the database. For example, It is possible to delete street, where some people are living.
I want to upgrade my script. I want to add a check to delete script and don't let delete data if some 'people' are connected to 'street' table.
jQuery handler of button click:
$('body').on('click', '.deleteStreet', function()
{
var id = $(this).attr('id');
var hideMe = $(this).parent().parent();
var dataString = 'id=' + id;
if(confirm("Are you sure you want to delete street? It is possible some people living there!"))
{
$.ajax({
type: "GET",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
hideMe.hide();
}
});
return false;
}
});
It will call script anyway and now will delete data anyway. I can add some checks to delete script now and it wouldn't delete, but jquery script would work anyway and will hide table row anyway (because request was send ok, without 404, etc)
1) Is it possible to see delete script result and hide or not hide row depending on it? For example, it will return true or false, js script will catch it and show message about deleting or not deleting of data depending on it.
2) This problem caused by structure of my site. There are some switches on index.pl and load appropriate scripts loading depending on query (mode=street then load street.pl, mode=user then load users.pl etc). So it will show all data loaded before delete.pl script and it will be impossible to check script returned true or false.
Any help? :) Thank you!
P.S.: I am very sorry for my awful english.
You can have the result of your ajax call in the first parameter of the success callback. ex:
$.ajax({
type: "POST",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
if(e === '1'){
hideMe.hide();
}
}
});
try to log your result in the console for tests: console.log(e).
For deleting data you should use a POST request ( or DELETE but not supported by all browsers).
I dont know how your datas (streets) looks like but an other way could it be to return all your existing streets in a json object on the delete request result. And refresh all lines.

efficient and light way to post multiple value field in form to aspx web form

ok, i'll try to better explain the question i am asking: I have an aspx webform that i am using to create an entity, simple data capture. This entity can have many child entities attached to it in a one to many relationship and that are created from the same form. I do not want to use a heavy asp.net component, like a datalist or any custom component to capture those. the way i am currently doing it is that i open a dialog in the page hosting a combobox populated with choices with an ajax call. once the user picks one of the entries and saves, i add an entry to a javascript collection that i use to keep the user choices and display them in a list on the client. when the user submits my form how can i submit this collection and reparse it on the server? I am thinking of using json to store,serialize and then deserialize. is this a good way?
You can post it using the following
var postData = function (myobjectinstance){
var objString = JSON.stringify(myobjectinstance);
$.ajax({
type: 'POST',
url: 'your url',
data: objString,
success: function (){
alert('did it');
},
dataType: 'json'
});
};
An then on the server with json.net you can deserialize the json string
// You can use JSON.Net
public static void PostMethod(string jsonstring)
{
var restoredObject = JsonConvert.DeserializeObject<MyObjectType>(jsonstring)
// do something with your object
}
Or you can use the PageMethods in combination with a scriptmanager if you are using a scriptmanager on your page. see this link for more info.

Categories

Resources