How can I change this code so that I can add it to the standard document ready for jquery so that all my scripts are together.
/*
* Fetch RSS feed once page has finished loading.
*/
(function(url, callback) {
jQuery.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
})('http://www.bet365.com/news/en/betting/sports/rss', function(feed){
var entries = feed.entries, content, publishDate;
for (var i = 0; i < entries.length; i++) {
publishDate = new Date(entries[i].publishedDate);
date = publishDate.getDate() + '/' + publishDate.getMonth() + '/' + publishDate.getFullYear();
content = truncateText((entries[i].contentSnippet) ? entries[i].contentSnippet : entries[i].content, 100);
jQuery('#rss > ul').append('<li><span> ' + date + '</span>' + entries[i].title + '</li>');
}
});
separate the functions.. it will good to use and understand
var my_callback = function(feed){ // Change to desired URL
var entries = feed.entries, content, publishDate;
for (var i = 0; i < entries.length; i++) {
publishDate = new Date(entries[i].publishedDate);
date = publishDate.getDate() + '/' + publishDate.getMonth() + '/' + publishDate.getFullYear();
content = truncateText((entries[i].contentSnippet) ? entries[i].contentSnippet : entries[i].content, 100);
jQuery('#rss > ul').append('<li><span> ' + date + '</span>' + entries[i].title + '</li>');
}
function make_ajax_call(url, callback) {
jQuery.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
}
then
$(document).ready(function(){
make_ajax_call('http://www.bet365.com/news/en/betting/sports/rss',my_callback);
});
Just wrap it with:
$(function(){
// Your code here
});
Actually $ is an alias for $.ready (and it's the same as $(document).ready) if function is passed as argument
Related
I have input which on change should send it is value to ajax and get response back. Ajax is working correct and enters to success,but does not working click function inside it if i do not do changes or click. If i click immediately after response it works, but if i do not do changes in 4-5 seconds it something like close the session. How can i avoid this timing?
here is my example of ajax
$('#unvan_search').on('keyup change', function() {
var unvan = $(this).val();
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
},
error: function(x, t, m) {
alert("error");
}
});
});
This binding here:
$("#unvan_select_div ul").on("click", '.get_street', function() { ... }
There’s no need to declare it in the success callback. This kind of delegate bindings is there for that purpose: being able to handle events on elements created at a later stage
It may work if you structure it like this.
var ret = false;
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
ret = true;
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
return;
},
error: function(x, t, m) {
alert("error");
}
});
});
if(ret) {
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
}
I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.
I am working on a MVC4 C#.Net project and when I am trying to
click the button ('#btn_rightArw_Dwn') then the ajax call fires multiple times in MVC4. Why this is happening? Please look up on below jQuery code.
Below I have added jQuery code.
$("#btn_rightArw_Dwn").click(function() {
$('.fade_bg').show();
var Masterid = $('#MastersId').val();
var pgm_id = $('#program1').val();
if ($('#rdclick').val() == "0") {
$.ajax({
url: "/DataInput/Arrow_Load_Down?Id=" + Masterid + "&flag=" + "Right" + "&type=" + 0 + "&pgm_id=" + pgm_id,
async: true,
data: {},
success: function(data) {
$('#DVmaster').html(data);
$('#btn_rightArw1').attr('hidden', false);
$('#btn_LeftArw1').attr('hidden', false);
var production_id = $('#program1').val();
$.ajax({
url: "/DataInput/Arrow_Load_Details_Down?Id=" + Masterid + "&flag=" + "Right" + "&ProductnSts_id=" + pgm_id + "&type=" + 0,
async: false,
data: {},
success: function(data) {
$('#DVDetails').html(data);
$('#DVDetails').show();
$('#btn_rightArw_Dwn').attr('hidden', false);
$('#btn_LeftArw_dwn').attr('hidden', false);
},
error: function(html) {
$('.fade_bg').hide();
}
});
var channelid = $("#channel1").val();
var starttime = $("#StartTime").val();
var Endtime = $("#EndTime").val();
var date = $("#Date").val();
var Vimpact = $("#Viewers").val();
var gradeid = $("#grade1").val();
var seclength = $("#Seconds option:selected").text();
var Daypartid = $('#daypartid').val();
var itemid = $('#item1 option:selected').val();
var brandid = $("#brand1 option:selected").val();
$.ajax({
url: "/DataInput/Print_Labels_in_Edit?starttime=" + starttime + "&finishtime=" + Endtime + "&date=" + date + "&channelid=" + channelid + "&impact1=" + Vimpact + "&Seclength=" + seclength + "&gradesid=" + gradeid + "&itemid=" + itemid + "&brandid=" + brandid,
cache: false,
success: function(html) {
var labels = html.split(',');
var daypartname = labels[0];
var CPH = labels[1];
var TVR = labels[2];
var Mediavalue = labels[3];
var daypartid = labels[4];
$('.fade_bg').hide();
$('#lblDaypart').text(" " + daypartname);
$("#lblCPH").text('£' + " " + CPH);
$('#lblTvr').text(" " + TVR);
$('#lblMediaValue').text(" " + "£ " + Mediavalue);
$('#daypartid').val(daypartid);
},
error: function(html) {
$('.fade_bg').hide();
}
});
}
});
}
});
Thanks in advance.
With this code i get the first 2 results of my JSON array. How can I "load more" by scrolling?
function suchen() {
var suche = document.getElementById("mysearch").value;
$.ajax({
url: 'http://XXX.de/?apikey=XXX&search=' + suche + '&callback=?',
type: "GET",
dataType: 'json',
success: function daten (response) {
$( 'ul#suche li' ).remove();
var i = 0;
response.forEach(function(data) {
if(i >= 2)
return false;
$('ul#suche').append('<li class="item-content"><div class="item-inner"><div class="item-title">' + data.title + '</div></div></li>');
i++;
})
}
});
}
How can load the next (3 - 4 for example) items by scrolling?
Before that, I'd mention that if you use id in selector you don't need to specify node type.
I mean use $('#suche') instead of $('ul#suche')
When it comes to infinite scroll, you should definitely specify items amount in your ajax call to get a exact chunk you need. Maybe to specify from and amount if your API gives a possibility.
Like this:
var from = 0
var amount = 2
var callApi = function (from, amount) {
$.ajax({
url: 'http://XXX.de/?apikey=XXX&search=' + suche + '&from' + from + '&amount=' + amount + '&callback=?',
success: function (response) {
response.forEach(function(data) {
$('#suche').append(
'<li class="item-content">' +
'<div class="item-inner">' +
'<div class="item-title">' + data.title + '</div>' +
'</div>' +
'</li>'
);
});
// increase from on each call
from += amount;
}
});
};
// call it
callApi(from, amount);
Then you need to add scroll eventListener and when last element appears on window canvas, call it again.
var lastChild, lastChildPosition, bottomPosition, bottomPosition
$(document).on('scroll', function (e) {
lastChild = $('#suche li:last-child');
lastChildPosition = lastChild.scrollTop();
scrollTop = $(this).scrollTop();
bottomPosition = scrollTop + $(window).height();
// call it again
if (bottomPosition > lastChildPosition) {
callApi(from, amount);
}
})
Thank you very much. I try to build a version with Wordpress which is based on your idea:
function suchen_api(lastindex) {
var suche = document.getElementById("mysearch").value;
var offset = lastindex;
var showposts = 2;
$.ajax({
url: 'http://XXX.de/?apikey=XXX&search=' + suche + '&offset=' + offset + ' &showposts=' + showposts + '&callback=?',
type: "GET",
dataType: 'json',
success: function(response){
response.forEach(function(data) {
$('ul#suche').append('<li class="item-content"><div class="item-inner"><div class="item-title">' + data.title + '</div></div></li>');
myApp.hideIndicator(); // Preloader geht aus
$$('.infinite-scroll-preloader').remove();
})
}
});
}
function suchen() {
$( '#suche li' ).remove();
var startindex = 0;
suchen_api(startindex);
}
// on Scroll
$$('.infinite-scroll').on('infinite', function () {
var startindex = $("ul#suche li").length;
suchen_api(startindex);
})
There is only one problem. Sometimes it shows me the last one doubled. Do you have an idea?
From the below function I am getting results. Now I want to put that result into a div. So how should I put the result into a div?
$(document).ready(function () {
$.ajax({
type: "POST",
url: "../ajaxaction.php",
data: {
action: 'alllist'
},
dataType: 'json',
success: function (msg) {
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
}
}
});
});
You can append the result in to div with the format you like but a simple way of adding would be. You can use append() function to keep the added html with new html for each iteration of loop.
success: function(msg){
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
$('#divId').append("Name: " + uname + "," + "Title: " + vtitle +
"Id: " + vid + "," + "Thumb: " + vthumb + "<br />");
}
$(document).ready(function() {
$.ajax({
type: "POST",
url: "../ajaxaction.php",
data: { action:'alllist'},
dataType: 'json',
success: function(msg){
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
$("#container").html("Username: " + uname + "<br />Video Title: " + vtitle + "<br />Vide ID: " + vid + "<br />Video Thumb: " + vthumb);
}
}});
});
If your div exists:
jQuery('div selector').append(uname+' '+vtitle+...whatever variable and format);
If not
jQuery('element selector to put the div in').append('<div id="aID" class="some classes">'+uname+' '+vtitle+...whatever variable and format...+'</div>');
you can do this:
success: function(msg){
$.each(msg, function(i, item){
$('#divid').html('User Name : '+item.user_name+
'Video title : '+item.video_title+
'Video Id : 'item.video_id+
'Video Thumb : 'item.video_thumb );
});
}