Django button to send emails - ajax

How would you go about creating a button in your templates of an app in Django. I have a script in my views.py:
def my_python_script(request):
if request.is_ajax:
# stuff here
else:
return HttpRequest(status=400)
But how do I actually turn this into a button? Is there some html or css I need to put somewhere? I saw some things about a templates directory in the application but I'm unsure on what things to put there and in what formats.

You would do like the following:
<button type='button' id="my_button">Click me</button>
And with a js (jquery):
$("#my_button").click(){
$.get("url_to_view",{data:"data",function(response){
// response to do something after the request
});
});

Related

ajax returns page source, not the message

All the answers I saw here or elsewhere on Google were with jquery. This is not jquery.
I send an ajax string to a php file.
The php, among other things, formulates a message string which I echo
back to the client.
The returned string is put up in the client as an alert.
The form is then reset.
The problem is that when I do this it puts up as much of the page source that the alert can handle. If I open developer tools to look at the return, it puts the message up correctly, not the page source. Here is the return snippet in my ajax:
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
document.getElementById("thisForm").reset();
}
}
The php file does a simple echo of a text string.
What is it about developer tools that makes this run correctly and why doesn't it print out the message in the alert when developer tools is not there?
When I run the backend php by itself, with or without developer tools, it displays the message properly.
Does anyone have any ideas?
More information: I tried to replace the alert and reset with a
display.innerHTML=ajaxRequest.responseText where display is a javascript object formed from getElementById("ajaxReturn") of a "div id="ajaxReturn". It didn't work. When I tried developer tools, it showed the network response text as being the page source.
I also added && this.status == 200 to the if statement. No change.
The problem is solved. I am not deleting this because it might help some other poster who runs into the same problem. I launched the AJAX with an onclick to a javascript function called ajaxFunction(). The html entity containing the onclick had an href="#" in it. Removing that href solved the problem.
I had the exact same issue and my cause was related to having an extra slash in my URL.
Lets say my URL was:
https://example.com/index.php
I had a wrong link as follows:
https://example.com/index.php/
On both instances my server loads the page,
But the Ajax shows the page source as response for:
https://example.com/index.php/
But works fine for:
https://example.com/index.php
The ajax is essentially posting to index.php/ajaxpage.php which then responds with whats on index.php instead of whats on ajaxpage.php

WordPress Ajax Get Request?

I have a page that includes a php file I have written like so
HTML
<div id="playlists_div_holder">
<?php include(dirname(__FILE__) . '/includes/get_playlists.php'); ?>
</div>
I have created a button that will refresh the playlists , incase the user has uploaded (added/removed) anything, and I am trying to do so with an ajax request to get the file and include it back into that div, but I am receiving a 500 error.
I am doing this in WordPress so that may be an issue.
The Button
<span class="button-primary refresh-playlists" onclick="ReloadPlaylists()">Refresh Playlists</span>
Ajax Request
function ReloadPlaylists() {
jQuery.get('<?php echo plugins_url();?>/Player/includes/get_playlists.php', function(data) {
jQuery('#playlists_div_holder').html(data);
alert('Load was performed.');
});
}
Including it works but an ajax get throws a 500 error
It's pretty hard to guess the problem but some simple workarounds that you can use all the time:-
CAUTION! Please take backup of your WordPress before doing anything.
1st workaround:-
Download fresh WordPress copy
Delete every folder, except the wp-content folder.
Upload all the files and folders again, except the wp-content folder.
2nd workaround:-
Rename
wp-content/themes
to
wp-content/themes-backup
Create a new folder:-
wp-content/themes
start copying each theme from themes-backup to themes one by one and see if the error is gone.
Now what you have done with the themes folder, do exactly with the plugins folder.
Based on your comment,
i'm getting call to undefined function get_option on line 8 , which is odd because it works when i include it the first time. Could it be because its calling the same file on the other and it has some sort of variable conflict?
This is because when the plugin in running as an include, all the wp-includes are laoded before your plugin code is execute. However when you make an AJAX call directly to that file, the wp-includes are no loaded hence your get_option() isn't working.
You can fix that by adding include_once("../../../wp-blog-header.php"); on top of your get_playlists.php file. That might break your plugin (not sure) so in that case its safe to use it inside a condition like this
if(stristr($_SERVER["REQUEST_URI"], get_playlists.php))
include_once("../../../wp-blog-header.php");
However once you do that you will get an Error 404 when you make an AJAX request because that URL is not registered in Wordpress URL Rewrite. You can override that by using header() function.
if(stristr($_SERVER["REQUEST_URI"], get_playlists.php)) {
include_once("../../../wp-blog-header.php");
header("HTTP/1.1 200 OK");
}

How to load the data using Ajax in Django template?

Using Ajax in Django is a open Issue. I have tried to understand it by reading blogs and forums, but it didn't work for me. I am posting a very simple question related to it.
Method defined in views.py: (just a sample)
def widget_data(request):
####
extra_context = {
'data': username
'part': company
}
return direct_to_template(request,'test/widgets.html',
extra_context)
I want to load extra_context to rendered template using Ajax.
Following things will happen in widget.html template i.e.
When a moderator will type a URL at the address bar to open a page it will load two widgets i.e. one for loading all the registered username and other one for their company name . user are continuously registering to the sites and adding company name to their profile. When a new user will registered to the site both widget should load automatically using Ajax.
I have no idea about the topic of Ajax.
How to do this?
How should i even start this?
I have read these following links :
Tutorial 1
Tutorial 2
I know that the answer will be too long and too messy but any help will be appreciative.
If you use jQuery you can do the following
$.get('/url/of/widget_data/view', success(data, textStatus, jqXHR) {
$('#idofdivtoupdate').html(data);
});
That would probably be the easiest way to do it.

jquery tab gives 404 sometimes when loading remote content

I am using jquery tabs to load content from a remote file. I have about 30 links in tabbed navigation all loaded with the same script, but for some reason I get 404 errors on 3 or 4 of the links. Each time I reload the page, the links that don't work will change, so some links that didn't work previously will load properly and others that worked before will throw a 404. The load function happens to create a jcarousel but fire but shows that it gets a 404 error.
$('#example > ul').tabs({
fx: { height: 'toggle', opacity: 'toggle'},
load: function(event, ui) {
$(ui.panel).find('.jcarousel-skin-tango').jcarousel({scroll: 5, easing:'easeInOutQuad', animation:800});
$(ui.panel).find('.jcarousel-skin-tango ul').css({"width":'2890px', "left":"0pt"});
}
});
//----------------------------------------------
<ul>
<li><span>A</span></li>
<li><span>B</span></li>
<li><span>C</span></li>
...
</ul>
Any help would be greatly appreciated. Thanks in advance.
My guess (with very little information) is that it has nothing to do with jQuery or AJAX, but some kind of threading problem either in PHP or in the web-server itself. If you open the same URLs as iframes, do they work then?

Debugging Ajax code with Firebug

I've a couple of problems debugging code returned in an Ajax call - specifically, a function returned in json (errors don't get trapped in Firefox) - up to the point where I started debugging these problems in Internet Explorer (I think it's a firefox related problem, as Venkman doesn't detects those errors either) Do you know of any way to debug code returned in json from an Ajax call?
EDITED 03/04/2009 15:05
Thanks to all for your responses, but I think I didn't explain myself well enough. I know enough of Firebug to do basic debugging, but my problem happens when I fetch some code in an Ajax call that has a problem with it. Let's say we have the following HTML file (you'll need prototype in the same folder to make it work correctly):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" src="prototype.js"></script>
</head>
<body>
<script>
function ajaxErrorTest()
{
new Ajax.Request('data.json', {
'method': 'get',
'onSuccess': function(data){
if(data.responseJSON.func)
data.responseJSON.func();}});
}
</script>
<input type="button" value="test" onclick="ajaxErrorTest();" />
</body>
</html>
and then, the contents of the data.json file is this:
{'func':function(){console.log('loaded...');alert('hey');}}
If you load the page in a browser and click the 'Test' button (and everything goes well) you'll get something in the console, and an alert box that says 'hey'. Now change the data.json file to this:
{'func':function(){console.log('loaded...');alerts('hey');}}
...and click the 'Test' button again (no need to reload the page ;-)
You get the console line, but no alert box... and no errors!!! this is the kind of errors I'm trying to debug.
Try clicking on the "Console" panel (it's a tab) and enabling it. You will find that any HTTP requests will be caught along with any information that they contain. I use this in order to view any JSON stored in the request as well as any errors (500/404/etc).
Also be aware that you have to enable the console panel on a per-domain basis. There are usually three subtabs: headers, post, and response. I usually use the post/response tabs quite a bit when I'm debugging my AJAX.
You probably want to use the Net tab and filter the requests for XMLHttpRequests (XHR) only.
Additional tips:
don't hesitate to console.dir(yourObject) in your code or directly in the console panel. This will give you the complete state and properties of your object.
check your request/response HTTP headers; sometimes it's just a matter of encoding.
if you don't know what event/user action triggered this XHR call, you can add console.trace() right before your AJAX call. This way you'll get the complete call stack.
Edit:
Code executed in another context
The only way I came up with is surrounding your code with an (ugly) try/catch.
I guess it's because the code is executed in another javascript context
<script>
function ajaxErrorTest()
{
new Ajax.Request('data.json', {
'method': 'get',
'onSuccess': function(data){
try{
if(data.responseJSON.func)
data.responseJSON.func();}});
} catch (err) {
console.dir(err);
}
}
</script>
This code gives a detailed error message:
ReferenceError: alerts is not defined
I really doubt changing the execution context will solve the problem.
I don't know how to this with prototype, but with jquery, it can be done easily:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
I'm not sure this issue involves the actual JSON that is retrieved. Can you try throwing an error directly in your onSuccess handler and see if it appears in the Firebug console? Something like this:
onSuccess: function() { alerts('hey'); }
If this is the case, then this issue should be fixed in Firebug 1.7.
I would use a combination of the net/console tabs in firefox.
Copy the json results from the Net Tab in Firefox.
Then paste the results into a variable in the console and try executing the offending function.
In this case, I pasted this:
var x = {'func':function(){console.log('loaded...');alerts('hey');}}
x.func();
When I run this, firebug gives me this error.
ReferenceError: alerts is not defined
As others have mentioned, view the JSON/Javascript returned by expanding the AJAX URL in the Console tab.
Then if you copy that to the run/eval panel of the Console tab (there's an up/down arrow in the bottom right, clicking the up will change it into a textarea on the right hand side, clicking down gives a single line running along the bottom).
If your Ajax call returns: function(){alert("hello")}
Then you can use something like the following:
x = eval('function(){alert("hello")}')
x();
This will allow you to execute the returned ajax.
To debug with breakpoints use the HTML view to create a tag (using Firebug's HTML view) and then simply paste the code into a function within this tag. You can then set breakpoints and fire it by calling the previous function from the run'/eval panel.
If this works fine then clearly there's a bug outside of your control, but you could simply workaround that by sending the json back as text/plain, assigning it to a variable and then evaluating it.
This one is simple, i allways use FIDDLER
to debug my ajax calls.
Fiddler is a Web Debugging Proxy which
logs all HTTP(S) traffic between your
computer and the Internet. Fiddler
allows you to inspect all HTTP(S)
traffic, set breakpoints, and "fiddle"
with incoming or outgoing data.
Fiddler includes a powerful
event-based scripting subsystem, and
can be extended using any .NET
language.
I use an HTTP Proxy Debugger called fiddler which has always worked fine for debugging my AJAX problems. It captures all HTTP requests and responses for you to view. Its freely available from http://www.fiddlertool.com/
the error you are trying to debug is pretty visible on native firefox console. it is: "tools" - "error console"
of course, you see it after it ocurrs but with an wrong line number (infinite resemblance)
I know the specific issue mentioned in the post is for firefox. I landed on this page when googling for generally how to debug java script that comes from an AJAX call and I'm sure a lot of others will.
I my case I was returning some HTML that had a script tag in it, if there was for example, a sytax error in the javascript that came down from the AJAX request in firebug you will get no exception, or errors. The AJAX content will just not render.
In the google chrome built debugger you'll get the error that has been raised, but you'll not be able to step through the code. If you wan't to step though then you'll need to make a dummy page for that.
Thats the best I've been able to get it so far.
When you use a library or javascript code that you have loaded it dynamically, you can use the phrase //# sourceURL=foo.js at the beginning of your javascript code that foo.js is the name that assign it. debugger will show it with that name.
This is true in chrome that I think in firebug.
In this case you can place a breakpoint in the dynamically loaded javascript ( or json ) code.
Use "debbuger;" as line of code where you wanna stop execution. In this way the loaded source code will be available in the source section of your debbuger. I know for sure it works on chrome.

Resources