Sucess ajax function work when i load the page - ajax

I don't understand why my sucess function work alone without i click on the function after 2 sec i load the page.
{% block javascripts %}
<script>
$.ajax({
url : '{{ path('post_like', {'id' : article.id}) }}',
type : 'POST',
dataType : 'html',
success : function(code_html, statut){
$("#likeChange").replaceWith("hello world");
console.log("test")
},
error : function(resultat, statut, erreur){
}
});
</script>
{% endblock %}
the content i need to change
<a id="likeChange">{{ article.likes | length }}<a>
this is the button to call function
<a data-like="{{ article.id }}" id="ajax" class="btn" role="button"><img src="{{ asset('build/image/flecheup.png') }}"></img></a>

I just don't do a function onClick
{% block javascripts %}
<script>
$(document).on('click', '#ajax', function(){
that = $(this);
$.ajax({
url : '{{ path('post_like', {'id' : article.id}) }}',
type : 'POST',
dataType : 'html',
success : function(code_html, statut, likes){
$("#likeChange").replaceWith(likes);
console.log("test")
},
error : function(resultat, statut, erreur){
}
});
return false;
});
</script>
{% endblock %}

Related

How to use values passed by jquery/ajax in django view

How do I retrieve and use the data passed to view via ajax? In this example I'm trying to implement a reddit like upvote/downvote system
html/js:
{% for post in posts %}
<h2>{{ post.title }}</h2>
{{ post.upvotes }}<button data-id="{{post.id}}" data-vote="up" class="vote" type="submit">Upvote</button>
{{ post.downvotes }}<button data-id="{{post.id}}" data-vote="down" class="vote" id="downvote" type="submit">Downvote</button>
{% endfor %}
<script>
$(".vote").click(function () {
var id = $(this).data("id"); //get data-id
var vote_type = $(this).data("vote"); //get data-vote
};
$.ajax({
url: '/ajax/upvote/',
data: {
'id': id,
'vote_type':vote_type,
}
});
</script>
urls.py:
url(r'^ajax/upvote/$', views.upvote, name='upvote'),
view:
def upvote(request):
#how do i use 'id' and 'vote_type' values here?
You need to first edit your javascript to send the csrf token, and register a POST url in your url.py .
{% for post in posts %}
<h2>{{ post.title }}</h2>
{{ post.upvotes }}<button data-id="{{post.id}}" data-vote="up" class="vote" type="submit">Upvote</button>
{{ post.downvotes }}<button data-id="{{post.id}}" data-vote="down" class="vote" id="downvote" type="submit">Downvote</button>
{% endfor %}
<script>
$(".vote").click(function () {
var id = $(this).data("id"); //get data-id
var vote_type = $(this).data("vote"); //get data-vote
};
$.ajax({
url: '/ajax/upvote/',
data: {
'id': id,
'vote_type':vote_type,
csrfmiddlewaretoken: '{{ csrf_token }}'
}
});
</script>
Now you can access the data you sent in your views.py in a usual way:
def upvote(request):
sentence= request.POST.get("id","")
upvote = request.POST.get("upvote","")
#continue doing your stuffs here...
Hope this helps.

Using Ajax to implement controller method which is passed an ID

I have a button that toggles a boolean value in my DB table. It works but reloads the page each time, so I'd like to toggle it using AJAX. I'm not sure how to do an AJAX post request that can provide the controller with the ID it needs. This is what I have so far:
TaskController Method:
public function updateCompleted($id)
{
$task = Task::findOrFail($id);
if($task->completed) {
$task->completed = false;
} else {
$task->completed = true;
}
$task->save();
Session::flash('message', 'Task updated!');
return redirect('tasks');
}
Button used to toggle (in this case, the first task with ID of 1):
{{ Form::open(array('action' => array('TaskController#updateCompleted', $task->id))) }}
{{ Form::hidden('_method', 'PATCH') }}
#if ($task->completed)
{{ Form::button('<span class="glyphicon glyphicon-ok"></span>', array('class'=>'btn btn-danger', 'type'=>'submit')) }}
#else
{{ Form::button('<span class="glyphicon glyphicon-remove"></span>', array('class'=>'btn btn-danger ajaxSubmit', 'type'=>'submit')) }}
#endif
{{ Form::close() }}
AJAX that doesn't work...
$('.ajaxSubmit').click(function(e) {
e.preventDefault();
$.ajax({
url: 'tasks/complete/{id}',
type: 'POST',
success: function(response)
{
console.log("working");
}
});
});
And route:
Route::patch('tasks/complete/{id}', 'TaskController#updateCompleted');
How do I get the Ajax to work? Thanks
try this
add the id in hidden input with id of "myid" for example
$('.ajaxSubmit').click(function(e) {
var data = $("#myid").val();
e.preventDefault();
$.ajax({
url: '/tasks/complete',
type: 'POST',
data: data,
success: function(response)
{
console.log("working");
}
});
});
do this
Route::post('tasks/complete', 'TaskController#updateCompleted');
don't forget CSRF .

403 forbidden error during send JSON data with ajax

these are code snippet for sending json data with ajax.
you can show same code in the last postings.
I'm just follow the code.
But I got 403 error
jsonpost.html
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/test/jsontest/',
data: {
'fruit': selected,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(result) {
document.write(result)
}
});
});
});
</script>
</head>
<body>
<form>
{% csrf_token %}
{{ data }}
<br>
Select your favorite fruit:
<select id="mySelect">
<option value="apple" selected >Select fruit</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
</body>
</html>
urls.py
urlpatterns = patterns('',
url(r'^jsontest/$', views.JsonRead.as_view(), name='userTest'),
)
views.py
class JsonRead(View):
def get(self,request):
return render(request, 'MW_Etc/jsonpost.html')
def post(self,request):
print(request.body)
data = request.body
return HttpResponse(json.dumps(data))
After change the fruit value, I got the error.
How can I resolve this?
Any others good ways is good as well.
If you are using post method you have to send csrf token in the form,same has to be done in the case of ajax
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/test/jsontest/',
data: {
'fruit': selected,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function(result) {
document.write(result)
}
});
});
});
try like this,this worked for me.

how to clear the form fields after submit data through ajax in symfony2?

my new.html.twig code is given below. How do I clear the form fields after the form submission?
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Proposals creation</h1>
<form action="{{ path('proposals_create') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<p>
<button type="submit">Create</button>
</p>
</form>
<ul class="record_actions">
<li>
<a href="{{ path('proposals') }}">
Back to the list
</a>
</li>
</ul>
<div id="result"></div>
{% endblock %}
{% block javascripts %}
<script src="{{ asset('js/jquery-1.10.2.js') }}" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() {
$("form").submit(function(e) {
e.preventDefault();
var $url = $(this).attr('action');
var $data = $(this).serialize();
$.ajax({
type: "POST",
url: $url,
data: $data
}).done(function( result ) {
if(result.success) {
$('#result').html('<span>Monetary expense correctly saved!<br/> The data are:<br/>id: '+ result.id +'<br/>descrition: '+ result.description +'<br/>proposalname: '+ result.proposalname +'<br/>status: '+ result.status +'</span>');
}
});
});
});
</script>
{% endblock %}
Use HTMLFormElement.reset() to revert all <form> fields to their defaults.
$("form").submit(function(e) {
e.preventDefault();
var $url = $(this).attr('action');
var $data = $(this).serialize();
$.ajax({
type: "POST",
url: $url,
data: $data
}).done(function( result ) {
if(result.success) {
$('#result').html('<span> ... </span>');
}
});
this.reset(); // formElement.reset()
});
reset() resets the form to its initial state. This method does the same thing as clicking the form's reset button. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method.

Django - after submitting invalid form submit button upon click redirects

I have a django project in which i have a form in a div being loaded by ajax.
when I submit the form with empty fields it returns the form with the required fields shown.
when I hit submit again it redirects to the action of the form instead of reloading the form in the div and showing errors as it does the first time I submit.
does anyone have any idea where the error might be occurring? I imagine somewhere in the ajax or view in my django project.
here is what is returned by the second submit:
{"success": false, "form": "<head>\n\n</head>\n<body>\n<form action=\"/cookbook/createrecipe/\" method=\"POST\" name=\"recipeform\" id=\"createrecipeform\">\n\t<table>\n\t\t<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='c5ea952ee2144b377b375d91b0843c75' /></div>\n\t\t<tr><th><label for=\"id_name\">Name:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_name\" type=\"text\" name=\"name\" maxlength=\"200\" /></td></tr>\n<tr><th><label for=\"id_author\">Author:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_author\" type=\"text\" name=\"author\" maxlength=\"100\" /></td></tr>\n<tr><th><label for=\"id_picture\">Picture:</label></th><td><input type=\"file\" name=\"picture\" id=\"id_picture\" /></td></tr>\n<tr><th><label for=\"id_ingredients\">Ingredients:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_ingredients\" rows=\"10\" cols=\"40\" name=\"ingredients\"></textarea></td></tr>\n<tr><th><label for=\"id_steps\">Steps:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_steps\" rows=\"10\" cols=\"40\" name=\"steps\"></textarea></td></tr>\n<tr><th><label for=\"id_prep_time\">Prep time:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input type=\"text\" name=\"prep_time\" id=\"id_prep_time\" /></td></tr>\n<tr><th><label for=\"id_type\">Type:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><select name=\"type\" id=\"id_type\">\n<option value=\"\" selected=\"selected\">---------</option>\n<option value=\"SW\">Sandwich</option>\n<option value=\"AP\">Appetizers</option>\n<option value=\"SD\">Sauces and Dressings</option>\n<option value=\"SS\">Soups and Salads</option>\n<option value=\"VG\">Vegetables</option>\n<option value=\"RG\">Rice, Grains and Beans</option>\n<option value=\"PA\">Pasta</option>\n<option value=\"BR\">Breakfast</option>\n<option value=\"MT\">Meat</option>\n<option value=\"SF\">Seafood</option>\n<option value=\"BP\">Bread and Pizza</option>\n<option value=\"DT\">Desserts</option>\n</select><input type=\"hidden\" name=\"reset_recipe\" id=\"id_reset_recipe\" /></td></tr>\n\t</table>\n\t<p><input type=\"submit\" value=\"Submit\"></p>\n</form>\n</body>"}
here is my ajax code:
<script type="text/javascript">
$(document).ready(function(){
var form = $('form#createrecipeform');
form.submit(function(e) {
e.preventDefault();
console.log('ajax form submission function called successfully.');
//form = $(this);
console.log(form)
var serialized_form = form.serialize();
$.ajax({ type: "POST", 
url: $(this).attr('action'),
data: serialized_form, 
success: (function(data) { 
console.log('ajax success function called successfully.');
data = $.parseJSON(data);
if (data.success) {
console.log('success');
} else {
console.log('failure');
var newForm = data.form;
form.replaceWith(newForm);
}
})
});
return false;
});
});
</script>
here is the view: (createrecipe is the action of the form and account is the page that is loading the ajax)
def createrecipe(request):
print "entering createrecipeview"
if request.method == 'POST':
print "form is a post"
form = RecipeForm(request.POST)
print form.errors
if form.is_valid():
print "form is valid"
form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
form = form.save()
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form': form,
})
data = {
'replace': True,
'form': t.render(c),
'success': True,
}
json = simplejson.dumps(data)
return HttpResponse(json, mimetype='text/plain')
else:
print "form is invalid"
form = RecipeForm(request.POST)
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form':form,
})
data ={
'form': t.render(c),
'success': False,
}
json = simplejson.dumps(data)
return HttpResponse(json, mimetype='text/plain')
def account(request):
user = request.user
if request.user.is_authenticated():
cookbooks = user.cookbooks
if cookbooks.all().exists():
cookbook = cookbooks.all()[0]
form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
recipe_list = cookbook.recipes.all()
else:
raise Http404
else:
return HttpResponseRedirect('/accounts/login')
t = loader.get_template('cookbook/account.html')
c = RequestContext(request, {
'form': form,
'recipe_list': recipe_list
})
return HttpResponse(t.render(c))
here is the create_form.html template:
<head>
</head>
<body>
<form action="{% url cookbook.views.createrecipe %}" method="POST" name="recipeform" id="createrecipeform">
<table>
{% csrf_token %}
{{ form.as_table }}
</table>
<p><input type="submit" value="Submit"></p>
</form>
</body>
and here is the account template that includes the create_form template:
{% extends "cookbook/base.html" %}
{% load pagination_tags %}
{% load comments %}
<h1>{{ user }}'s Cookbook</h1>
<ul>
{% block nav-cookbooks %}
<li><a class="nav-inactive" href="/cookbooks/">Cookbooks</a></li>
{% endblock %}
{% block nav-account %}
<li><a class="nav-active" href="/account/">My Cookbook</a></li>
{% endblock %}
</ul>
{% block content %}
{% autopaginate recipe_list 6 %}
<div id="recipe_cont">
{% for recipe in recipe_list %}
<div class="recipe">
<div class="button">
<img src="{{ STATIC_URL }}chicknbraw.jpg" alt="" height="70" width="70" style="display:inline;" />
<h4>{{ recipe.name }}</h4>
</div>
<h5>{{ recipe.author }}</h5>
<h5>Prep Time: {{ recipe.prep_time }} minutes</h5>
<h6>Add Recipe
Remove Recipe</h6>
</div>
{% endfor %}
</div>
<div id="popupContact" class="popup">
<a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
<p id="contactArea">
<h1 style="text-align:center">Create New Recipe</h1>
{% include 'cookbook/create_form.html' %}
</p>
</div>
<div id="backgroundPopup">
</div>
<div id="col2-footer">
{% paginate %}
<p id="recipe_order_text"> order by: abc|date
</div>
{% endblock %}
{% block footer %}
<a class="create" style="cursor:pointer" >Create New Recipe</a>
{% endblock %}
sorry for putting so much code but it all seems to rely upon another piece of code so I figured all relevant code would be helpful
thanks for any help you can give me
katie
In your javascript, you're hijacking the form so that it submits via ajax, but then you're calling replaceWith on the form, so your hijacked form gets obliterated and is replaced with a new, non-hijacked form. To solve this you can either
1) Only replace the content of the form - this should work since you're only attaching events to the form itself and not its child elements
2) Write your js as a function which you can call firstly on the initial form, and subsequently on any new forms loaded via ajax.
UPDATE: for example,
<script type="text/javascript">
$(document).ready(function(){
function hijack() {
var form = $('form#createrecipeform');
form.submit(function(e) {
e.preventDefault();
console.log('ajax form submission function called successfully.');
//form = $(this);
console.log(form)
var serialized_form = form.serialize();
$.ajax({ type: "POST",
url: $(this).attr('action'),
data: serialized_form,
success: (function(data) {
console.log('ajax success function called successfully.');
data = $.parseJSON(data);
if (data.success) {
console.log('success');
} else {
console.log('failure');
var newForm = data.form;
form.replaceWith(newForm);
hijack();
}
})
});
return false;
});
};
hijack();
});
</script>

Resources