I'm trying to delete an element in a list by clicking a button, each button got the pk of the element as id
$('.delete').on('click', function (event) {
var evaluacion_id = this.id;
$.confirm({
title: 'Desea Eliminar Evaluacion?',
content: 'De ser asi no podra Recuperar estos datos',
buttons: {
confirm: function (evaluacion_id) {
var url = "{% url 'delete-evaluacion' evaluacion_id %}"
$.ajax({
type:"POST",
url: url,
success: function(){
location.href="{% url 'evaluaciones-psicologo' informe.proceso.pk %}"
}
});
},
cancel: function () {
$.alert('Continue Evaluando');
},
}
})
});
if i do $.alert("Delete "+evaluacion_id); instead of the ajax function everything its ok and it shows me the correct id
But if I call it with ajax function, throws me this
Reverse for 'delete-evaluacion' with arguments '('',)' not found. 1 pattern(s) tried: ['INTRANET\\/delete-evaluacion/(?P<pk>\\d+)$']
And my urls.py
url(r'^procesos/EvaluacionesPsicologo/(?P<pk>\d+)$',views.evaluaciones_psicologo,name='evaluaciones-psicologo'),
url(r'^procesos/EvaluacionePsicologo/(?P<pk>\d+)$',views.evaluacion_psicologo,name='evaluacion-psicologo'),
url(r'^delete-evaluacion/(?P<pk>\d+)$', views.EliminarEvaluacion, name='delete-evaluacion'),
The problem is that the template tag {% url 'delete-evaluacion' evaluacion_id %} is evaluated when the template is rendered, not when the JavaScript is run. Django doesn't know the variable evaluacion_id, so it tries to reverse the URL with an empty string, which doesn't match the URL pattern.
The proper way to do this would be to get the URL pattern and transform it into the template URL format, but that would require diving deep into the internals of Django's URL resolving and is probably not worth the hassle. There is a library that does that for you: Django JS Reverse
A more pragmatic approach would be to reverse the URL with a dummy ID, which you then replace in JavaScript.
$('.delete').on('click', function (event) {
var evaluacion_id = this.id;
$.confirm({
title: 'Desea Eliminar Evaluacion?',
content: 'De ser asi no podra Recuperar estos datos',
buttons: {
confirm: function (evaluacion_id) {
var url = "{% url 'delete-evaluacion' 9999 %}".replace('9999', evaluacion_id);
$.ajax({
type:"POST",
url: url,
success: function(){
location.href="{% url 'evaluaciones-psicologo' informe.proceso.pk %}"
}
});
},
cancel: function () {
$.alert('Continue Evaluando');
},
}
})
Related
I am coding a small Django project where an user can select an object and save it in a database. I am trying to implement an Ajax call on a button to delete this object if necessary.
I am doing it step by step, debugging with the console.
my urls:
app_name = 'register'
urlpatterns = [
path('<int:user_id>/', views.account, name='account'),
path('/delete/', views.delete, name='delete'),
]
my view.py:
def delete(request):
data = {'success': False}
if request.method=='POST':
product = request.POST.get('product')
print(product)
data['success'] = True
return JsonResponse(data)
my ajax.js:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var product = 'coca-cola'
console.log('ok till this point')
$.ajax({
url: '{% url "register/delete" %}',
type: "POST",
data:{
'product':product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log('working fine')
}
});
});
My view isn't doing much for now but I haven't any knowledge about Ajax and I am doing it one step at a time.
This is the error I get in the console:
jquery.min.js:2 POST http://127.0.0.1:8000/register/6/%7B%%20url%20%22register/delete%22%20%%7D 404 (Not Found)
As far as I understand, Ajax can't find my url: '{% url "register/delete" %}'.
I have tried '{% url "register:delete" %}' with no luck either.
I found an answer after some tweaking, I defined my url before the Ajax call and then pass it in it:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var product = 'coca-cola'
var url = '/register/delete/'
console.log( url)
$.ajax({
url: url,
type: "POST",
data:{
'product':product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log('working fine')
}
});
});
Also you can add just the string of url to "url" parameter without characters {% url %}. Maybe you copied the code from pattern Django and added it to JS-file. So it does not work.
I'm writing an ajax that works when url contains a constant but does not work when url contains a variable because this does not get replaced by the actual value.
$('body').on('click', '.deleteLayer', function () {
var layer_id = $(this).data('id');
confirm("Are You sure want to delete record with layer_id="+layer_id+"?");
$.ajax({
type: "POST",
url: "{{ route('layers.destroy',['layer' => "+layer_id+"])}}",
data: {_method: 'delete', layer:layer_id},
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
If I use a value, let's say 50 instead of layer_id then it works!!!:
url: "{{ route('layers.destroy',['layer' => 50])}}",
This is the route that I try to access:
DELETE | admin/layers/{layer} | layers.destroy
If I do not send layer parameter in the url I receive the following error
message : "Missing required parameters for [Route: layers.destroy]
[URI: admin/layers/{layer}]. (View:
/var/www/laravelapp/resources/views/layers.blade.php)"
Why is layer_id, here
url: "{{ route('layers.destroy',['layer' => "+layer_id+"])}}",
not replaced by the actual value?
When you are writing like ['layer' => "+layer_id+"] the js variable is not working. It goes like +layer_id+ as the parameter of the route. You can try like this
var layer_id = $(this).data('id');
var url = '{{ route("layers.destroy", ":id") }}';
url = url.replace(':id', layer_id );
$.ajax({
type: "POST",
url: url,
data: {},
success: function (data) {
},
error: function (data) {
}
});
{{URL::to('/destroy')}}+'/'+layer_id;
Route
Route::get('/destroy/{id}', 'controller#destroy')
Controller
public function destroy($id){
// use $id here
}
Hope you understand.
I'm new to Laravel and using Ajax for some functionalities.
//Route
Route::post('some/thing/','Controller#Method');
//jQuery
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "some/thing/",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
//controller
public function Method(Request $object){
if(isset($_POST['val1'])){//do something}
}
problem is in the URL parameter of AJAX. When I'm giving value to the url i.e some/thing/, it gives me 404 error showing www.siteurl/some/thing/some/thing/ not found and when I'm keeping url value blank then it's working. But then i don't think it's a good practice to do like this.
I have seperate .js file in public folder.
Controller in different and blade file in different directory. Laravel version 5.6.22
thank you.
I think you have to change the Url to the absolute path:
Incase you are working on Blade file:
Change the url from : url: "some/thing/",
To url: {{url('some/thing')}},
In case you are working on external Js File:
Change the url from : url: "some/thing/",
To url: url: "/some/thing/",
When you write the url to ajax its trying to achieve some/thing/some/thing/
To fix; give a name for your route and then use this name for your ajax url.
//Route
Route::post('some/thing/','Controller#Method')->name('yourRouteName');
//jQuery
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "{{ route('yourRouteName') }}",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
Use absolute path instead of relative. append / before the url like "/some/thing/"
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "/some/thing/",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
Hope this helps.
You can add route in $except array in VerifyCsrfToken middle ware to ignore csrf token verification on that route
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
"/some/thing/"
];
}
I have a button and when it's clicked, I basically want to load the Auth::user()->name and a date into the database. I can't figure out how to do an ajax call without passing in some sort of data. This is my ajax query.
var url2 = "/application-background-sent/{{$application->id}}";
$(document).ready(function(){
$('#bgSubmit').click(function(e){
$.ajax({
url: url2,
success: function(data) {
alert(data);
},
type: 'GET'
});
});
});
My route:
Route::get('/application-background-sent/{id}', 'ApplicationsController#backgroundSent');
My controller:
public function backgroundSent($id)
{
$application = Application::findOrFail($id);
$application->bg_check_submitted_by = Auth::user()->name;
$application->save();
return response()->json(['success'=>'Data is successfully added']);
}
I have made an Ajax function but i am getting a big prolem in that.
I was displaying the contents on click of the link..
The links are fetched from the database and also the url of the links are fetched from the datbase.
I have wriiten ajax to call the contents dynamically on click of the link
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>
Now FetchUrlByHobbyName is the function called from the Controller thart returns the url
//Ajax routine to fetch the hobbyinfo by hobbyname
[HttpPost]
public ActionResult FetchUrlByHobbyName(string data)
{
HobbyMasters hobbymaster = new HobbyHomeService().FetchHobbyMasterByHobbyName(data);
string url = hobbymaster.InformationUrl;
if (HttpContext.Request.IsAjaxRequest())
return Json(url);
return View();
}
And in my View i have written the link like this:
#foreach (var item in Model)
{
<li >#Html.ActionLink(item.HobbyName, "Hobbies")
</li>
}
i tried this :
#Html.ActionLink(item.HobbyName, "Hobbies", null, new { id = "alink" })
and then calling Ajax on click of 'alink' but with this my ajax function doesnot get called.
Now the problem is the ajax function is getting called on click of every link on the page..
I want to assign a unique Id to it but i am not understanding how to do that
please Help me...
For that specific link, assign an id. E.g
<a id="someID" href="url">Link</a>
and than bind the click only with that link.
$('#someID').click(function (e)) ....
If I understood you correctly this helps you
The text of the link
<script type="text/javascript">
function myAjaxFunction(){
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
</script>
Try to give a css class selector to you action link like this...
#Html.ActionLink("some link", "Create", "Some_Controller", new { }, new { #class = "test" })
then User jquery for it..
<script type="text/javascript">
$(document).ready(function () {
$('.test').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>