Highlight word and send GET request - javascript

I've created a text field in a Django model. I want to highlight words when word is clicked. I've found this jsFiddle
How can I adjust it to send a GET request to Django when a word is selected to receive JSON from other website API? Thanks in advance!
$(function() {
editTxt('#myTxt');
editTxt('#myTxtDiv');
$('span').live('mouseover', function() {
$(this).addClass('hlight');
});
$('span').live('mouseout', function() {
$(this).removeClass('hlight');
});
});
function editTxt(selector) {
$(function() {
var newHtml = '';
var words = $(selector).html().split(' ');
for (i = 0; i < words.length; i++) {
newHtml += '<span>' + words[i] + '</span> ';
}
$(selector).html(newHtml);
});
}

You might do something like this by using $.ajax:
...
$("span").on("mouseover", function() {
xhr = $(this).addClass("hlight");
$.ajax({
method: "post",
url: "YOUR_DJANGO_API_URL",
data: { text: $(this).text() },
success: function(data) {
// replace HTML element or whatever.
console.log(data);
}
});
});
$("span").on("mouseout", function() {
xhr.abort();
$(this).removeClass("hlight");
});
...
Note you have to replace data object text attribute to whatever your API backend parameters accepts, and as mentioned in the comments you don't need .live()
Make sure to replace YOUR_DJANGO_API_URL with your backend API URL

Related

How to send django url with parameters to ajax request?

Currently, I am sending url to the ajax as :
$('.togglebtn').on("click",function(){
console.log("Hello")
$.ajax({
type: 'GET',
url: "http://localhost:8000/toggle/2945016571198",
contentType: 'application/json',
success: function (data) {
appendData(data);
function appendData(data) {
var mainContainer = document.getElementById("switch_{{forloop.counter}}");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ;
mainContainer.appendChild(div);
}
}
}
});
Currently, I am sending request into a static url. Can we use {% url toggle i.id %} to set the url dynamically in the ajax request? Does this ajax function repeats at all or not?
Not in that way or fashion, the {% url toggle i.id %} is for the Django template, so that is executed when rendering the page server side. What you want to do is client side.
Your are also trying to use "switch_{{forloop.counter}}", which won't work unless you have multiple snippets of the 'click' function. Which I would advise against since it simply doesn't make sense. You define a function once and then use it. See first example.
Best thing I can think of is exposing a 'base url' in your template and use that in javascript.
For example in your Django template:
<script>
// Put the Django variable into javascript context.
toggle_base_url = {{ toggle_base_url_from_django_view_context }};
// Use it in your ajax url by combining strings.
$('.togglebtn').on("click",function(){
console.log("Hello")
var obj = $(this); // Save the clicked button for reference.
var objectId = obj.attr('id');
var buttonId = obj.attr('data-button-id');
$.ajax({
type: 'GET',
url: toggle_base_url + "/" + buttonId
contentType: 'application/json',
success: function (data) {
// Cannot use 'this' in this context (IIRC), use the obj var we assigned.
// Replace with something to find your parent container
// Could use have a attribute on your button that points to the container.
// Probably the number you use in the url?
var mainContainer = obj.parent('containerclass');
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ;
mainContainer.appendChild(div);
}
}
}
});
</script>
In your Django view you do something like this:
# Make a base url to reuse, remove the last part.
# So turn `/toggle/1` into `/toggle`
base_url = reverse('toggle', args=[1]).rsplit('/', 1)
context = {
'toggle_base_url_from_django_view_context': base_url,
}
return render(request, 'yourtemplate.html', context=context)

Retrieving data from myapifilms.com api

I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});

retrieving data from jsonp api that contains pages

I'm a little stuck on how I can retrieve all data from a jsonp api when the data is split in pages. The callback looks like this:
{
entries: [],
page: 1,
pages: 101,
posts: 10054
}
the code under only gets me results from page 1, but I would like to get results from all 101 pages. If I add a query to the url like : &page=2 or &page=3 I can access objects from that page only, what I'm trying to is access all objects from all pages in one go....
would appreciate some help :)
$.getJSON('http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=?', function(data){
var html = "";
$.each(data.entries, function(key,value){
html += '<p>' + value.navn + '</p>';
})
$('#test').html(html);
})
You can make first call to get the number of pages and in next calls you can loop through them.
Try below code
$.getJSON('http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=?', function(data) {
var pages = data.pages;
for (var i = 1; i <= data.pages; i++) {
$.getJSON('http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=?&page=' + i, function(data) {
$('#test').append("Page " + data.page + " Data >> ");
var html = "";
$.each(data.entries, function(key, value) {
html += '<p>' + value.navn + '</p>';
})
$('#test').append(html);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
You can use jsonp using $.ajax() not by $.getJSON(). and you have to declare your callback method in your javascript code
$("#btn").click(function(){
$.ajax({
url: "http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=myJsonpCallbackMethod",
dataType: "jsonp",
success: function( response ) {
//console.log( response ); // server response
}
});
});
function myJsonpCallbackMethod(data){
alert("Hello");
console.log( data ); // server response
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button id="btn">Click Me</button>

javascript passing values dynamically to a method jquery

$(document).bind('pageinit', function () {
var vendor_id = $.urlParam('vendor_id');
$.ajax({
type: "GET",
url: "http://testservice/testmenu",
data: {
vendor_id: vendor_id
},
error: function () {
alert("Could not get the menu : " + url);
},
success: function parseXml(xml) {
var jsonData = $.parseJSON(xml);
$(jsonData).each(function (index, post) {
$(post).each(function (index, row) {
var finalString = [];
for(var index = 0; index < row.menu.length; index++) {
finalString.push('<div id="collapsibleMenu" data-mini="true" data-role="collapsible" data-inset = "true" data-content-theme="g">');
finalString.push('<h3>' + row.menu[index].category_name + '</h3>');
finalString.push('<ul id="menuDetails" data-role="listview">');
for(var j = 0; j < row.menu[index].products.length; j++) {
var output = ['<li data-icon="addToCart" id="addToCart"> <p>' + row.vendor_menu[index].products[j].prod_name + '</p><p> $' + Number(row.vendor_menu[index].products[j].price).toFixed(2) + '</p>' + '</li>'];
finalString.push(output);
}
finalString.push('</ul></div>');
}
$('#output').append(finalString.join(''));
});
});
$('#output').trigger('create');
}
});
});
function test(prod_id) {
alert("entered test " + prod_id);
addToCart(prod_id, 1);
}
In the following code, where I am doing the following:
<a href="javascript:test("+row.menu[index].products[j].prod_id")">
This is obviously giving me an error. The point is, I need to pass the prod_id dynamically into the javascript test method. I am not sure how to do that. If I just call test without passing prod_id, it works great. Please help!
Try removing the quotes in the argument.
I think I might have figured it out.
Try this.
<a href="javascript:test(\''+row.menu[index].products[j].prod_id+'\')">
This looks like the perfect reason to use a template engine. You might use a Jade template like this:
for post in posts
for row in post
for menu in row.menu
#collapsibleMenu(data-mini="true", data-role="collapsible", data-inset="true", data-content-theme="g")
h3= menu.category_name
ul#menuDetails(data-role="listview")
for product in menu.products
li#addToCart(data-icon="addToCart")
a(href="#", data-product-id=product.prod_id)
p= product.prod_name
p= '$' + Number(product.price).toFixed(2)
Then you can simplify your $.ajax call to:
$.ajax({
// ...
dataType: 'json',
success: function(data) {
$('#output').append(templateFunction(data));
}
});
For the click event, use event delegation:
$('#output').on('click', 'a[data-product-id]', function() {
addToCart(Number($(this).data('product-id')), 1);
});
Easy, yeah? Now change all of your ids to classes, because ids must be unique and yours aren't!

Removing HTML code from a javaScript array?

Hi I have the following code in a javaScript file called songs:
var marchMD = new Array();
marchMD[0] = ["Save the Best for Last - Vanessa Williams"];
marchMD[1] = ["Informer - Snow"];
marchMD[2] = ["The Sign - Ace of Base"];
for (var i=0;i<marchMD.length; i++) {
songList = songList + '<p>' + marchMD[i] + '</p>';
}
$('#songs').html(songList);
Once this has been loaded, the follow javaScript in the file youtube reacts with the code above:
$(document).ready(function() {
$('#songs p').click(function(e) {
var $el = $(e.currentTarget);
var search = $el.html();
//alert(search);
//return;
var keyword = encodeURIComponent(search);
var yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + keyword + '&format=5&max-results=1&v=2&alt=jsonc';
$.ajax({
type:"GET",
url: yt_url,
dataType: "jsonp",
success: function(response) {
if(response.data.items) {
$.each(response.data.items, function(i, data) {
var video_id = data.id;
var video_frame = "<iframe width='420' height='315' src='http://www.youtube.com/embed/" + video_id + "' frameborder='0' type='text/html'></iframe>";
$("#ytVid").html(video_frame);
});
} else {
$("#ytVid").hmtl("<div id='no'> No Video</div>");
}
}
});
});
});
The alert that I have in the code above was a test to see if it would return anything and it doesn't. However, if I remove the href html tag from the code this works. The reason I have it is so when someone clicks one of the songs, it takes them to the top of the page to view that song in youtube.
Thanks
If you know that the element that contains your link will only ever contain your link, you could use text() to strip out the HTML formatting, like this:
var search = $el.text();
When you have the <a> in there, var search = $el.html(); includes the tag as well, not just the text. Try this:
$('#songs p').click(function(e) {
var search = $(this).find('a').html();

Categories

Resources