How to handle multiple actions in Django-Template - django

I have created a web app in which page which consist of choose file input and Now I need to preprocess the data with one button and that preprocessed data should be used for next button called forecast to show the result in that page.Is it possible with Django.
Does it compulsory to take any action in page with url changes in django?

The question is not completely clear, but from what I understand you can use Ajax. On first button click send an ajax request, process it in the view logic, send the appropriate data using maybe JsonResponse, and in the success block of your ajax request set the appropriate data for your forecast button using jquery. Something like -
$.ajax({
url: <url_of_data_processing_logic>,
type: 'post',
data: <required data>,
dataType: 'json',
success: function (data) {
$("#<forecast_button_Id>").html(data.forecast_html);
},
error: function (e) {
console.log(e);
}
});

Related

Django select option

I have a form which has a select field (your color). In front of the select field, I have a button that produces a popup which allows users to create new color before they submit. I am submitting that color form via Ajax. After adding a new color to the database, the popup closes.
I want the newly added color to show in the select list without reloading the page.
Is this possible?
I think you can do this by the same ajax where the success triggers. Code below may help a little :
$(".submit").click(function () {
$.ajax({
url: 'url where your view waits',
data: {
'post': "your data on post",
},
type: 'post',
cache: false,
success: function (data) {
// here you can do DOM manipulation add new object to the list.
// You can also get data from backend in json format an then
// add it to your DOM.
},
});
});
I hope this helps.

(Opencart) How to load a controller in a function and not break ajax with that function?

Is there a way to load controller (product/category) within some contained space, so that the ajax to the custom function within that controller doesn't break?
I'm basically loading (from ajax) a custom function which is inside a core contoller product/category. In this function I need to reload the the product/category controller to get new product list based on ajax data I sent to the function, to then return it as a response to the original ajax.
When I try to do
$this->load->controller('product/category')
it beaks the ajax I set up with the function and in the console I see 404.
I tried using
$foo = $this->load->controller('product/category')
and it works, but I need to also execute
$this->load->view('product/category')
and I don't know how to do it without breaking ajax.
Basically I did what I essentially wanted (see the middle of my question, namely the part about the ultimate need to refresh my product list using ajax) the other way (after reading up How to get products in JSON format from OpenCart using phonegap/jQueryMobile): from the ajax I called the products/category directly and not my custom function inside of the product/category controller as in the question, and when I got reponse back containing the html output of the view, I reloaded a div I made in the product/category.twig with that html using jQuery. The ajax was
$(document).ready(function(){
$.ajax({
url: 'index.php?route=product/category&path=18&json',
type: 'get',
beforeSend: function() {
},
complete: function() {
},
success: function(data) {
console.log('success');
if (data.length > 0) {
console.log(data);
$('#mydiv').html(data);
}
}
});
});
and the code I added to product/category.php was
if(isset($this->request->get['json'])) {
$this->response->setOutput($this->load->view('product/view_for_mydiv', $data));
} else {
$this->response->setOutput($this->load->view('product/category', $data));
}
As you may notice I added a div inside product/category.twig called mydiv, which I placed exactly where I wanted the html to go and then I created a twig called view_for_mydiv.twig inside default/product/category/ folder, the html of which the product/category controller would send back instead of its general twig when it saw that an ajax call had been made to it. The #mydiv div located inside category.twig wraps the html that is the same html that gets produced when view_for_mydiv.twig is used to render product/category.

Return in Http Response and Html page but its not showing on the browser in Django

I have created a page on locahost:8080/kar, i am sending an ajax POST request to different Url(same domain) i.e. locahost:8080/kar/create_post there i am returning an HTML response but its not showing on the browser as the URL is still on locahost:8080/kar, the data is stored in the database.Where as in the developer console i can see the response in the network tab .When i redirect it is also showing the same thing in the developer console
Why i am not able to change the URl and see the response ?
It's a client side thing, that means the desired behaviour needs to be implemented with javascript. Django is functioning normally here.
When you're sending Requests via AJAX, that is a non blocking request with the XMLHttpRequestheader set, your browser won't trigger the chain of events that occurs when a server side script evaluates your form and returns something, which may be data, or a redirect, depending on whether the form validated or not.
A typical AJAX call in jQuery looks like this:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
If you would like to perform some actions when the request you sent by XMLHttpRequest returns, you could attach that to the appropriate success handler:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});
If you need to redirect to the URI that is returned as a redirect from your server you can get the redirect URI from the response in the success handler:
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
}
}
});
If you would like to modify the URL in the users bar without reloading the page you could have a look at this question.

HTML FORM - have form action="" occur before onsubmit=""

I've got a pop-up form, onsubmit it closes itself and also refreshes the parent screen.
It uses action="x.php" to transfer session data.
My problem is that in the form onsubmit="js()" is occuring before action="x.php", so the data doesn't get sent before the window closes.
How can I switch the order that these are executed?
Use jQuery AJAX to submit the form and perform your onsubmit code in the success callback.
$("#formID").submit(function() {
/*
Do client side validation before you submit the form with AJAX
*/
var formData = $("#formID").serialize();
$.ajax({
type: "POST",
url: "x.php",
data: formData,
success: function() {
/*
The actions you want to perform
window.close(); // etc etc
*/
}
});
return false; // stop default form submit because we're using ajax
});

Why does my Django request.method does not match POST

$.ajax({
type :'GET',
url : geturl(a),
// type: $(this).attr('method'),
dataType : 'json',
views.py:
if request.method=="POST":
if request.POST.get('monyrsubmit'):
monthform=MonthForm(request.POST)
if monthform.is_valid():
selected_month=monthform.cleaned_data["Month"]
selected_year=monthform.cleaned_data["Year"]
print selected_month
print selected_year
can i have both GET and POST requests in the type field of ajax. im using a form and only when the submit button is clicked im trying to display information based on the data submitted. if request.POST.get('monyrsubmit') does not work.
Help will be appreciated
It's very simple. You have to abstract the events.
function event_page_load() {
function ajax_request('GET')
}
function click_submit_button() {
function ajax_request('POST')
}
function ajax_request(type) {
$.ajax({
type : type,
......
......
})
}
You can also consider the follwoign general guidelines.
GET and POST should be used based on the type of the request to the server
- If you are reading the existing data(without modification) from the server, use GET
- if you are writing/modifying any data in the server, use POST
in jQuery, you can use these simple methods.
For GET requests
$.get(
url,
{param1: "value1", param2: "value2"},
function(responseText){
// todo ;
},
"html"
);
for POST requests
$.post(
url,
{param1: "value1", param2: "value2"},
function(responseText){
// todo ;
},
"html"
);
Make sure that you have disable the browser caching.
$.ajaxSetup ({
cache: false
});
In django side, you can use request.is_ajax() method to verify the ajax call and you can filter based on request.method property.
You can refer all the possible usages of AJAX with Djano at https://github.com/sivaa/django-jquery-ajax-exmaples