How can I pass a Django template context variable to JS function - javascript

I am trying to create a simple web link toggle for following or unfollowing a question in my app. I got close using the info My Own Like Button: Django + Ajax -- How? but am not quite there.
My problem is that I cannot dynamically pass question.id to my JS function as the answer in the above link implies. Ie
The hard-wired JS code below DOES work. It passes '12' as a valid param for the view tied to /question/follow-unfollow-inline/. But when I try to replace '12' with a context variable '{{ question.id }}' from the template that calls this JS code, my function passes the string '{{ question.id }}' back to /question/follow-unfollow-inline/ rather than it's value. How do I fix this?
$(function () {
$("#follow_unfollow_toggle").click(function () {
$.ajax({
type: "POST",
url: "/question/follow-unfollow-inline/",
data: { 'qid': '12' },
success: function (e) {
alert('Success!');
}
});
});
});
For now, I'm using #csrf_exempt on my view, but I know I should pass it as data.

You could define it on your anchor tag with data- attribute:
Template:
<a id="follow_unfollow_toggle" href="#" data-qid="{{ question.id }}">Like</a>
Js file:
$(function () {
$("#follow_unfollow_toggle").click(function () {
$.ajax({
type: "POST",
url: "/question/follow-unfollow-inline/",
data: { 'qid': $(this).data('qid') },
success: function (e) {
alert('Success!');
}
});
});
});

Related

How To add another post name/variable inside ajax script

<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: "epdate="+$("#epdate").val(),
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
i have this code and i want to add another variable
inside ajax script adding another
data: "empname="+$("#empname").val(),
dopesnt work i hope someone would help me. thank you
and how can i call a postname or make a postname into session an call it into another php page?
Actually, there are multiple ways, either separate them using a & character.
<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: "epdate=" + $("#epdate").val() + "&empname="+$("#empname").val(),
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
Or alternatively, you can use an object which holds the name-value pair.
<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: { epdate : $("#epdate").val(), empname : $("#empname").val() },
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
UPDATE 1: You can also pass it as an array in the following format,
data : [{
name : 'epdate',
value : $("#epdate").val()
}, {
name : 'empname',
value : $("#empname").val()
}],
UPDATE 2: There is build in functions in jQuery to do the same, use [serialize()][] or serializeArray() method for that. You can apply it on a form element or input elements and which generates based on the input elements name attribute.
data : $('#epdate,#empname').serialize(),
// or
data : $('#epdate,#empname').serializeArray()
,

Laravel 5.7 Autocomplete search from DB: JS not recognizing the route

I'm following this tutorial: https://www.youtube.com/watch?v=D4ny-CboZC0
I've done everything, but at the time of testing I get the following error in the console:
jquery.min.js:2 POST
http://apr2.test/admin/posts/%7B%7B%20('autocomplete.fetch')%20%7D%7D
404 (Not Found)
One thing I'm doing different is that I want that search functionality inside my page of post creation, not an exclusive one, so my routes are like this:
Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => 'auth'], function () {
Route::get('/', 'AdminController#index')->name('admin');
Route::get('posts', 'PostsController#index')->name('admin.posts.index');
Route::get('posts/create', 'PostsController#create')->name('admin.posts.create');
Route::post('posts/create', 'PostsController#fetch')->name('autocomplete.fetch');
Route::post('posts', 'PostsController#store')->name('admin.posts.store');
});
My JS/jQuery code:
// A $( document ).ready() block.
$(document).ready(function () {
$('#country_name').keyup(function () {
var query = $(this).val();
if (query != '') {
var _token = $('input[name="_token"]').val();
$.ajax({
url: "{{ ('autocomplete.fetch') }}",
method: "POST",
data: {
query: query,
_token: _token
},
success: function (data) {
$('#countryList').fadeIn();
$('#countryList').html(data);
}
});
}
});
$(document).on('click', 'li', function () {
$('#country_name').val($(this).text());
$('#countryList').fadeOut();
});
});
What's going wrong?
I think the problem is coming from the blade where you are using the route name as %7B%7B in a url is translated to {{.
Please double check you're using the right code there, or in the action tag in your form element: {{ route ("autocomplete.fetch") }} and it's not being lost by some quotes.

Django include template using Javascript

I came from a Rails background thus the question may seem stupid.
In Rails, when we create a Ajax request, then we can update a view by rendering a partial using the javascript selector like the following:
$("#dashboardEmails").html("<%=j render partial: 'emails', locals: {emails: #emails} %>");
How can I do that in Django template? I've tried the following:
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize() + "&submit=connect",
success: function (data) {
if(data['tables'].length > 0){
$('#data-connection-info').html("{% include 'projects/connection_info.html' with data='"data"' %}");
}
console.log(data);
},
error: function (data) {
console.log("Error");
}
});
Here, I want to update the view with a template projects/connection_info.html, also passing a javascript variable (data) to the template using with. But it is not working.
Any idea how can I achieve that?
UPDATE
I passed the template from the view like:
template = render_to_string('projects/connection_info.html', json_data)
return HttpResponse(json.dumps(template), content_type='application/json')
Then in the ajax success function updates the DOM:
success: function (data) {
$('#data-connection-info').html(data);
}
In this way the problem is solved. :)
I passed the template from the view like:
template = render_to_string('projects/connection_info.html', json_data)
return HttpResponse(json.dumps(template), content_type='application/json')
Then in the ajax success function updates the DOM:
success: function (data) {
$('#data-connection-info').html(data);
}
In this way the problem is solved. :)

Laravel ajax delete request

so here is my delete button
<button class="btn btn-danger btn-xs btn-delete delete" value="{{$post->id}}">Delete</button>
then the ajax request
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "DELETE",
url: "{{route('delete_post')}}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
the route
Route::get('delete_post','PostController#getDeletePost');
then the controller:
public function getDeletePost($post_id)
{
$post = Post::where('id', $post_id)->first();
$post->delete();
return redirect()->route('dashboard')->with(['message' => 'Successfully deleted!']);
}
so please help me identfy why nothing really happens when i press the delete button
I have modified you javascript, first issue in your code is,you must either use get request or post request, second issue you are not using named route in order call url for ajax like {{ route() }} , it should be {{ url('path') }} or name your route..
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "get",
url: "{{ url('/') }}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
You are sending a DELETE request type in your Ajax call, which would require a _method parameter with a value of DELETE added to your AJAX data. Your route is a GET route, so that is why you are seeing no action
Another problem is in your blade syntax you are referencing a named route 'delete_post', but that is your URL, not the route name. You have not named the route from what you have posted
Try updating this line in your routes file and that should allow the request to make it to your controller method.
Route::post('delete_post','PostController#getDeletePost')->name('delete_post');
Now you have to change your Ajax request type to
type: "POST"

Submit Ajax Form via php without document.ready

I am submitting a number of forms on my page via php using Ajax. The code works great in forms preloaded with the page. However, I need to submit some dynamic forms that don't load with the page, they are called via other javascript functions.
Please, I need someone to help me review the code for use for forms that don't load with the page. Also the 'failure' condition is not working.
The code is below:
<script type="text/javascript">
feedbar = document.getElementById("feedbar");
jQuery(document).ready(function() {
$('#addressform').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $('#addressform').serialize(),
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
failure: function () {
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
Thanks.
You need to bind event by existing html (e.g body).
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()
see api: https://api.jquery.com/on/
Try like this:
$("body").on('submit', '#addressform',function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $('#addressform').serialize(),
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
failure: function () {
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
you can delegate to document:
$(document).on('submit', '#addressform', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $(this).serialize(), // <----serialize with "this"
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
error: function () { //<----use error function instead
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
As you have posted this line as below:
I need to submit some dynamic forms that don't load with the page
What i understand with this line is you want a common submit function for all forms which are generated dynamically, then you can do this:
$(document).on('submit', 'form', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $(this).serialize(), // <----"this" is current form context
success: function () {
//some stuff
},
error: function () { //<----use error function instead
//some stuff
}
});
e.preventDefault();
});
});
For your last comment:
You can try to get the text in ajax response like this:
success: function (data) {
feedbar.innerHTML='<div class="text-success">'+ data +'</div>';
},
error: function (xhr) { //<----use error function instead
feedbar.innerHTML='<div class="text-danger">' + xhr.responseText + '</div>';
}
if Success:
here in success function you get the response in data which is the arguement in success function, this holds the response which it requested to the serverside.
if Error:
Same way if something goes wrong at the serverside or any kind of execption has been occured then xhr which is the arguement of error function holds the responseText.
And finally i suggest you that you can place your response in feedbar selector using jQuery this way:
var $feedbar = $('#feedbar');
so in success function:
$feedbar.html('<div class="text-success">'+ data +'</div>');
so in error function:
$feedbar.html('<div class="text-success">'+ xhr.responseText +'</div>');

Categories

Resources