Updating the page with Ajax - ajax

after i submit a form with Ajax and i have the result back ... i need to update my EJS tag with this new data.
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){
........
console.log(result)
}
and in my EJS file i have this code:
<% if(test.type =='type_1' ) { %> type 1 information <% } %>
<% if(test.type =='type_2' ) { %> type 2 information <% } %>
so if the user change the input to type 2 i need to update my page and show the user the information of type 2 without refreshing the page

Related

Django - Update div as plain text after I create a post using ajax

My project has a Post model. My home page has list of all post and post_create form. I create post using ajax view. Intention was to create a new post and update the home page without page refresh. Here is the code,
views.py,
def post_create_ajax(request):
if request.is_ajax():
if request.method == 'POST':
title = request.POST.get('the_post')
author = request.user
post = Post(title=title, author=author)
print(title)
post.save()
return JsonResponse({'title': title})
The script,
$('#postform').submit(function(event){
event.preventDefault();
console.log('Working');
create_post();
});
function create_post(){
console.log('Create Post is working');
var posttitle = $('#id_title').val();
$.ajax({
url: '/ajaxcreate/',
type: "POST",
data: {
the_post: posttitle,
csrfmiddlewaretoken: '{{ csrf_token }}',
},
dataType: 'json',
success: function(data){
$('#id_title').val('');
console.log(data.title);
$('#post_title_content').html(data.title);
},
error:function(){
console.log('Error Occoured');
alert('Error');
},
})
}
This part works fine. The page new post is getting added without refresh.
Here is a problem. After I submit a post, the new title that getting added are not safe.
e.g. if I add <b> This is a title </b>, The new div is added with This is a title and only returns to plain text <b> This is a title </b> after I refresh the page.
So my question is how to change my script so that it will update div as plain text?
Images:
New post is added, but not in plain text,
After I refresh it shows as plain text,
You should use .text instead of .html on this line
$('#post_title_content').html(data.title);
jQuery.html() treats the string as HTML while jQuery.text() treats the content as text
You should use .text(data.title) instead of .html(data.title). There is more information on this other question.

Django form submitted with ajax redirects to form action instead of calling success

I have simple form
class TimeForm(forms.Form):
time = forms.TimeField()
date = forms.DateField()
def clean_date(self):
time = self.cleaned_data['time']
date = self.cleaned_data['date']
date_time = datetime.combine(date, time)
if datetime.now() > date_time:
raise ValidationError("datetime error")
return start_date
with class based view
class TimeView(View):
#staticmethod
def post(request):
form = TimeForm(request.POST)
if form.is_valid():
# do something
json_data = json.dumps({'some_record': value})
else:
json_data = json.dumps({'errors': form.errors})
return HttpResponse(json_data, content_type='application/json')
In html I have standard form with submit connected do ajax
<form action="/time_url/" method="POST" id="time_form">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
<script>
$('#time_form').submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/time_url/',
dataType: 'json',
data: $(this).serialize(),
success: function(data, textStatus, jqXHR){
alert('yay');
}
})
});
</script>
and I'd like to be able to submit this form without page reload. Everything seems to work perfectly but success function of ajax is not triggered, instead page is redirected to /time_url/ with json data. It doesn't matter wheter form is valid nor not, it's always redirected.
I've tried also with
return JsonResponse(form.errors.get_json_data())
instead of
return HttpResponse(json_data, ...)
as suggested here Django form submit with ajax but without success.
I'm new to javascript but for me it looks like problem with ajax, since proper data is served by server.
Thanks for any tips.

Rendar partial view in another partial view along with data model using jQuery .Ajax function

I am working on MVC 5 app and I want to render partialView in another partialview with model data using jQuery ajax function. when javaScript function is called, it suppose to send ID of selected element back to controller which is working fine, and in return bring partial view along with model which is not working from following code
<td>
<a href="#" class="SearchUser_Icon Hyperlink_Text" onclick="load_getUserListByGroupID(this)" id=#item.GroupID></a>
</td>
.
JavaScript function
function load_getUserListByGroupID(element)
{
var selectedGroupID = element.id;
alert(selectedGroupID);
$.ajax({
type: "POST",
url: "/UserManagement/SearchUsersByGroupID/",
dataType: "json",
data: { 'GroupID': selectedGroupID },
success: function (viewHTML) {
alert("success");
$("#userContentBlock").html(viewHTML);
},
error: function (errorData) { onError(errorData); }
}).done(function (result) {
alert("done!");
});
}
.
<div id="userContentBlock"></div>
Controller Method
[HttpPost]
public ActionResult SearchUsersByGroupID(string GroupID)
{
int intID = Convert.ToInt32(GroupID);
var UsersListByGroupID = _userServices.GetUsersByGroupID(intID);
return PartialView("GetUsersListByGroup_Partial", UsersListByGroupID );
}
You are returning HTML while expecting JSON in the ajax call. Just remove the dataType: "json" from the settings and everything should work as expected.
jQuery.ajax() dataType:
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.

ajax query based on model form sends no data to server

I have a model based form:
class CommentForm(ModelForm):
class Meta:
model = Comments
fields = ['comments_text']
In html:
<form action="" method="post" id = "comment_form">
{% csrf_token %}
{{form}}
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
When making an ajax query to add comment, it sends no input data from the form to view:
$(document).ready(function()
{
$("#comment_form").submit(function(e){
$.ajax({
url: url_,
type: "post",
success: function(result){
alert(result);
}
});
});
});
What's the reason? Console error: POST http://127.0.0.1:8000/articles/addcomment/1/ net::ERR_CONNECTION_REFUSED
When making an ajax query to add comment, it sends no input data from the form to view:
If you're using ajax, you'll need to pass the parameters manually through data.
$.ajax({
url: url_,
type: "post",
data: $('#comment_form').serialize(),
success: function(result){
alert(result);
}
});
What's the reason? Console error: POST http://127.0.0.1:8000/articles/addcomment/1/ net::ERR_CONNECTION_REFUSED
Try leaving out the url parameter in your ajax request

Call different action on checking checkbox than on unchecking

I'd like to call one controller action on checking checkbox and another on unchecking.
That is, I want to call "meeting#create" on checking and "meeting#destroy" on unchecking.
This is signup form where You can sign up for several meetings via checkboxes. On checking the checkbox, the corresponding meeting gets added to an order (practically a cart) and on unchecking, the corresponding meeting gets removed from the order.
How is it possible to call a different action depending on actual status of the check_box_tag?
I'm no professional, so it took me long enough to figure out the options I should supply (the url_for) and I don't have a clue how to do it conditionally.
Please help!
<% #meeting.each do |meeting| %>
<%= check_box_tag 'checkbox', meeting.id, checked = false, :data => {:remote => true, url: url_for(controller: :order, action: :create, meeting_id: meeting), method: :post}, :class => 'checkbox' %>
<% end %>
In the end, I wrote the ajax script by hand.
$( document ).ready(function() {
$(".checkbox").click(function() {
var chb = $(this);
if($(this).prop('checked')){
$.ajax({
url: '/bookings?meeting_id='+chb.attr('value'),
type: "post"
});
}
else{
$.ajax({
url: '/bookings?meeting_id='+chb.attr('value')+'&cart_id='+currentcartid,
type: "delete"
});
};
});
});
One ajax script sufficed.

Resources