django JSON response does not attached to jQuery post sucess - ajax

I use Ajax post method to send my form information to django and after a time consuming process results get back to the ajax post . the problem is that when django view return
result It apear on web browser screen and seems it dose not bound to ajax post success method
here is my Ajax post method :
$('#LearnSubmit').on('click',function(e){
e.preventDefault
var form =$('#ParameterForm');
console.log("waiting ajax");
$.ajax({
type :"POST",
url : $form.attr('action'),
data : $form.serialize(),
success : function(data,status){
console.log('lablablab');
console.log(data)
}
})
}) ;
according to my ajax post method after djang oview return result "lablablab" and data should print in console but returing result is printed on screen
could time consuming django view cause that ?
here is my django view :
def NNLearnSin(request):
context = RequestContext(request)
if request.method=='POST':
response_dict = // a time consuming process here
return JsonResponse(respons_dict)

It sounds like your form submit button is actually submitting the form and the click event is not called. Looking at your code I would say that e.preventDefault should be e.preventDefault() otherwise the default form submit is not "prevented".

Related

Do I sent two requests to the ActionResult?

I have an ASP.net MVC project and depending on the filter options chosen by the user I am sending different ajax requests to the same actionresult, for example:
$(document).on("click", "#filter_reset_button", function () {
var url = "/Admin/Index";
ajaxRequest({
url: url,
type: "get",
data: { reset: true },
successCallback: function () {
window.location.href = url;
}
});
});
Other listeners sent different data, something like:
data: { page: 2, filterUpdate: true }
and so on. The Index ActionResult returns different lists of items, depending on different options chosen in the data and the code works completely fine.
A colleage of mine told me, that my code is actually sending two get requests to the AR everytime, so its not efficient. Is that true? And if its the case, how can I refactor it. to make it just one request? If I let window.location.href = url part out, the site actually doesnt load the server response.
Yes you are doing 2 request in button click. First in Ajax Get, Second in Success Call Back.
But Why are you calling window.location.href = url; success call back. ?
If you want update the page after click, you can do partial updates to page. Check this post.
That is correct 2 request called.
First request when you call AJAX get to Action Index in Admin Controller.
Second request when you set window.location.href = url, it will same as you enter /Admin/Index in browser.
In this case you only need window.location.href = '/admin/index?reset=true' in click function
You can see the post here at this post
Actually on success callback you must change your code accordingly to the above post

Spring-Boot: Redirect and Refresh model and page

I have a spring-boot application, with theyemleaf. I repeatedly update the page, and redirect it to the same page, so i expect that the elements of the page get updated:
#GetMapping("/suggested-events/vote/{eventId}")
public String voteForEvents(Model model,
#PathVariable("eventId") Long eventId,
#RequestParam(value = "message", required = false) String message ) {
log.info("The message is: "+message);
SuggestedEvent event = suggestedEventService.findSuggestedEventById(eventId);
ArrayList<SuggestedEvent> events = suggestedEventService.findSuggestedEventsByArea(event.getArea());
model.addAttribute("mainEvent",event);
model.addAttribute("events",events);
model.addAttribute("message",message);
return "/suggested-event/vote";
}
and when a button get pushed in the view it triggers the below post method:
#PostMapping("/suggested-events/vote")
public String voteForASuggestedEvent(RedirectAttributes redirectAttributes){
log.info("You have made a vote");
redirectAttributes.addAttribute("message", "Success");
return "redirect:/suggested-events/vote/1";
}
This second controller method, performs an operation an makes a message, and redirects it to the first method. So, it successfully redirected to the first method and it logs
log.info("The message is: "+message);
but it does not refresh my page, and i do not get the message as model?
When i redirect to the first method, i expect it adds the message to my models:
model.addAttribute("message",message);
But it does not added to my page
and when a button get pushed in the view it triggers the below post
method:
It sounds like this trigger is using AJAX, rather than a form submit. Doing so would match the symptoms you describe.
If you POST to /suggested-events/vote using AJAX, the server will return a 302, and the browser will follow it. However, the response for that 302 is still the result of an AJAX call. You have access to it in your success callback, but the browser isn't going to render it for you.
but it does not refresh my page
If a 302 doesn't cause your page to re-render, this also suggests you're using AJAX.
If you actually use a form submit instead, the browser will re-render using the markup returned by the successful redirect.
This can be verified by using the following two buttons in your vote.html:
<form action="http://localhost:8080/suggested-events/vote" method="POST">
<input type="submit" text="Submit" />
</form>
<button onclick="postmessage();" >Button</button>
<script>
function postmessage() {
$.ajax({
method: 'POST',
data: {},
url: 'http://localhost:8080/suggested-events/vote'
});
}
</script>
The first button will work as expected, and the second button matches the symptoms you describe.
If you are already using a form, please update the question with it (or better yet, the entire Thymeleaf template).
I had the same problem as OP described and Mike's explanation brought me in the right direction.
I am reading a db-table and populating it with thymeleaf using th:each. I wanted to add a javascript-confirmation before deleting an item. Sending an ajax GET without an event-listener and reloading with location.reload(true) didn't reach the #GetMapping("/delete/{id}") in the controller.
This SO-thread gave me the answer to the ajax-call.
<a class="btn btn-danger" href="#" th:onclick="|confirmDeletion('${u.id}')|"></a>
<script th:inline="javascript">
function confirmDeletion(id) {
if (confirm("Delete this id? " + id)) {
var http = new XMLHttpRequest();
http.open("GET", "/delete/" + id, true);
http.addEventListener("readystatechange", function() {
if (http.readyState === 4 && http.status === 200) {
window.location.reload(true);
}
});
http.send();
}
}
</script>
there are many ways to redirect page in Spring, but be sure if the model attribute off message its passing correctly to FrontEnd or passing like parameter to another handler , you can see this document : http://javainsimpleway.com/spring-mvc-redirecting-model-attributes-from-one-controller-to-other-controller/ , hope this is useful !!

Web2py How to return data from controller after an ajax call

I have a sign in page,the page send request to the controller and show errors after getting back the result.
This is the ajax call in sign in page
$.ajax({
url:"signin", //changed into temp.html page
data:{
username:$username,
password:$password,
email:$email },
success:function(errCode){
if(errCode==0){
alert('Error,wrong username/password');
}else{...}
},
type:'POST'
});
The problem is in controller def signin() I don't know how to return the data's value back to ajax,it either didn't work or wiped the page clean and printed just the data's value.How can I do it,is it the same if I want to return a javascript type file?
Edit:I found a way to work around it,I changed the ajax request destination to a temp page and return the value directly.Here is my view function in controller
def signin():
return dict()
def temp():
errCode=0
return errCode

angularjs changes in data not affected in views ajax

I am developing an application with angular js
Question: When I have an ajax call to server and I need to change the views based on the result of ajax call, the views don't get affected by this call, I think it the page renders before ajax call is finished but I don't know how to resolve it
For example the following piece of code
$scope.addItem = function() {
$http({
method :'GET',
url : 'addItem',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success( function(data) {
$scope.allItems = data;
});
}
the allItems changed after the ajax call but the view is not changed
how should I solve this?

Refresh form in Django without reloading page

Hi I'm new in Ajax and django and I want to refresh my form. I try some code but it didn't work. I'm sure what I want to do is very basic.
Here my html:
<div class="row" style="padding-top:20px;">
<div class="col-md-12" id="testAjax">
{% load crispy_forms_tags %}
{% crispy form %}
</div>
</div>
I want to refresh my form in the div testAjax.
Here my view:
def createPin(request):
error = False
if request.method == "POST":
form = CreatePinForm(request.POST)
if form.is_valid():
pin = form.save(commit=False)
pin.customer = request.user.customer
pin.save()
msg = "pin saved"
return redirect('/pin/CreatePin', {'form': form, 'msg': msg})
else:
error = True
else:
form = CreatePinForm()
return render(request, 'createPin.html', {'form': form, 'error': error,})
My Ajax:
function refresh()
{
$form=$('#createPin');
var datastring = $form.serialize();
$.ajax({
type: "POST",
url: '/pin/CreatePin/',
dataType: 'html',
data: datastring,
success: function(result)
{
/* The div contains now the updated form */
$('#testAjax').html(result);
}
});
}
Thanks alot for your help.
When I need to do some operations and I don't want to reload the page I use a JQuery call to Ajax, I make the pertinent operations in AJAX and then receive the AJAX response in the JQuery function without leaving or reloading the page. I'll make an easy example here for you to understand the basics of this:
JQuery function, placed in the template you need
function form_post(){
//You have to get in this code the values you need to work with, for example:
var datastring = $form.serialize();
$.ajax({ //Call ajax function sending the option loaded
url: "/ajax_url/", //This is the url of the ajax view where you make the search
type: 'POST',
data: datastring,
success: function(response) {
result = JSON.parse(response); // Get the results sended from ajax to here
if (result.error) { // If the function fails
// Error
alert(result.error_text);
} else { // Success
//Here do whatever you need with the result;
}
}
}
});
}
You have to realize that I cannot finish the code without knowing what kind of results you're getting or how do you want to display them, so you need to retouch this code on your needs.
AJAX function called by JQuery
Remember you need to add an url for this Ajax function in your urls.py something like:
url(r'^/ajax_url/?$', 'your_project.ajax.ajax_view', name='ajax_view'),
Then your AJAX function, it's like a normal Django View, but add this function into ajax.py from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_exempt from django.utils import simplejson
#csrf_exempt
def ajax_view(request):
response = []
#Here you have to enter code here
#to receive the data (datastring) you send here by POST
#Do the operations you need with the form information
#Add the data you need to send back to a list/dictionary like response
#And return it to the JQuery function `enter code here`(simplejson.dumps is to convert to JSON)
return HttpResponse(simplejson.dumps(response))
So, without leaving the page you receive via javascript a list of items that you sended from ajax view.
So you can update the form, or any tag you need using JQuery
I know that this can be so confusing at the beginning but once you are used to AJAX this kind of operations without leaving or reloading the page are easy to do.
The basics for understanding is something like:
JQuery function called on click or any event you need
JQuery get some values on the template and send them to AJAX via
POST
Receive that information in AJAX via POST
Do whatever you need in AJAX like a normal DJango view
Convert your result to JSON and send back to the JQuery function
JQuery function receive the results from AJAX and you can do
whatever you need

Resources