jQuery load element not working for ajax - javascript

I need to preload ajax data before attaching it to a div and for that I have this code:
$.ajax({
url: 'ajax.php',
data: { modelID:id },
type: 'post',
success: function(result){
$(result).load(function(){
$('.view_'+id).html(result)
$('.view_'+id).find('.brandModelGallery').bxSlider({})
$('.view_'+id).addClass('loaded')
})
}
})
And this doesn't return anything. If write it as $('.view_'+id).load(result) then I can see all the contents of result in console as a syntax error so it fetches them alright, but not this way. Why is that?

I've create an example on jsfiddle
Html:
<div id="d1"></div>
<div id="d2"></div>
js:
$.ajax({
url: './',
data: { modelID: '1' },
type: 'post',
success: function(result){
console.log(result);
$('#d1').html(JSON.stringify(result));
// A fake object as your result.
var bxSlider = $('<ul class="bxslider"><li><img src="https://i.imgur.com/KsV6jS5.png" /></li><li><img src="https://i.imgur.com/bqcK47I.png" /></li></ul>');
// Do thing only when all img loaded.
var unLoadimges = bxSlider.find("img").length;
bxSlider.find('img').load(function() {
--unLoadimges;
console.log("loaded, left: " + unLoadimges);
if (unLoadimges === 0) {
bxSlider.appendTo($("#d2")).bxSlider();
}
});
}
})
When you append img element to your page, it doesn't mean its loaded. Listen to its load event.
Edit: Just make the bxSlider works on my example now.
Not sure if there's a better way to check whether all images loaded or not.

Related

Run if/else script with only part of a URL

I am trying to edit my Javascript to pull different data via an AJAX call based upon only part of a URL. Currently, my if/else script looks like this:
if (window.location.href=="london") {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data-london.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
} else {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
}
This doesn't work as currently written since if window.location.href=="london") is only part of the URL, not the full URL. Is there a way to edit this script to run only based off of the last bit of the page URL? For example: /london, /nw, etc.? Is there a better way to accomplish this task?
Instead of
if (window.location.href=="london") {
Use below code
var URL = window.location.href;
if(URL.indexOf("london") !== -1)
The .indexOf function will find out a substring is exist or not in a string. And in your case you wants "london" is exist or not in URL.
I assume you are asking, when the url something like 'https://example.com/london' , so you just want to include or get the value of london. below code will help to provide always last bit of value of the url.
window.location.pathname.splitOnLast('/')[1]
it will give you '/london'. or you can just check the existence of theondon in the url.
Firstly it is not necessary to use if else like above
You can use like below
var dataurl = document.URL
$.ajax({
url: 'somepage.php',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});
in somepage.php file you can process the data however you want based on the dataurl
And also in javascript you can do like below
var urlTopost="other.php";
if(document.url.indexOf("london")!==-1)
{
urlTopost="london.php";
}
$.ajax({
url: urlTopost,
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});

JQuery .show animation not working

I got another problem with my code :)
var limit = 15;
$(document).ready(function() {
var data = 'clients=&categories=&keywords=&limit='+limit;
$.ajax({
type: 'POST',
url: 'index.php?ind=work&op=get_list',
data: data,
success: function (data) {
$('.list').html(data);
$('.thumb').click(function() {
var idz = 'id='+$(this).attr('id');
$.ajax({
type: 'POST',
url: 'index.php?ind=work&op=get_work',
data: idz,
success: function (data) {
$('.work').show('slow').html(data);
}
});
});
}
});
});
The HTML code is simple:
<div class=\"center wide work\" style=\"display: none;\">
</div>
When I click on a div.thumb, all needed information is loaded with no problem. The problem is that there is no transition animation. Please help with that. Thanx in advance!
The only reason I can think of is the element is already displayed, so try
$('.work').hide().html(data).show('slow');

How to replace .live() method with .on() method

Hei.. I have a function to load more news. Since jquery-1.9.1.min.js this function was working alright, but now I have to replace it with .on() method and I still can't get it work.
Here is the code:
// Load more news feed
$(function(){
var page = 1;
$.ajax({
type: "POST",
url: "data.php",
data: "page=profile&get_news_feed=true",
dataType:'json',
success: function(data){
$("#the_news_feed").html(data.news_feed);
if(page <= data.total_pages){
$("#the_news_feed").after('<button id="load_more_feed" class="btn btn-primary btn-large" style="width: 100%;margin-top:10px">Load More</button>');
}
}
});
$("#load_more_feed").live("click", function(){
var next = page+=1;
$.ajax({
type: "POST",
url: "data.php",
data: "page=profile&get_news_feed=true&page_num="+next,
dataType: "json",
success: function(data){
$("#the_news_feed").append(data.news_feed);
if(next == data.total_pages){
$("#load_more_feed").remove();
} else {
$("#load_more_feed").html("Load More");
}
},
beforeSend: function(){
$("#load_more_feed").html("Loading...");
}
});
});
});
I tryed to replace:
$("#load_more_feed").live("click", function()
with
$("#the_news_feed").on("click", "load_more_feed", function()
but I still can't get it work. What am I doing wrong? Thank you!
I display this function with id="news_feed" so here was the problem
<div class="tab-pane fade" id="news_feed">
<div id="the_news_feed"></div>
</div>
Final solution is $("#news_feed").on("click", "load_more_feed", function()
Thank you guys!
Actually, you're missing the # in the id selector.
$("#the_news_feed").on("click", "load_more_feed", function()
must be
$("#the_news_feed").on("click", "#load_more_feed", function()
assuming #the_news_feed is the parent of #load_more_feed.
EDIT :
From your code, you're appending this #loadmore button after #the_news_feed, so this obviously will not work. Try changing it to this :
$(document).on("click", "#load_more_feed", function()
This will bind the click to the document, which will always exist. Alternatively, you could bind it to #load_more_feed closest static parent, like an element which exists when you load your page and not dynamically created.

$.ajax interfering with .hide() and .show() Jquery in this script

(In Firefox and IE9 it doesn't work. In Chrome, this works)
If I remove the ajax, the hide / show JQuery works. Any solutions?
<form id="ppform" action="blah.asp" method="post">
<div id="saleload">Blah</div>
<button id="sendbutton">Send</button>
</form>
$(document).ready(function(){
$('#saleload').hide();
$('#sendbutton').click(function() {
$('#saleload').show();
$.ajax({
type: "POST",
url: /blah/blah.asp,
data: reqBody,
dataType: "json",
success:function(data,textStatus){
if (data.redirect) {
window.location.href = data.redirect;
}else{
$("#ppform").replaceWith(data.form);
}
}
});
});
});
This line:
$("#ppform").replaceWith(data.form);
is replacing the whole form contents with the response from your Ajax request. This means the click handler you setup will be gone too, because #sendbutton will be gone. Even if you have another button with the same ID inside data.form, it won't work. You have to use event delegation instead:
$(document).ready(function(){
$('#saleload').hide();
$(document).on('click', '#sendbutton', function(){
$('#saleload').show();
$.ajax({
type: "POST",
url: "/blah/blah.asp",
data: reqBody,
dataType: "json",
success:function(data,textStatus){
if (data.redirect) {
window.location.href = data.redirect;
} else {
$("#ppform").replaceWith(data.form);
}
}
});
});
});
Also: you seem to be posting an undefined variable reqBody to your server, and, as lonesomeday said above, you were missing quotes around the URL.
The obvious reason is that there is an error with your Javascript that causes the whole section not to execute. Quickly looking through your code shows this line:
url: /blah/blah.asp,
Strings need to be enclosed in quotation marks:
url: "/blah/blah.asp",

Setting data-content and displaying popover

I'm trying to get data from a resource with jquery's ajax and then I try to use this data to populate a bootstrap popover, like this:
$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);
and the function for retrieving data is:
get_data_for_popover_and_display = function() {
var _data = $(this).attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}
What is happening is that the popover is NOT showing when I click, but if I hover the element later it will display the popover, but without the content (the data-content attribute). If I put an alert() inside the success callback it will display returned data.
Any idea why is happening this? Thanks!
In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display().
Don't worry! The this keyword is hairy; misinterpreting its value is a common mistake in JavaScript.
You can solve this by keeping a reference to this by assigning it to a variable:
get_data_for_popover_and_display = function() {
var el = $(this);
var _data = el.attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
el.attr('data-content', data);
el.popover('show');
}
});
}
Alternatively you could write var that = this; and use $(that) everywhere. More solutions and background here.
In addition to the answer above, don't forget that according to $.ajax() documentation you can use the context parameter to achieve the same result without the extra variable declaration as such:
get_data_for_popover_and_display = function() {
$.ajax({
type: 'GET',
url: '/myresource',
data: $(this).attr('alt'),
dataType: 'html',
context: this,
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}

Categories

Resources