jquery problem? - javascript

i have this jquery problems i have had for days, im so new to this, so excuse my dumbness in this subject. thanks :))
html code:
<ul class="statuses">
<li id="set_23" class="message">
// this is meant to increase everytime you click the vote_up just like stackoverflow
<span class="vote_count">27</span>
<img src="img/uparrow.png" />
<img src="img/downarrow.png" />
</li>
</ul>
this is my jquery code:
$(document).ready(function() {
$('#statuses').delegate('.vote_up', 'click', function() {
//get the id
var the_id = $(this).closest('.message').attr('id').split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
// fade in the new vote_count
$(this).siblings("span.vote_count").html(msg).fadeIn();
// get the child <img> and set its src
$(this).children("img").attr("src", "img/uparrowActive.png");
}
});
});
});
EDIT: also the jquery fade.in and change of image src is not working, am i referencing the right span or class(the ajax request is working now)

First thing to jump-out:
<ul class="statuses">
and
$('#statuses')
... the # symbol in jQuery is the id-selector (same as CSS). Since your <ul> is set to class="statuses" then you'll need to use the class-selector:
$('.statuses')
That alone will break all your jQuery

From the jQuery docs:
The beforeSend, error, dataFilter,
success and complete options all take
callback functions that are invoked at
the appropriate times. The this object
for all of them will be the object in
the context property passed to $.ajax
in the settings; if that was not
specified it will be a reference to
the Ajax settings themselves.
So, try adding context: this to your ajax request options.

Change this
var the_id = $(this).closest('.message').attr('id').split('_').pop();
to this
var the_id = $(this).parents('.message').attr('id').replace('set_', '');
or alternatively
var the_id = $(this).parent().attr('id').replace('set_', '');
if you know that your link's parent element will always be ul.message.

Related

jquery .ajax() not sending string [duplicate]

Not sure what's wrong but I'm getting this error from my chrome console:
jquery-3.2.1.slim.min.js:1244 jQuery.Deferred exception: $.ajax is not a function TypeError: $.ajax is not a function
at HTMLDocument.<anonymous> (file:///C:/Users/Adam/Desktop/UseTime/js/example.js:3:7)
at j (file:///C:/Users/Adam/Desktop/UseTime/js/jquery-3.2.1.slim.min.js:1193:55)
at k (file:///C:/Users/Adam/Desktop/UseTime/js/jquery-3.2.1.slim.min.js:1199:45) undefined
r.Deferred.exceptionHook # jquery-3.2.1.slim.min.js:1244
jquery-3.2.1.slim.min.js:1247 Uncaught TypeError: $.ajax is not a function
at HTMLDocument.<anonymous> (example.js:3)
at j (jquery-3.2.1.slim.min.js:1193)
at k (jquery-3.2.1.slim.min.js:1199)
From this JavaScript:
$(function() { //when the DOM is ready
var times; //declare global variable
$.ajax({ //set up request
beforeSend: function (xhr) { //before requesting data
if (xhr.overrideMimeType) { //if supported
xhr.overrideMimeType("application/json"); // set MIME to prevent errors
}
}
});
//funciton that collect data from the json file
function loadTimetable() { //decalre function
$.getJSON('data/example.json') //try to collect json data
.done(function (data) { //if succesful
times = data; //store in variable
}).fail(function () { //if a problem: show message
$('#event').html('Sorry! we couldnt load your time table at the moment');
});
}
loadTimetable(); //call the function
//CLICK ON TEH EVENT TO LOAD A TIME TABLE
$('#content').on('click', '#event a', function (e) { //user clicks on place
e.preventDefault(); //prevent loading page
var loc = this.id.toUpperCase(); //get value of id attr
var newContent = "";
for (var i = 0; i < times[loc].length; i++) { // loop through sessions
newContent += '<li><span class = "time">' + times[loc][i].time + '</span>';
newContent += '<a href = "descriptions.html#';
newContent += times[loc][i].title.replace(/ /g, '-') + '">';
newContent += times[loc][i].title + '</a></li>';
}
$('#sessions').html('<ul>' + newContent + '</ul>'); // Display Time
$('#event a.current').removeClass('current'); // update selected link
$(this).addClass('current');
$('#details').text('');
});
//CLICK ON A SESSION TO LEAD THE DESCRIPTION
$('#content').on('click', '#sessions li a', function (e) { //click on session
e.preventDefault(); // prevent loading
var fragment = this.href; //title is in href
fragment = fragment.replace('#', ' #'); //Add Space before #
$('#details').load(fragment); //to load info
$('#sessions a.current').removeClass('current'); //update selected
});
//CLICK ON PRIMARY NAVIGATION
$('nav a').on('click', function (e) { //click on nav
e.preventDefault(); //prevent loading
var url = this.href; //get UR: to load
$('nav a.current').removeClass('current');
$(this).addClass('current');
$('#container').remove(); //remove old
$('#content').load(url + ' #container').hide().fadeIn('slow'); // add new
});
});
I'm not sure if it's an issue with the way I'm initiating .ajax or if my jquery isn't correctly implemented. I think it is. Any Thoughts?
edit: here's the html that goes with the script above
<!DOCTYPE html>
<body>
<header>
<h1>UseTime</h1>
<nav>
HOME
PROFILE
MANAGE TASKS
TIME TABLE
</nav>
</header>
<section id="content">
<div id="container">
<div class="third">
<div id="event">
<a id="class1" href="class1.html"><img src="" alt="class1" /> Class 1 </a>
<a id="class2" href="class2.html"><img src="" alt="class2" /> Class 2 </a>
<a id="class3" href="class3.html"><img src="" alt="class3" /> Class 3 </a>
</div>
</div>
<div class="third">
<div id="sessions"> Select a Class from the left </div>
</div>
<div class="third">
<div id="details"> Details </div>
</div>
</div>
<!-- container -->
</section>
<!-- content -->
<script src="js/jquery-3.2.1.slim.min.js"></script>
<script src="js/example.js"></script>
</body>
You are using slim version of jQuery. It Doesn't support ajax Calling.
Use
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
instead of it.
Slim build
Sometimes you don’t need ajax, or you prefer to use one of the many
standalone libraries that focus on ajax requests. And often it is
simpler to use a combination of CSS and class manipulation for all
your web animations. Along with the regular version of jQuery that
includes the ajax and effects modules, we’ve released a “slim” version
that excludes these modules. All in all, it excludes ajax, effects,
and currently deprecated code. The size of jQuery is very rarely a
load performance concern these days, but the slim build is about 6k
gzipped bytes smaller than the regular version – 23.6k vs 30k. These
files are also available in the npm package and on the CDN:
https://code.jquery.com/jquery-3.1.1.slim.js
https://code.jquery.com/jquery-3.1.1.slim.min.js
Referred from jQuery Blog
jQuery 3 slim version doesn't support ajax.
According to the release docs,
Along with the regular version of jQuery that includes the ajax and
effects modules, we’re releasing a “slim” version that excludes these
modules. All in all, it excludes ajax, effects, and currently
deprecated code.
To use .ajax method, simply use the full version one.
Try this one (jquery-3.2.1.min.js) instead of slim (jquery-3.2.1.slim.min.js)
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

How to display item from server once a link is clicked

student here! So I created a function that runs an $.ajax request, and for each item, I output html to the DOM. Well, check it out:
function getLinks (){
let blogLinks;
$.ajax(settings).then(function(data, status, xhr){
data.forEach(function(item, i, arr){
let id = item._id;
if (item.title){
blogLinks = `<li><a class="link" href=#${item.title}>${item.title}</a></li>`
$($findUl).append(blogLinks);
}
})
})
}
this var might be useful info as well:
let $blogViewAll =
$(`<div class="blog-view">
<h3>Check Out These Blogs</h3>
<div class="column-1">
<ul class="link-list"></ul>
</div>
<div class="column-2"></div>
</div>`);
let $findUl = $($blogViewAll).find('.link-list');
It's doing exactly what I want it to do and appending the links to the page. Now I want to click on the link and have the message body display on the page. So I'm trying this:
$findUl.on('click', function(e){
$.ajax(settings).then(function(data, status, xhr){
data.forEach(function(item, i, arr){
//since you clicked on that link
//I should look at what you clicked
//match it to the corresponding obj{item.body}
//and display it, but I don't know how to match and grab :(
})
})
});
And that's where I'm stuck! Any suggestions? Thanks!!!
(i'm using the tiny-za server btw)
You can access the current link the user clicked on in your initial argument e, via the property e.currentTarget:
$findUl.on('click', function(e){
// this gives you the DOM node that was clicked:
console.log(e.currentTarget);
}
A little shortcut to get the title using jQuery:
$findUl.on('click', function(e){
var title = $(e.currentTarget).text();
}
Another note, you should really only be loading the data from the server in that ajax call once, not every time something is clicked (which is sloooow).
I'd recommend loading the data into an object when the page loads, then using the obejct properties to append to the DOM. You'll be able to access that same object in future click handlers

Get the data-url correctly using javascript function

I am creating a delete comment function and
this are the pieces of html for a delete comment functionality.
<div id="comment-area">
<div class="list-border">
<small class="mdl-button delete-comment js-delete-comment pull-right" data-url="http://myproject.com/comment_controller/delete_comment/12/6">
x
</small>
</div>
<div class="list-border">
<small class="mdl-button delete-comment js-delete-comment pull-right" data-url="http://myproject.com/comment_controller/delete_comment/13/6">
x
</small>
</div>
</div>
And this is the function for delete a comment, which is automatically loaded when document is ready,
function delete_comment () {
$('.delete-comment').click( function (e) {
var url = $('.delete-comment').attr('data-url');
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function (data) {
$('#comment-area').html(data.comments);
delete_comment();
},
error: function () {
alert('error');
}
});
});
}
The problem with this function from the given html above, if I'm going to click on .delete-comment with
data-url="http://myproject.com/comment_controller/delete_comment/13/6" take note on this "13/6", the javascript function delete_comment(),
in this line
var url = $('.delete-comment').attr('data-url');
chose to get the data-url="http://myproject.com/comment_controller/delete_comment/12/6" take note also this "12/6", to see the difference, instead of the data-url of .delete-comment I clicked.
In short, this function always chose the first-child div small, whatever small.delete-comment I'm going to click.
What was the best solution for this?
Try
var url = $(this).attr('data-url');
You are getting the attribue value by className and multiple elements have same class so the attribute value for first element found in dom is being returned.
So you need to get the value of element which is clicked and you can use this to get the value of clicked element.
A more robust way to approach this would be to use the jQuery .data() function.
var url = $(this).data('url');
This will pick up any dynamically added/updated url that may have changed via JavaScript, but not updated in the DOM attribute.

If div text equals certain text do something?

Cannot for the life of me get this to work. Even when removing the AJAX POST function, it still doesn't work. There is no alert or anything. Here is the JSFiddle and code:
HTML
<div class="notification">
<div class="title gooddog">test</div>
<div class="reason helvetica"></div>
</div>
<script>
var interval = setInterval(function(){
var Winner = $(".notification .title gooddog").text();
if(Winner == "test") {
$.ajax({
url: "Won.php",
type: "POST",
data: { Winner : Winner }
})
.success(function(data) {
console.log('foo', data);
});
}
},1000);
</script>
It is meant to trigger/check the div text for changes every 1 seconds, but as you can see, it's doing nothing..
var Winner = $(".notification .title gooddog").text();
should be
var Winner = $(".notification .title.gooddog").text();
jsfiddle http://jsfiddle.net/abwp5u21/8/
You've got several issues...
You are using jQuery syntax but you are not including the jQuery plugin...at least not in the fiddle
Not an issue in this case, but if you want to get whatever is inside a div use the html function rather than the text function
As #Cattla pointed out in her answer to the proper "multi-class" selector is .title.gooddog
I wouldn't be surprised if you had more issues on the server-side as well. Here's an updated JS Fiddler

Swipe JS not working with populated content

I'm using Swipe JS 2.
If I make the HTML structure myself, it works perfectly, but if I populate the HTML with content coming from the jQuery, it stops on the second slide.
My HTML structure:
<div id="map" class="swipe">
<div class="swipe-wrap">
<div class="city" id="current">
<div class="location">Current Location</div>
</div>
</div>
</div>
<nav>
<ul id="position">
<li class="on">Current location</li>
</ul>
</nav>
This is my structure on the jQuery.
$.getJSON("http://localhost/locations.php", function(localdata) {
$.each(localdata.locations, function(i, geolocal){
var vcountry = geolocal['country'];
var vregion = geolocal['region'];
var vcity = geolocal['city'];
country = vcountry.replace(' ','_');
region = vregion.replace(' ','_');
city = vcity.replace(' ','_');
// THE PROBLEM IS HERE. IF I USE AJAX OR GETJSON HERE INSIDE THE OTHER GETJSON, THE SWIPE IS BROKEN.
$.ajax({
type: "GET",
url: "http://localhost/remotexml.php?url=http://www.yr.no/place/"+ country +"/"+ region +"/"+ city +"/forecast.xml",
success: function(xml) {
var localName = $(xml).find('location name').text();
$('#map div.swipe-wrap .city:last-child').after('\n<div class="city">\n<div class="location">'+localName+'</div>\n</div>\n</div>');
$('#position').append('\n<li>'+localName+'</li>');
}
});
});
})
.success(function() { })
.error(function() { })
.complete(function() {
var slider =
Swipe(document.getElementById('map'), {
auto: 5000,
continuous: true,
callback: function(pos) {
var i = bullets.length;
while (i--) {
bullets[i].className = ' ';
}
bullets[pos].className = 'on';
}
});
var bullets = document.getElementById('position').getElementsByTagName('li');
});
What happens is: when I see the HTML created by the jQuery, is perfect. jQuery is creating the divs inside the slider and the lis inside the list. Perfect. When I run the website, load and starts perfectly, but then, when changes slide, stops on the second slide, and the second slide is blank. Nothing there. Even thought there is content on the HTML.
The most weird part? If I start the Developer Tools (Command + Alt + I on Chrome), right after the website loads, it WORKS PERFECTLY. What kind of bizar behavior is this? :D
Anybody can help me to make this Swipe JS to run?
If you're populating the slider with content via an AJAX request, then you will most likely have to wait until that AJAX request is finished before you build the slider - i.e. in the success callback of your AJAX function.

Categories