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>
Related
I have the following function
<script src='jquery-3.1.1.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
function loaddata() {
var div = $('#div');
$.get('load_data.php', function(data) {
div.html(data);
$('body, html').scrollTop(div[0].scrollHeight);
});
}
loaddata();
setInterval(loaddata, 1000);
});
window.addEventListener('scroll', function(){
if(($(window).scrollTop() < 1) )
{
$.ajax({url: 'load_extra_data.php,
cache: false,
success: function(html){ $('#div').prepend(html);
$(document).scrollTop(position);
}})
}
})
</script>
the problem is related to the function
window.addEventListener('scroll', function(){
The function load_extra_data.php provides the data that has to be added to the div.
I need to wait until the data from load_extra_data.php is fetched before scrolling a second time.
How can the problem be solved ?
Keep a flag to tell you whether you have data loading, and don't ask for more data while the flag is set. Roughly:
var loading = false; // The flag, initially false
window.addEventListener('scroll', function(){
if (!loading && $(window).scrollTop() < 1) {
// ^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Checking the flag
loading = true; // Setting the flag
$.ajax({
url: 'load_extra_data.php',
cache: false,
success: function(html){
$('#div').prepend(html);
$(document).scrollTop(position);
},
complete: function() { // Clearing the flag when
loading = false; // the request ends (whether
} // it succeeds or fails)
});
}
});
(I've only used ES5 and earlier features in that, since your code didn't show signs having ES2015+ items in it. But in 2020, I'd certainly be writing to ES2015+ and transpiling if I really had to support obsolete environments that didn't support it.)
You could use the callback function .done() of $.ajax(). Which will be executed after the data has loaded.
$.ajax({url: 'load_extra_data.php',
cache: false,
success: function(html){ $('#div').prepend(html);
$(document).scrollTop(position);
}}).done(function() {
// Executed after $.ajax fetch is done
})
I have a script that makes $.ajax request for a json api. So what I want to do is to build unit test so I can test the result from the ajax request. For example if I get json object back. I know result should include "items" and "result" which is an array. The things is I dont know how to initialize the $.ajax function which is inside a
$("#button").click(function() { });
Here's the skeleton of my javascript index.js file. The file is not complete. as it is longer. I just included the relevant parts. But it works. Here's the app live online http://pctechtips.org/apps/books/
$(document).ready(function() {
var item, tile, author, publisher, bookLink, bookImg;
var outputList = document.getElementById("list-output");
var bookUrl = "https://www.googleapis.com/books/v1/volumes?q=";
var searchData;
$("#search").click(function() {
outputList.innerHTML = ""; //empty html output
searchData = $("#search-box").val();
//handling empty search input field
if(searchData === "" || searchData === null) {
displayError();
}
else {
// console.log(searchData);
// $.get("https://www.googleapis.com/books/v1/volumes?q="+searchData, getBookData()});
$.ajax({
url: bookUrl + searchData,
dataType: "json",
success: function(response) {
console.log(response)
if (response.totalItems === 0) {
alert("no result!.. try again")
}
else {
$("#title").animate({'margin-top': '5px'}, 1000); //search box animation
$(".book-list").css("visibility", "visible");
displayResults(response);
}
},
error: function () {
alert("Something went wrong.. <br>"+"Try again!");
}
});
}
$("#search-box").val(""); //clearn search box
});
});
In your test you need first to prepare a HTML fixture which will contain all the required elements like #search. After preparing it, you can load your script via $.getScript() - it will attach click event listener to #search. Finally, you have to spy on $.ajax and trigger the click manually via $('#search').trigger('click')
I'm using ajax for my form because I don't want the page to reload after submit.
Now is everything working but the only problem is that the ajax script runs everytime I click the submit button.
I thought I could just paste the ajax in my if statement that tells when to run and when not, but it doesn't work.. anyone have any idea why?
theForm.onsubmit = function() {
if (pion == 1 || myName.value.length == 0 || myMessage.value.length == 0) {
if (pion == 1 || emailValid.value.length == 0) {
emailValid.style.border = "1px solid red";
myError.innerHTML = "U heeft geen geldig e-mail adres ingevoerd.";
}
if (myName.value.length == 0) {
myName.style.border = "1px solid red";
myError.innerHTML = "U heeft geen naam ingevuld.";
}
if (myMessage.value.length == 0) {
myMessage.style.border = "1px solid red";
myError.innerHTML = "U heeft geen bericht ingevuld.";
}
return false;
}
else {
// the ajax I found somewhere, that works but not in this if/else statement
$(function () {
$('form').bind('submit', function () {
$.ajax({
type: 'post',
url: 'mail.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
return true;
}
}
This code block:
$('form').bind('submit', function () {
$.ajax({
type: 'post',
url: 'mail.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
bound the function that sends the AJAX request to your form element's submit event. Once it did, the function remains bound forever (or at least until you explicitly unbind it). That's why once your code falls in the else statement for the first time, the AJAX request will be sent every time the form is submit.
That said, your if/else logic should be inside the function that is bound to your form's submit event in order to send the AJAX request conditionally. Something like:
$('form').bind('submit', function () {
if (etc etc etc) {
// do other things
}
else {
// send AJAX
$.ajax({
type: 'post',
url: 'mail.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
}
});
return false;
});
// the ajax I found somewhere
Copying/pasting code into your project without any knowledge of what that code does is a famously bad idea.
This code doesn't make an AJAX call:
$(function () {
// anything in here
});
What this code does is tell jQuery to execute that function when the document is ready. But presumably the document is already ready when you invoke this, since it's happening on a form submit event.
At best, depending on how the internals of jQuery works, it might be executing that inner function immediately. But still, you don't need that wrapping call to jQuery.
But then, what is that function doing?:
$('form').bind('submit', function () {
// anything in here
});
Again, it's not actually executing any AJAX code. All this is doing is binding a function to the form's submit event. That function may contain AJAX code (and in this case it does), but that's not being executed here. It will be executed when the form is next submitted.
But, you're doing this every time you submit the form. So what's happening is:
User presses submit, nothing visibly happens. 1 event handler is bound to the next submit event.
User presses submit, 1 event handler (AJAX) is executed, 2 event handlers are now bound to the next submit event.
User presses submit, 2 event handlers (AJAX) are executed, 4 event handlers are now bound to the next submit event.
and so on...
If you want to call the AJAX code in the else block, then just call it in the else block:
if (/* ... */) {
// ...
} else {
$.ajax({
type: 'post',
url: 'mail.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
}
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" );
function checkuser(user) {
var ret = false;
$.ajax({ type:'POST', url:'user.php',
async:false,
data:{'user':user},
success:function (data) {
if (data == 1) ret = true
} });
return ret;
}
I use bvalidator to validate fields. It seems to fire this function on every keypress and the user is not able to continue typing before the ajax call is competed. I'm not really sure what to do here.
How could I make the function not be ran more than once every two seconds for example?
You need to get rid of async:false but you also need to modify your code to work asynchronously. The synchronicity is what is causing your UI to 'freeze'.
Maybe you could try setting a timeout that will run 2 seconds after a key is pressed on your input, but if another key is pressed it restarts that timer. So in essence it will only after two seconds of no keystrokes.
var validateTimeout;
$('#target').keydown(function() {
clearTimeout(validateTimeout);
validateTimeout = setTimeout(function(){checkuser(user);},2000);
});
You'll need to update the checkuser ajax call to have a smarter callback to work async:
function checkuser(user) {
$.ajax({ type:'POST', url:'user.php',
async:false,
data:{'user':user},
success:function (data) {
if(data == 1){
//something to indicate sucess
}else{
//something to indicate failure
}
} });
}
You could throttle the call with a throttle plugin:
jQuery Throttle Plugin