This question is based on this question; but, there are some differences.
My friend has an online webpage, which it has an inline script tag, there is a JavaScript function:
(#1):
var domain = window.location.protocol + "//" + window.location.host + '/';
$(document).ready(function() {
var count = 5;
countdown = setInterval(function() {
if (count == 0) {
$('#countdow').hide();
$('#link-news').show()
} else {
$('#countdow').text(count);
count--
}
}, 1700);
$('#link-news').click(function() {
var urls = $('input[name=linknexttop]').val();
if (urls == 1) {
$('input[name=linknexttop]').val(2);
$.ajax({
type: "GET",
url: domain + "click.html",
data: "code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
success: function(html) {
//alert(html);
window.location = html;
}
})
}
})
});
After waiting in 5 seconds, it will show:
(#2):
<div id="countdow">Please wait ...</div>
<img src="en_tran.png" border="0" name="imgTag" />
</div>
Now, I want to send data to click.html (in #1), without click into image imgTag (in #2). Is there possible to do it with JavaScript?
Rule for playing: "I am allowed to insert my code bellow his original code only; so, I am not allowed to change anything in his code. And, the most important: code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b is random.".
You can trigger the $('#link-news').click function by calling $('#link-news').click() after the 5 seconds countdown.
Or you can directly call the ajax call in the click function.
if (count == 0) {
$('#countdow').hide();
$('#link-news').show();
$('#link-news').click(); /* This will trigger the click event without actually clicking on the image */
} else {
$('#countdow').text(count);
count--
}
you can trigger click function without clicking on it using trigger function of jquery.
$( "#link-news" ).trigger( "click" );
Related
the title may be a bit misleading but I'm not sure how to phrase it better, so I apologize for that.
I'm creating a custom handler so the site doesn't refresh when new content is pressed (similar to how youtube works, for example).
For that I'm using this script:
$('.sidebar2 li a').click(function (e) {
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
e.preventDefault();
test = false;
return false;
}
}
});
});
even though I've stated e.preventDefault() to trigger, javascript loads the new content into the current frame without refreshing, but the browser refreshes again anyway.
I've tried to use href="#" however in this case when I go back and handle that, I always end up with two same pages, one without and one with # at the end, and in addition to that it wouldn't be very user friendly to have all links href="#"
What am I doing wrong to make the browser redirect "normally" even though I've told him no no no?
I've also tried adding onclick="javascript:void(0)" on a elements and that didn't help
ajax is async. By the time success callback is called event will already be bubbled up the DOM tree and processed. You need to call preventDefault before sending a request.
$('.sidebar2 li a').click(function (e) {
e.preventDefault(); // here for example
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
test = false;
// returning here makes no sense also
// return false;
}
}
});
});
I want to change the content of an element using .html() to indicate that a process has started.
But the problem is that it won't work no matter what I do. I might be missing something here that prevents the script from working.
Code:
if(counter < 1 && flag == true){
alert("test");
$("#updownform").html("Please Wait...");
// if(confirm("Are you sure you want to proceed?")){
// counter++;
// $.ajax({
// method: "POST",
// url: "index.php?module=Accounts&action=processUpdowngrade",
// data: {form_data: $(this).serialize()},
// success: function (datas) {
// counter = 10000;
// location.reload();
// }
// });
// }else{
// $("#updownform").html("Save changes");
// }
}
In this example where everything is commented out except for the alert and .html(). The .html() works but if I uncomment everything it will only work when AJAX is finished with the request even after the confirm condition was triggered. Which I found weird since I already placed it before the confirm condition. So ideally it would have executed before the confirm condition.
I also tried using beforeSend but it still didn't work. I also tried setting it to asynch:false/true together with beforeSend to no avail.
I would recommend trying the code below to see if it helps.
<script>
if (counter < 1 && flag == true) {
alert("test");
document.getElementById("updownform").value = "Please Wait...";
if (confirm("Are you sure you want to proceed?")) {
counter++;
$.ajax({
type: "POST",
url: "index.php?module=Accounts&action=processUpdowngrade",
data: $("#enter_your_form_id").serialize(), // serializes the form's elements.
success: function(data) {
counter = 10000;
location.reload();
}
});
} else {
document.getElementById("updownform").value = "Save changes";
}
}
</script>
I added some infinite scrolling from this tutorial and i've been stuck on ajax request. it's always requesting multiple times.
and this is my code :
$(document).ready(function() {
var win = $(window);
var page = 1;
var req = null;
win.scroll(function() {
if ($(document).height() - win.height() == win.scrollTop()) {
if (req != null) {
req.abort();
}
req = $.ajax({
url: "/member/member_c/generate_data",
type: "POST",
data: {
"page": page
},
dataType: "text",
success: function(msg) {
var obj = jQuery.parseJSON(msg);
if (obj.result) {
$('#contentz').append(obj.data);
console.log(JSON.stringify('page ' + obj.page + ' : ' + jQuery.inArray(page,done)));
page = page + 1;
req = null;
}
},
});
}
});
});
i've been wondering, what is 'VM' at my console and why is what always firing a 'wrong' request?
Thanks
It appears that you're including two copies of your code somehow, since one call comes from your member_c.js file and the copies come from VM22* sources. You should show us your entire source code for the page with this problem, not just this single snippet.
I have the code below to find the next sequential page number and load it at the bottom of the page once the user hits the bottom of the screen.
the loading div slides down and as it is loading and up once it is done... it is set to "display:none" by default
What i need is a line of code in there which basically hides the #loading div if no more pages can be found to load... " var url = "page"+nextpage+".html";" finds the new page... titled 'page 2.html, page3.html' and so on.
Any help would be appreciated. I'm assuming it is easy but I can't find a solution anywhere...
alreadyloading = false;
nextpage = 2;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
if (alreadyloading == false) {
$("#loading").slideDown();
var url = "page"+nextpage+".html";
alreadyloading = true;
$.post(url, function(data) {
$('#newcontent').children().last().after(data);
alreadyloading = false;
nextpage++;
$("#loading").slideUp();
});
}
}
});
If there is no such file then the AJAX request will fail, so you can do what you need from inside a "failure" handler. To be able to specify that, you one solution is to move from using $.post to using the more configurable $.ajax, which gives you all the necessary options:
$.ajax({
type: 'POST',
url: url,
success: function(data) {
$('#newcontent').children().last().after(data);
nextpage++;
},
complete: function() {
alreadyloading = false;
$("#loading").slideUp();
}
});
The complete callback contains code which will be executed no matter what happens with the request; the success callback will be executed before complete, but only if the request was successful.
I have the following code build using jquery. When a user copies and pastes a a youtube url, i am suppose to extract the video id is the getVideoId(str) method in jquery. Using the id, i get the video image picture title and contents.
When the textbox->("#url") has a length more than 10, i will make a ajax request. Thus the ajax request is working. But now i have another problem. The very first time when the textbox has more than 10 characters, there is two ajax request being fired (tested using firebug). Than when the user enters more characters, there are many ajax request fired.
Thus this will slow down the process of the last ajax request. I just want to get the data of the youtube link and show a suggest where the user can add the title and content. It is like how the old facebook video video link is. Anyone has a better suggest in improving the codes?
jQuery(document).ready(
function(){
$("#url").keyup(function() {
var $t1 = $("#url").val();
var $length = $t1.length;
var $data;
$("#title").val($length);
$("#content").val($t1);
if($length==0){
alert('zero value');
return;
}
if($length>10){
$data = $.ajax({
url: '<?php echo $this->Html->url(array("action" => "retrieveVideoFeed"));?>',
dataType: "json",
data: {
vid: getVideoId($t1)
},
success: function(data) {
alert('success in getting data');
}
});
return;
}
});
function getVideoId(str) {
var urlRegex = /(http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (urlRegex.test(str) && str.indexOf('v=') != -1)
{
return str.split('v=')[1].substr(0, 11); // get 11-char youtube video id
} else if (str.length == 11) {
return str;
}
return null;
}
}
);
You could cache the calls and use blur event and not keyup: you are firing a lot of AJAX call because keyup() fires an event each time a key is pressed, you should use blur that fires an event when an input loses focus.
If you cache the calls in an object you can avoid a lot of repeated calls
var cacheUrl = {};
$("#url").blur(function() {
var $t1 = $("#url").val();
var $length = $t1.length;
var $data;
$("#title").val($length);
$("#content").val($t1);
if($length==0){
alert('zero value');
return;
}
if(cacheUrls[$t1] !== undefined && $length>10){
$data = $.ajax({
url: '<?php echo $this->Html->url(array("action" => "retrieveVideoFeed"));?>',
dataType: "json",
data: {
vid: getVideoId($t1)
},
success: function(data) {
//save the data to avoid a future call
cacheUrls[$t1] = data;
alert('success in getting data');
}
});
return;
}elseif ($length>10){
//you already have the data in cacheUrls[$t1]
}
});
EDIT if you want to use the submit key to start the search you could trigger the blur event when you press enter like this:
$("#url").keypress(function(e){
if(e.which == 13){
$(this).blur();
return false;
}
});
I think many ajax requests are fired because you are using $("#url").keyup(function()
so that for every key event in url input the particular funciton will exectue.So, as per i know better to use focusout method instead of keyup.
If you stay with the keyup-Event you maybe want to use an ajaxmanager-plugin for jQuery which can manage queues or limits the number of simultaneous requests.
$.manageAjax.create('myAjaxManager', {
queue: true,
cacheResponse: false,
maxRequests: 1,
queue: 'clear'
});
....
if($length>10){
$data = $.manageAjax.add({ ...
This will prevent having alot of ajaxrequests active at the same time when the user is typing. As soon as he stops the request will not aborted and the results will show up.