Ajax : only call the ajax if element existing - javascript

for example i have a .ajax() function like below:
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
It works fine,but i'd like to add a if statement to detect whether the $(".numberOfProfile0").html() exist or not, and will only execute when the $(".numberOfProfile0").html()exist
I tried below but it doesn't seem right
if ($(".numberOfProfile0").length) {
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
}
- UPDATE:
Let's show the whole application
This is the function:
if($(".numberOfProfile0").html().length){
function trend1() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
}
$.when(trend1()).done(function(trend1_data) {
//do something
}

Please remember jQuery selector is not a string. Using jQuery, the correct way to do this is something like $('.selector').val().length , $('.selector').html().length
Use $(".numberOfProfile0").html().length > 0 in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="numberOfProfile0">lorem</div>
<script>
if ( $(".numberOfProfile0").html().length > 0 ) {
alert("success");
// your function:
//function trend() {
//return $.ajax({
// url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + //$(".numberOfProfile0").html(), //getting the api
// type: 'get',
//success: function(data) {
//}
// });
// }
}
</script>

I think it should be
function trend() {
if ( $(".numberOfProfile0").length ) {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}//if()
else
{
return false; //or any other appropriate value
}
}//trend()

use ($(".numberOfProfile0").html() !== '') that mean if element with class .numberOfProfile0 is not empty
function trend() {
if ($(".numberOfProfile0").html().trim() !== '') {
$.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
}

You are doing it wrong! You are defining the function inside the if, where as you should be calling it inside if.
First define the function.
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
Then call it.
if ($(".numberOfProfile0").length) {
trend();
}
OR
You can put the if check inside the function.
function trend() {
if ($(".numberOfProfile0").length) {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
else{
return -1;
}
}

You can use .is() within $.when() at ternary to return trend() if element exists, else return null to $.when(); handle element not existing in DOM. Note, you can remove success option at $.ajax() if response is handled at .done()
function trend() {
return $.ajax({
url: "/dashboard/getTrend'"
+ "?period=30d"
+ "&profileId="
+ $(".numberOfProfile0").html(), //getting the api
type: "get"
});
}
$.when($(".numberOfProfile0").is("*") ? trend() : null)
.done(function(trend1_data) {
if (trend1_data === null) {
// handle `$(".numberOfProfile0")` not existing in `DOM`
} else {
// handle `trend1_data` not being `null`, element exists
// do something
}
})

You should check the existence of the element inside the before_send callback for aJax and cancel the aJax request if not.
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(),
type: 'get',
before_send: : function( xhr ) {
if ($(".numberOfProfile0").length > 0 && $(".numberOfProfile0").html().trim() == ''){
return false;
}
}
success: function(data) {
}
});
}
The above code snippet should work in your case.

Related

How do I pass the parameter of whichever list object I click on?

$.ajax({
url: "/userList",
type: "GET",
success: function(data){
console.log(data);
if (!data) alert("ERROR")
else{
for (let j=0;j<data.length;j++) {
user = data[j];
console.log(data[j]);
$("#userList").append("<button> <a href='javaScript:getUserProfile(" + data[j] + ")'>" + data[j] + "</button>");
}
}
} ,
dataType: "json"
});
It keeps saying data[j] is undefined whenever i try to pass it in. I have done print statements and such but I can't find the root of the issue.
Can you try this?
$.ajax({
type: "GET",
url: "/userList",
dataType: 'json',
success: function(data){
if (!data)
alert("ERROR")
else{
for (j=0;j<data.length;j++) {
var user = data[j];
console.log(user);
$("#userList").append("<button> <a href='javaScript:getUserProfile(" + user + ")'>" + user + "</button>");
}
}
}
});
Also, make sure that the url is correct. Looks like is not correct....

Handling of click events in jQuery(For Like and Unlike button)

I am trying to create a Like-Unlike system using AJAX and jQuery. The "like" event seems to work properly, but when I want to "unlike" the event is not responding. Any suggestions to solve this problem is appreciated.
$(document).ready(function() {
$(".like").click(function() { //this part is working
var item_id = $(this).attr("id");
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('like');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('liked');
$('a#' + item_id).html(data);
}
}
});
});
$(".liked").click(function() { //this part is not working
var item_id = $(this).attr("id");
console.log(item_id);
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('liked');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('like');
$('a#' + item_id).html(data);
}
}
});
});
});
$(".like") and $(".liked") are retrieved when the document is ready but don't get updated when you add/remove classes from an element.
If you assign a more generic class the vote elements like 'like-toggle' you would be able to do the following:
$(document).ready(function() {
$('.like-toggle').click(function(event) {
if ($(event.target).hasClass('like') {
// Call your unlike code, replace like with liked.
} else {
// Call your like code, replace liked with like.
}
});
});
This will work because the like-toggle class never gets removed from the elements and thus the elements which are present when the document is ready will keep functioning.

ajax & load are not working togeher

I want to check each time user access when page loading, sessions.php is working and return true or false but load is not working with ajax...
var section = $("#header a");
section.on('click', function() {
$.ajax({
type: "POST",
url: "/particley/global/post/sessions.php",
success: function(html) {
if (html == 'true') {
$('#load').load(section.id + ' #load');
window.history.pushState(this.id, this.id, this.id);
if (this.id == '/p/sign-out') {
window.location.assign("/p");
}
} else {
window.location.assign("/p/sign-out");
}
}
});
});
var section = $("#header a");
section.click(function(){
$('#load').load(this.id + ' #load', function() {
$.ajax({
type: "POST",
url: "/particley/global/post/sessions.php",
success: function(html)
{
if (html != 'true') {
window.location.assign("/p/sign-out");
}
}
});
});
window.history.pushState(this.id, this.id, this.id);
if (this.id == '/p/sign-out') {
window.location.assign("/p/sign-out");
}
});
for this line
$('#load').load(section.id + ' #load');
did you mean:
$('#load').load(section.attr("id") + ' #load');
to retrieve the attribute id ?
2 cents ;)

JavaScript/jQuery callback using Ajax

I'm having trouble with my functions running before Ajax requests (the first to a local JSON, the second to an online resource) have finished.
In this example I want countTheMovies to run at the end after my application has got all the information it needs and populated the divs. Instead it's running straight away.
I tried to delay it using an if condition, but with no joy. I've also tried with callbacks, but think I must be getting those wrong (I'm assuming callbacks are the answer). I'm aware of timed delays, but because in the actual project I'm sourcing 250+ movies (and because a timed delay seems like cheating) I thought I'd ask here instead.
Can anyone recommend JavaScript or jQuery code to fix this problem?
$(function(){
getMovieList();
});
function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
if (isLast) countTheMovies();
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
A plunker of my failings: https://plnkr.co/edit/0mhAUtEsaOUWhkZMJqma?p=preview
You've almost got it!
The same way that you call getMovieInfo in the success callback of getMovieList, you should be calling countTheMovies in the success callback of getMovieInfo.
As Jacob said above, move the countTheMovies call inside the AJAX request.
$(function(){
getMovieList();
});
function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
if (isLast) countTheMovies();
}
}
});
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
Just put your countTheMovies() logic inside of the success callback of the AJAX request in getMovieInfo if you want it to run on success.
You can call your countTheMovies() function from inside the success field of your Ajax call. This way it will make the function call when you intend it to.
Try out this
$(function(){
getMovieList();
});
function getMovieList() {
$.when( $.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
}) ).then(function( data, textStatus, jqXHR ) {
countTheMovies();
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}

Json data in a next and previous button

I have to use a AJAX call to get Json data after clicking next and previous buttons. Json data should contain blog content displayed after clicking next or previous. Any suggestions how my function should look like? So far I have only:
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).success(function (data) {
$.each(data, function (key, val) {
$('#blogcont').append(key+ val);
});
return false;
});
}
And my Json file is only a test file:
{"one":"test1", "two":"test2", "three":"test3" }
Sorry I am a beginner!!!!
Thanks
Your $.ajax() syntax is incorrect
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
}
});
return false;
}
or
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
});
return false;
}
Try this
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += '<p>' + key + ':' + val + '</p>';
});
$('#blogcont').html(content)
.find('p')
.hide()
.first().show();
$('button.next').click(function() {
$('#blogcont').find('p:visible')
.hide()
.next('p').show();
});
});
return false;
}
How about storing the JSON data as a variable, which you can then access using an index on click?
var jsonData;
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function (data) {
jsonData= data;
}
});
var clickIndex = 0;
$('.prev').click(function() {
if(clickIndex > 0) {
clickIndex -= 1;
}
get(clickIndex);
});
$('.next').click(function() {
clickIndex++;
get(clickIndex);
});
Your get function would then accept the index and find the JSON property:
function get(i) {
var item = jsonData[i];
}
Note that you would need to add an if statement to check whether you have reached the index limit on click of .next. Also, this is fine for a test JSON file, but a better solution would be to be able to request just one relevant item from a web service returning the JSON.

Categories

Resources