I'm trying to get the year of a film given its title using IMDB's API and then appending the year in parenthesis next to the title.
There's some fundamental JS or AJAX thing that I'm screwing up. Any help would be much appreciated!
This is my code: jsFiddle
HTML
<ol>
<li>Jaws</li>
<li>The Lord of the Rings</li>
</ol>
jQuery
function getYear(title)
{
$.ajax({
url: "http://www.imdbapi.com/?t=" + title,
dataType: 'jsonp',
success: function(data){
var year = data.Year;
}
});
}
$("li").each(function() {
var text = $(this).text();
getYear(text);
$(this).append(" ("+year+")");
});
Your code is calling the AJAX function, but immediately going on to update the page before the asynchronous function returns. You need to include the code that updates the page in the callback to the AJAX function so that it executes when the data is ready.
I have reworked your code to this:
function getYear(title)
{
$.ajax({
url: "http://www.imdbapi.com/?t=" + $(title).text(),
dataType: 'json',
success: function(data){
var year = data.Year;
var text = $( this ).text();
$(title).append(" ("+year+")");
}
});
}
$( "li" ).each(function() {
getYear(this);
});
Which works successfully on this fiddle
Related
I made a function that is invoked for the lack of better words from a page, lets call it Page1, the function is called when a button is clicked, at the end of said function it calls another one that creates (or should seeing I haven't been able to test it) a html and appends it to a div with a #lista id.
The problem is that this div is another page (Page2), so I don't know if there is some syntax like in ajax where you specify where you want those values to go, so basically page 1 calls a function (on another file just in case) that function calls another and the result of that function goes on Page1 (another file, again just in case)
Here is my jQuery/JS code to further illustrate:
$("#btnAceptar").click(function() {
var idlab = $('#txtNumLab').val(),
capacidad = $('#txtCapacidad').val(),
carrera = $('#txtCarrera').val(),
ubicacion = $('#txtUbicacion').val();
var request = $.ajax({
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'addLab',
'pIdLab':idlab,
'pCapacidad':capacidad,
'pCarrera':carrera,
'pUbicacion':ubicacion},
dataType: 'json',
success: function(response){
alert('exito')
agregar();
}
});
});
This function should affect a element with id #Lista on Page2.
function agregar(){
var div = $( "#lista" ).append( "<div class='box'>
<p>Lab #'numero'</p>
<p class='info'><a href='#' id='lnkInfo'>Info</p></a>
<p class='info'><a href='reservarLab.html'>Reservar</p></a>
</div>" );
div.id = querySelectorAll('#lista > div').length +1;
var numero = div.id;
$('#numero').append(div);
}
Thanks a lot in advance!
Yes you can get content from another page using jQuery:
Ajax request gets the entire file, but you can filter the content once it's retrieved:
$.ajax({
url:href,
type:'GET',
success: function(data){
$('#content').html( $(data).find('#IDofDivToFind') );
}
});
Second Approach (Untested)
You can use JQuery .load() method:
$( "#content" ).load( "ajax/test.html div#content" );
Reference:
http://api.jquery.com/load/
my problem is when i try to show a value by ajax calling,it shows the value to "generic" class but when i try to show it on the parent row it is not showing anything.
here is my ajax code
$.ajax({
type: 'POST',
url: 'http://localhost/medical/index.php/purchase/test',
data: 'data=' + pid,
success: function() {
$.get('http://localhost/medical/index.php/purchase/test', function(data) {
$(this).parents('tr').find('.generic').html(data); // doesn't show the value
$( ".generic" ).html(); // this show the value but in all table row
});
}});
Thanks in Advance
The problem is called scope. this in context of the anonymous function means something else than it means outside. You can do it like this
var that = this;
$.ajax({
...
success: function() {
$.get(..., function(data) {
$(that).parents('tr').find('.generic').html(data);
});
}
});
Having a problem with a webapp i've been working on lately, and it has to do with ajax reloading breaking javascript.
I have the following Ajax Call
$.ajax({
type: "POST",
url: "/sortByIngredient/",
data: JSON.stringify(
{
selectedIngredients: tempDict
}),
contentType: "application/json; charset=utf-8",
success: function(data){
var curList = $("#drinkList").contents();
console.log(curList);
$("#drinkList").empty()
$("#drinkList").append(data)
and the following Html UL
<div id = "drinkList" class="d-list">
<ul>
<li id='someID'>some Item</li>
<li id='someID2'>some Item2</li>
</ul>
</div>
I also have a jQuery callback set to activate on clicked list items. On initial loading, all works well. Once the ajax call occurs, and replaces the contents of #drinkList with another list, formatted identically. In case anyone is curious, here is the onClick callback:
$("li").click(function()
{
window.currentDrink = $(this).attr("id");
console.log(window.currentDrink);
$.ajax({
url: "/getDrink/" + $(this).attr("id"),
type: "get",
success: function(data){
$("#ingDiv").html(data);
}
});
});
After I make that Ajax call, the list modifies correctly, but after that, no more javascript seems to work. For example,the console.log is not called when i click on a list item, and the proper view doesnt update(#ingDiv, as shown in the above call)
Is my changing the HTML through Ajax breaking the javascript somehow?
Am I missing something obvious? If it isn't clear already, I am not a web developer.
use event delegation like this -
$('#drinkList').on('click','li',function(){
// do your stuff here
});
As you are not a web developer - This is what your code should look after changes
$('#drinkList').on('click', 'li', function () {
window.currentDrink = $(this).attr("id");
console.log(window.currentDrink);
$.ajax({
url: "/getDrink/" + $(this).attr("id"),
type: "get",
success: function (data) {
$("#ingDiv").html(data);
}
});
});
http://learn.jquery.com/events/event-delegation/
http://api.jquery.com/on/
i have this jquery code with an ajax request that works fine, but the jquery is not displaying the results(vote_count) and changing the upvote image, just like stackoverflow:
jquery code:
$(function(){
$("a.vote_up").click(function(){
//get the id
the_id = $(this).attr('id');
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_up&id="+$(this).attr("id"),
url: "ajax/votes.php",
success: function(msg)
{
//echo the votes count
$("span#votes_count"+the_id).html(msg);
//replace the new vote count
$("span#votes_count"+the_id).fadeIn();
//replace the image with active arrow
$("#vote_up"+the_id).attr("src", "img/upvoteActive.png");
}
});
});
the html code:
<li class ="record">
<span class="vote_count">$net_vote</span>
</li>
to clarify everything again, the ajax request is fine its upvoting the right answer, the problem is in the success bit of the ajax, the new vote count is not showing, and the image is not being replaced to an active arrow(just like stack overflower) thanks :))
Your selectors in the success callback are all wrong. You have <span class="vote_count">...</span> but then try to update it's value as if it had an id: $("span#votes_count"+the_id)...
You probably want your code more like:
success: function(msg) {
//echo the votes count
$("span.vote_count#"+the_id).html(msg);
//replace the new vote count
$("span.vote_count#"+the_id).fadeIn();
//replace the image with active arrow
$(".vote_up#"+the_id).attr("src", "img/upvoteActive.png");
}
So as you can see, you'll also want to add the id of the object into the .vote_count element as well.
Update:
To be clearer, here is the updated markup:
<span class="vote_count" id="$id">$net_vote</span>
<img src="img/uparrow.png" />
<img src="img/downarrow.png" />
And here is the updated javascript:
$(document).ready( function() {
$("a.vote_up").click(function(){
//get the id
var the_id = $(this).attr('id');
//the main ajax request
$.ajax( {
type: "POST",
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function( msg ) {
$("span.vote_count#"+the_id).html(msg).fadeIn();
$(".vote_up#" + the_id + " img").attr("src", "img/upvoteActive.png");
}
} );
} );
} );
In your jQuery code you use #votes_count but the html does not have an id but a vote_count class (without the s).
So it should read span.vote_count
same with the upvote, you use an id to target it but it has a class..
You were incorrectly targetting the spans, and also, sending get parameters over a post request. I have fixed below:
$(function(){
$("a.vote_up").click(function(){
//get the id
the_id = $(this).attr('id');
//the main ajax request
$.ajax({
type: "POST",
data: {'action' : 'vote_up','id' : $(this).attr("id")} // here
url: "ajax/votes.php",
success: function(msg)
{
//echo the votes count
$("span.vote_count").html(msg); //here
//replace the new vote count
$("span.vote_count").fadeIn(); // here
//replace the image with active arrow
$(".vote_up").find(the_id).attr("src", "img/upvoteActive.png"); // and here
}
});
});
I'm building a tagger. After a user submits a tag, ajax returns:
{"returnmessage":"The Ajax operation was successful.","tagsinserted":"BLAH, BLOOOW","returncode":"0"}
I want to take the tagsinserted and loop through it, and during each loop take the item in the list and insert it on the HTML page. suggestion on how to do this right?
Here is the current code:
$("#tag-post").click(function(){
// Post $('#tag-input').val()
$.ajax({
url: '/tags/ajax/post-tag/',
data: { newtaginput : $('#tag-input').val(), userid : $('#userid').val()},
success: function(data) {
// After posting
alert('done');
}
});
});
You can do something like this:
$("#tag-post").click(function(){
$.ajax({
url: '/tags/ajax/post-tag/',
data: {newtaginput : $('#tag-input').val(), userid : $('#userid').val()},
success: function(data) {
$.each(data.tagsinserted.split(', '), function(i, v) {
$("<div></div>").text(v).appendTo("#tagHolder");
});
}
});
});
You can loop through the tags by calling data.tags.split(',') and looping through the array it returns.
You can insert tags to the page by calling $('<li />').text(tag).appendTo('someSelector').