Skip to content

Instantly share code, notes, and snippets.

@john2x
Created April 3, 2011 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john2x/900438 to your computer and use it in GitHub Desktop.
Save john2x/900438 to your computer and use it in GitHub Desktop.
String.prototype.format = function() {
var formatted = this;
for(arg in arguments) {
formatted = formatted.replace("{" + arg + "}", arguments[arg]);
}
return formatted;
};
$(document).ready(function() {
$("#form-book-search").submit(function(event){
search_amazon(event);
});
$(".form-book-add").submit(function(event){
add_book(event);
});
function search_amazon(event){
event.preventDefault();
console.log("CLICKED");
console.log("title: " + $("#id_title").val());
console.log("author: " + $("#id_author").val());
$("#results").empty();
$.post("/books/search/",
{
csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
title: $("#id_title").val(),
author: $("#id_author").val()
},
function(data){
if(data['success']){
display_results(data['books_results']);
$("#results").append("<hr/>");
display_results(data['amazon_results']);
return true;
} else {
console.log("error");
return false;
}
},
"json"
);
}
function add_book(event){
// how to get the book's title, ASIN#, ISBN#, etc. from the button?
event.preventDefault();
console.log(event.target);
}
function display_results(results){
var i = 0;
$.each(results, function(asin, details){
console.log(asin + ' : ' + details);
$.each(details, function(key, value){
console.log(key + ' : ' + value);
});
$("#results").append(
'<div class="book" id="{0}"><p id="book">'
+ '<a href="' + details['url'] + '"><span id="book-cover"><img src="' + details['cover'] + '"/></span></a>'
+ '<a href="' + details['url'] + '"><span id="book-title"><h3>' + details['title'] + '</h3></a>'
+ '<span id="book-author"> by ' + details['author'] + '</span>'
+ '</p>'.format(i)
);
// An "Add" form for each book
$("#results").append(
'<form class="form-book-add" id="{0}" method="post" action="/books/add/">'
// Django requires a CSRF token here. How do I add it via Javascript?
+ '<input type="hidden" id="book-asin" value="'+asin+'"/>'
+ '<input type="hidden" id="book-title" value="'+details['title']+'"/>'
+ '<input type="hidden" id="book-author" value="'+details['author']+'"/>'
+ '<input type="hidden" id="book-cover" value="'+details['cover']+'"/>'
+ '<input type="hidden" id="book-url" value="'+details['url']+'"/>'
+ '<input type="hidden" id="book-isbn" value="'+details['isbn']+'"/>'
+ '<input type="submit" id="btn-book-add" value="Add"/>'
+ '</form></div>'.format(i)
);
i ++;
});
}
});
@wenbert
Copy link

wenbert commented Apr 6, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment