For some reason the $(window).scroll(function () { is stopping ajax from firing.
I've done a few tests. I completely removed my CSS fileto remove any overflows or heights set in the html,body, as this was a common thing that was stopping it on the net.
when I remove just the line $(window).scroll(function () {my ajax fires on page load but then if I want to scroll for new content i can't.
$(document).ready(function() {
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
flag = true;
first = $('#first').val();
limit = $('#limit').val();
no_data = true;
if (flag && no_data) {
flag = false;
$('#loadmoreajaxloader').show();
$.ajax({
url: "commentedoncontent.php",
dataType: "json",
method: "POST",
cache: false,
data: {
start: first,
limit: limit
},
success: function(data) {
flag = true;
$('#loadmoreajaxloader').hide();
if (data.count > 0) {
first = parseInt($('#first').val());
limit = parseInt($('#limit').val());
$('#first').val(first + limit);
$.each(data.posts, function(i, response) {
//post content here
});
} else {
alert('No more data to show');
no_data = false;
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
flag = true;
no_data = false;
}
});
}
}
});
});
Related
I am trying to submit a form with just automatic click button.
so I have a timer which is if the timer is already 0, it should submit the form automatically.
here is the code that I have.
function tick() {
var timeDisplay = document.getElementById('question_timer');
var isTimeLimit = true;
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
if (sec < 10) {
sec = '0' + sec;
}
var message = min.toString() + ':' + sec;
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0 && isTimeLimit == true) {
clearInterval(intervalHandle);
displayQuestion();
} else {
//boolean is false
if (secondsRemaining === 0) {
submitAnswer();
clearInterval(intervalHandle);
}
}
secondsRemaining--;
}
function startCountdown() {
clearInterval(intervalHandle);
secondsRemaining = 5;
intervalHandle = setInterval(tick, 1000);
}
function submitAnswer() {
$('#form_question_scenario').on('submit', function(e) {
$.ajax({
method: "post",
url: url,
data: new FormData(this),
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
});
}
How can I run the submitAnswer function if the timer is already 0. any help would be really appreciated.
The submitAnswer() function just attaches the event handler, it doesn't actually submit the form.
To achieve what you require attach the submit event handler when the page loads, then when you want to submit the form trigger that event on it. Try this:
// attach submit event handler when the page loads
$('#form_question_scenario').on('submit', function(e) {
$.ajax({
// ajax settings here...
});
});
function tick() {
var timeDisplay = document.getElementById('question_timer');
var isTimeLimit = true;
var min = Math.floor(secondsRemaining / 60);
var sec = ('00' + (secondsRemaining - (min * 60))).slice(-2); // note tidied the logic here
var message = min.toString() + ':' + sec;
timeDisplay.innerHTML = message;
// stop if down to zero
if (secondsRemaining === 0 && isTimeLimit == true) {
clearInterval(intervalHandle);
displayQuestion();
} else {
if (secondsRemaining === 0) {
$('#form_question_scenario').trigger('submit'); // submit the form here
clearInterval(intervalHandle);
}
}
secondsRemaining--;
}
function startCountdown() {
clearInterval(intervalHandle);
secondsRemaining = 5;
intervalHandle = setInterval(tick, 1000);
}
You don't need submit event at all, just call the function like you did when 0 sec is left, get id of form and create new form data, and do Ajax request...
function submitAnswer() {
let myForm = document.getElementById('form_question_scenario');
$.ajax({
method: "post",
url: url,
data: new FormData(myForm),
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
}
EXAMPLE:
Form data is populated without submit event just by calling the function:
function submitAnswer() {
let myForm = document.getElementById('form_question_scenario');
let data = new FormData(myForm)
formObj = {};
for (var pair of data.entries()) {
formObj[pair[0]] = pair[1]
}
console.log(formObj)
}
submitAnswer()
<form id="form_question_scenario">
<input type="text" value="test" name="test">
</form>
I have the following code that fires when a user scrolls to the bottom of the screen. The only issue is that I would like for the Ajax call to fire only once. My code is:
var w = $(window);
window.onscroll = function(ev) {
if ($(document).height() - w.height() == w.scrollTop()) {
$('#loading-image').show();
$.ajax({
url: "page-2.html",
cache: false,
success: function(result){
$("#part2").html(result);
console.log();
},
complete: function(){
$('#loading-image').hide();
}
});
}
};
The simplest way you can add a global variable and check it this way:
var w = $(window);
var BOTTOM_REACHED = false;
window.onscroll = function(ev) {
if ($(document).height() - w.height() == w.scrollTop() && !BOTTOM_REACHED) {
BOTTOM_REACHED = true;
$('#loading-image').show();
$.ajax({
url: "page-2.html",
cache: false,
success: function(result){
$("#part2").html(result);
console.log();
},
complete: function(){
$('#loading-image').hide();
BOTTOM_REACHED = false;
}
});
}
};
You can try like this :
var bottom_reached = false;
$(window).scroll(function(){
if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
bottom_reached = true;
$('#loading-image').show();
if(bottom_reached)
{
bottom_reached = false;
$.ajax({
url: "page-2.html",
cache: false,
success: function(result){
$("#part2").html(result);
console.log();
},
complete: function(){
$('#loading-image').hide();
}
});
}
}
});
This is a script :
<script type="text/javascript">
var pageSize = 10;
var pageIndex = 0;
$(document).ready(function () {
GetData();
$(window).scroll(function () {
if ($(window).scrollTop() ==
$(document).height() - $(window).height()) {
GetData();
}
});
});
function GetData() {
$.ajax({
type: 'GET',
url: '/home/GetData',
data:{"pageindex":pageIndex,"pagesize":pageSize},
dataType: 'json',
success: function (data) {
if (data != null) {
for (var i = 0; i < data.length; i++) {
$("#container").append("<h2>" +
data[i].CompanyName + "</h2>");
}
pageIndex++;
}
},
beforeSend : function () {
$("#progress").show();
},
complete : function () {
$("#progress").hide();
},
error: function () {
alert("Error while retrieving data!");
}
});
}
I have tried removing the type="text/javascript". What might be the possible issue, and how to fix scripting issues on diff browsers.
How can I use this script in case of tight coupling like, DisplayFor(x => x.name) in mvc .net?
I want to do is do now is instead of infinite ajax polling i want to do is make it run for 5 times then terminate the ajax infinite polling.
My problem is it doesn't work as i wanted. Can anyone help me with this?
ajax script:
$(document).ready(function () {
var = x;
var countTimer = setInterval(function () {
if(x++ === 5){
clearInterval(countTimer);
}else{
codeValue()
}
}, 500)
function codeValue() {
$.ajax({
type: "POST",
url: 'codeTime.php',
dataType: "JSON",
cache: false,
success: function (result) {
$("#count").val(result.user_code);
}
});
return false;
}
});
Change to var x = 0
I'd personally do it like this:
var x = 0;
var countTimer = setInterval(function () {
if(x === 5){
clearInterval(countTimer);
}else{
codeValue();
x++;
}
}, 500);
First of all you do not define x, u have var = x; which should be a syntax error. Try this:
$(document).ready(function () {
var countTimes = 0;
var numberOfTimes = 5;
var countTimer = 0;
countTimer = setInterval(function () {
countTimes++;
if(countTimes > numberOfTimes){
clearInterval(countTimer);
}else{
codeValue();
}
}, 500);
function codeValue() {
$.ajax({
type: "POST",
url: 'codeTime.php',
dataType: "JSON",
cache: false,
success: function (result) {
$("#count").val(result.user_code);
}
});
return false;
}
});
i have a jquery .click() function that executes an .ajax() method call
$(".btn-play").live("click", function () {
//set globalSortNumber
globalSortNumber = $(this).parents("[sortnumber]").attr("sortnumber");//.attr("value") ; //change should be some type of input like mediaid //see if its possible to add the sortID to the handle span
// alert(globalSortNumber);
//set title
//set mediaID
var mediaID = $(this).parents("[mediaid]").attr("mediaid");
// alert(mediaID);
//ajax query to get link and excute code to launch music
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
})
when the .ajax() method executes succesfully it calls a javascript function
function playsong(sortNumber,url) {
if (soundManager.supported()) {
globalSortNumber = sortNumber;
var aSoundObject = soundManager.createSound({
id: 'mySound' + sortNumber,
url: url,//'/Music/mafiamusicpt2rickross.mp3',
whileplaying: function () {
if (count == 0) {
if (this.position > 1000) {
this.pause();
pos = this.position;
count++;
this.resume();
}
} else if (count == 1) {
soundManager._writeDebug('old position: ' + pos);
soundManager._writeDebug('new position: ' + this.position);
// See that this.position is less than pos!
count++;
}
},
onfinish: function () {
//find the next song in the list
//var nextSongPosition=
this.destruct();
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
})
playsong(sortNumber++,url)
}
});
aSoundObject.play();
}
}
as you can see i have an .ajax() method inside my javascript function, is this possible?
I am creating loop that starts on the finish listener of the soundmanager object. So when I need to make the ajax call to get he next url I need. If my way isnt correct can you please tell me what is the best way to accomplish what i am trying to do.
Think it's fine but i would make a separate function for the ajax call so you dont need to duplicate the code twice. Easier to maintain.
$(".btn-play").live("click", function () {
//set globalSortNumber
globalSortNumber = $(this).parents("[sortnumber]").attr("sortnumber");//.attr("value"); //change should be some type of input like mediaid //see if its possible to add the sortID to the handle span
//alert(globalSortNumber);
//set title
//set mediaID
var mediaID = $(this).parents("[mediaid]").attr("mediaid");
//alert(mediaID);
//ajax query to get link and excute code to launch music
getAudio(mediaID);
}
function playsong(sortNumber,url) {
if (soundManager.supported()) {
globalSortNumber = sortNumber;
var aSoundObject = soundManager.createSound({
id: 'mySound' + sortNumber,
url: url,//'/Music/mafiamusicpt2rickross.mp3',
whileplaying: function () {
if (count == 0) {
if (this.position > 1000) {
this.pause();
pos = this.position;
count++;
this.resume();
}
} else if (count == 1) {
soundManager._writeDebug('old position: ' + pos);
soundManager._writeDebug('new position: ' + this.position);
// See that this.position is less than pos!
count++;
}
},
onfinish: function () {
//find the next song in the list
//var nextSongPosition=
this.destruct();
getAudio(mediaId);
playsong(sortNumber++,url)
}
});
aSoundObject.play();
}
}
function getAudio(mediaID) {
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
});
}