ajax & load are not working togeher - javascript

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 ;)

Related

Phonegap/Cordova - on("click") not firing

I'm creating a phonegap app.
This code is going to get by a json, the content on de database. Then I want to insert in the database the vote with the device.uuid. The problem is that the on("click") or on("touchstart") is not firing, not even in the alert(). Please help!!
$(document).ready(function() {
var url = "http://filmpix.esy.es/json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id;
$('.music-box').append("<button class='btn btn-default insert' value='" + id + "'>Votar</button>");
});
});
$(".insert").on("touchstart", function() {
alert("asdasd");
var music_id = $(this).val();
var dataString = "music_id=" + music_id;
$.ajax({
type: "POST",
url: "http://filmpix.esy.es/insert.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#insert").val('A votar...');
confirm("Tens a certeza que queres votar nesta musica?");
},
success: function(data) {
if (data == "success") {
alert("inserted");
$("#insert").val('Votado');
} else if (data == "error") {
alert("Não foi possível votar");
}
}
});
return false;
});
});
The return false statement should come after the function's "}" on your touch event.

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.

Load ajax after page load

This is the first time that I'm using ajax with jquery and I'm new on jquery I have a structure
$(document).ready(function(){
data_url = $('.lazy_content').attr("data-url");
data_id = $('.lazy_content').attr("data-target-id");
$.ajax({
url: data_url,
type: "POST",
beforeSend: function() {
$(".loaderDiv").show();
$("#" + data_id).html("");
},
success: function(data) {
$(data).each(function(index, el) {
$(".loaderDiv").hide();
$("#" + data_id).html(data);
});
}
});
});
<div class="lazy_content" data-url="/ajax/yorumlar/#Model.OtelBilgileri.seflink" data-target-id="ajax-content-1">
<h4 class="tur-main-baslik">COMMENTS</h4>
<div id="ajax-content-1"></div>
</div>
<div class="lazy_content" data-url="/ajax/trustyou/#Model.OtelBilgileri.seflink" data-target-id="ajax-content-2">
<h4 class="tur-main-baslik section-head">POSTS</h4>
<div id="ajax-content-2"></div>
</div>
as you see I have data-url this data url has my ajax-file and I'm getting my ajax file but after page loading nothing work..whats wrong with my code ?
Put your code inside $( document ).ready()
and I think you need to change your code like :
$(document).ready(function() {
data_url = $('.lazy_content').attr("data-url");
data_id = $('.lazy_content').attr("data-target-id");
$.ajax({
url: data_url,
type: "POST",
beforeSend: function() {
$(".loaderDiv").show();
$("#" + data_id).html("");
},
success: function(data) {
$(data).each(function(index, el) {
$(".loaderDiv").hide();
$("#" + data_id).html(data);
});
}
})
})
Or iterate with each class i.e .lazy_content
$( document ).ready(function() {
$('.lazy_content').each(function(){
data_url = $(this).attr("data-url");
data_id = $(this).attr("data-target-id");
$.ajax({
url: data_url,
type: "POST",
beforeSend: function() {
$(".loaderDiv").show();
$("#" + data_id).html("");
},
success: function(data) {
$(data).each(function(index, el) {
$(".loaderDiv").hide();
$("#" + data_id).html(data);
});
}
})
})
})
Depending on where the javascript is in the HTML the DOM may not have loaded at the point you run the script.
encapsulating your javascript within the jquery 'on DOM loaded' function ( $(document).ready( function() { ) will fix that problem, code as follows.
$(document).ready( function() {
$('.lazy_content').on("load", function() {
data_url = $(this).attr("data-url");
data_id = $(this).attr("data-target-id");
$.ajax({
url: data_url,
type: "POST",
beforeSend: function() {
$(".loaderDiv").show();
$("#" + data_id).html("");
},
success: function(data) {
$(data).each(function(index, el) {
$(".loaderDiv").hide();
$("#" + data_id).html(data);
});
}
})
});
});
Load evnet is Only usable in window,img element.
If You use Jquery load function, You can use callback function.
$("#target").load("append.html",function(){
// callback
});
another way, you append scripts below target html.

jquery iframe load dynamically

I am using following jquery script to load another url after successful ajax request.
$(document).ready(function() {
var $loaded = $("#siteloader").data('loaded');
if($loaded == false){
$("#siteloader").load(function (){
if(ad_id != undefined){
var req_url = base_url+'ajax/saveclick/'+ad_id+'/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function() {
$(preloader).show();
$('#adloading').remove();
},
complete: function() {
$(preloader).hide();
},
success: function(result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url+'userpanel/cpa/'+ad_id+'/');
}
});
}
else{
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
});
}
});
<iframe src="remote_url" id="siteloader"></iframe>
I don't want to run ajax again after changing src on iframe and i have also tried to stop it by $("#siteloader").data("loaded", "true");
Please suggest me a good solution for this. thanks.
If you only want to execute the "load" handler once
Simply add the line
$("#siteloader").unbind('load');
In the success callback.
If you want the "load" handler to be executed on each src change, you may do something like that :
$(document).ready(function () {
$("#siteloader").load(function () {
// Move the test in the event Handler ...
var $loaded = $("#siteloader").data('loaded');
if ($loaded == false) {
if (ad_id != undefined) {
var req_url = base_url + 'ajax/saveclick/' + ad_id + '/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function () {
$(preloader).show();
$('#adloading').remove();
},
complete: function () {
$(preloader).hide();
},
success: function (result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url + 'userpanel/cpa/' + ad_id + '/');
}
});
}
else {
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
}
});
});
Maybe your ad_id variable is not well defined / changed ...

Ajax : only call the ajax if element existing

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.

Categories

Resources