jQuery .load() not working in Django - django

I'm trying to make a call to a url in Django and load the contents of it. Right now I have:
<script>
$('.myClass').load('{% url update_dropdown %}',
{'kind': "Book" },
function(data){
alert(data);
});
</script>
And then the view that update_dropdown refers to is:
#csrf_exempt
def update_dropdown(request):
category = request.POST.get('kind', None)
all =False;
args = {
"label":category,
"all":all
}
return render_to_response('template.html',(args))
However, the .load() won't work for some reason. If I go directly to the URL it shows the data I expect, but .load() won't cooperate. I know it's not a display issue, as the alert will not work (unless I remove the #csrf_exempt, then it alerts the HTML of the error page)
I'm pretty confused as to what's going on, and I've been debugging this and trying to find the error for hours now, any help would be appreciated .
I can get it to work if I make the return type a JSON object and use getJSON(), but I'd prefer not to

Try wrapping it in a ready:
$(document).ready( function () {
$('.myClass').load('{% url update_dropdown %}',
{'kind': "Book" },
function(data){
alert(data);
});
});

Apparently it was an issue with the jQuery uiSelect library I was using. It was out of date and causing errors.

Related

Lucee ColdFusion.Ajax.submitForm

I'm converting a site from ColdFusion to Lucee (for the first time). In ColdFusion, after using the cfajaximport tag, I can run JS code similar to this:
ColdFusion.Ajax.submitForm('runMe', 'runCode.cfm', callback_testMe, errorHandler_testMe);
I seem to be unable to run this in Lucee. I'm looking for some kind of Lucee alternative, but can't seem to find anything.
Basically, I'm wanting to submit form data, run some server side stuff, then return the results without refreshing the page.
Any help would be greatly appreciated.
Lucee does not have CF UI tags, you're going to have to do this with jQuery AJAX or similar.
var formID = "runMe"; // formId Param
$("#"+formID).on("submit", function (e) {
e.preventDefault(); // Prevent page load
$.ajax({
type: "POST", // httpMethod Param
url: "runCode.cfm", // URL Param
data: $(this).serialize(),
success: function (data) {
console.log(data); // callbackhandler
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError); // errorHandler
}
});
})
This should do exactly the same thing and I even pointed out the similar params from ColdFusion.Ajax.submitForm

Avoid double call GET Ajax load

Well, I'm trying to create a graphical interface for a database using django.
I have to say that I'm trying to learn so I don't have too much experience with Frameworks, just with pure code.
The doubt I have is:
-When trying to create a filter system with checkboxes I have used Ajax to be able to update the view without having to refresh. Like this:
$(document).on('click','#console_check_filter',function(){
var ps_id;
ps_id = $(this).attr("data-posts-id");
$.ajax({
url: "{% url 'list-view' %}",
method: 'POST',
data: {
'getfilter': ps_id,
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function (res, status,data) {
$("#list").load("/game/list-view");
},
error: function (res,ras,rus) {
}
});
});
But I had the error that for every call I made with POST the AJAX function ().load() made another call which eliminated the variable that gave me the POST. This made it impossible for me to use the information received from the POST to create the filter.
Result: I click on the checkbox and in the console I get a call with the filtered list and then another one without filter, and as it is not only the last one that is rendered, which has no data.
To solve this I have used a globar variable to save the value in the POST and the ().load() return to make the GET call using the value saved in the GLOBAL.
filet=""
def game_list(request):
global filet
context = {}
game_filter = request.GET.get('console_check_filter')
games = Game.objects.all()
game_post = games
data = {'success': False}
page = request.GET.get('page',1)
game_console_filter=""
context['games'] = games
#if request.method=='POST':
game_console_filter = request.POST.get('getfilter')
if not game_console_filter:
game_console_filter = request.GET.get('getfilter')
if request.method=="POST":
filet = get_game_console_filter(request,game_console_filter)
context['games'] = games
context['game_post'] = filet
return render(request,'Jocs/list-view.html',context )
This doesn't seem elegant to me, I'm out of the woods, yes, but I don't think it's the best solution.
Any idea to avoid this happening to me?
A greeting and thank you very much for everything
Apparently I am more stupid than I thought. In the end the solution was to send the variable by URL. Example:
AJAX:
$(document).on('click','#console_check_filter',function(){
var ps_id;
ps_id = $(this).attr("data-posts-id");
$.ajax({
url: "{% url 'list-view' %}",
method: 'POST',
data: {
getfilter': ps_id,
csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function (res, status,data) {
$("#list").load("/game/list-view/?filters="+ps_id); > <-----HERE
},
error: function (res,ras,rus) {
}
});
});
views.py:
#if request.method=='POST':
game_console_filter = request.POST.get('getfilter')
if not game_console_filter:
game_console_filter = request.GET.get('filters') <---HERE
I think that if this is the right way to proceed, at least it's more elegant.
I hope someone else will find this answer useful.
Sorry for the inconvenience and for asking trivial questions. Greetings to all.

AJax does not seem to work on the delete button

I am really new to ajax. I want to delete the entry from database on button click and I do not want the page to reload. but the ajax doesn't seem to work at all. What is wrong in my code? Please suggest the correct code. Thanks in advance.
<script>
$(document).on('click','#delete',function(){
var a ;
a=confirm("Do you really want to delete the user?");
if(a==true){
var newurl = "{% url 'NewApp:centredelete' pk=1%}"
var id = $(this).attr('name')
$.ajax(
{
type:"GET",
url: "newurl.replace('1',id);",
data:{
delete:True
},
success: function( data )
{
if(data.success == true){
$(id).remove();
}
else{
alert(data.error)
}
}
})}
});
</script>
views.py
def CentreDeleteView(request, pk):
centre = Centre.objects.get(pk=pk)
centre.delete()
return HttpResponseRedirect(reverse('NewApp:centrelist'))
edit:
urls.py
url(r'^centredelete/(?P<pk>\d+)/$',views.CentreDeleteView,name='centredelete'),
I am getting "Not Found: /NewApp/centrelist/url.replace('1',id);
" in the terminal. I don't know why it is taking the wrong url.
Kindly add your url file here and mention here the response on server terminal
replace "newurl.replace('1',id);" with newurl.replace('1',id) in your ajax.
You've used double quotes around newurl.replace('1',id) so the url will send as is instead of replacing '1' with the required id.

(Opencart) How to load a controller in a function and not break ajax with that function?

Is there a way to load controller (product/category) within some contained space, so that the ajax to the custom function within that controller doesn't break?
I'm basically loading (from ajax) a custom function which is inside a core contoller product/category. In this function I need to reload the the product/category controller to get new product list based on ajax data I sent to the function, to then return it as a response to the original ajax.
When I try to do
$this->load->controller('product/category')
it beaks the ajax I set up with the function and in the console I see 404.
I tried using
$foo = $this->load->controller('product/category')
and it works, but I need to also execute
$this->load->view('product/category')
and I don't know how to do it without breaking ajax.
Basically I did what I essentially wanted (see the middle of my question, namely the part about the ultimate need to refresh my product list using ajax) the other way (after reading up How to get products in JSON format from OpenCart using phonegap/jQueryMobile): from the ajax I called the products/category directly and not my custom function inside of the product/category controller as in the question, and when I got reponse back containing the html output of the view, I reloaded a div I made in the product/category.twig with that html using jQuery. The ajax was
$(document).ready(function(){
$.ajax({
url: 'index.php?route=product/category&path=18&json',
type: 'get',
beforeSend: function() {
},
complete: function() {
},
success: function(data) {
console.log('success');
if (data.length > 0) {
console.log(data);
$('#mydiv').html(data);
}
}
});
});
and the code I added to product/category.php was
if(isset($this->request->get['json'])) {
$this->response->setOutput($this->load->view('product/view_for_mydiv', $data));
} else {
$this->response->setOutput($this->load->view('product/category', $data));
}
As you may notice I added a div inside product/category.twig called mydiv, which I placed exactly where I wanted the html to go and then I created a twig called view_for_mydiv.twig inside default/product/category/ folder, the html of which the product/category controller would send back instead of its general twig when it saw that an ajax call had been made to it. The #mydiv div located inside category.twig wraps the html that is the same html that gets produced when view_for_mydiv.twig is used to render product/category.

Display JSON response text from ajax in jQuery Template

I need to pass the response from ajax call to a jquery template.The response json is not malformed.I have checked this by using alert statements in the ajax fn.When the response is passed to the template,it does not get recognized.For example,when I use ${field1} in template,nothing gets displayed in the browser.No error messages are displayed at the browser.Can someone help me fix this issue?
Json response from server:
{
"field1": 23432434,
"field2": "sometext",
}
Ajax fn:
function getinfo(uri)
{
jQuery.ajax({
url: 'http://{{request.META.SERVER_NAME}}'+uri,
success: function(info) {
return info;
},
async: false,
dataType: 'jsonp'
});
}
Template:
<script id="infoTemplate" type="text/x-jQuery-tmpl">
<div>${field1}</div>
</script>
Code to Bind JSON to template:
<script id="Template1" type="text/x-jQuery-tmpl">
{{tmpl(getinfo(uri)) "#infoTemplate"}}
</script>
Note: I can't use the following method to bind JSON with template.That's a long story.
function getinfo(uri)
{
$.getJSON('http://{{request.META.SERVER_NAME}}'+uri, function(data) {
$("#infoTemplate").tmpl(data).appendTo("#somedivid");
});
}
That's not how callbacks work. You're returning info to the callback function, and not to getinfo.
You either have to do something like you proposed after, or keep the result from the ajax call in a global var and call the tmpl function after while, to be sure that you have already got the answer from the ajax call. The first way is the way to go.