Conditionally handle ajax request - javascript

I have a full screen loading animation whenever Ajax start (most of them are action by the user) and hide on completion. At the same time I also have Ajax call to check server status using setInterval.
How do I separate the Ajax call to check server status because it is annoying if it appear as full screen. A small loading icon beside the status is fine.
May refer to the snippet below:
$(document).ajaxStart(function() {
$.LoadingOverlay("show");
});
$(document).ajaxComplete(function() {
$.LoadingOverlay("hide");
});
$(document).ready(function() {
setInterval(ajaxCall, 3000);
function ajaxCall() {
$.ajax({
url: "action.php",
type: "POST",
data: {
'action': 'checkstatus'
},
dataType: "json",
success: function(data) {
console.log('online');
$('.serverStatus').removeClass('ssOffline');
$('.serverStatus').addClass('ssOnline').text('Online');
},
error: function(xhr, ajaxOptions, thrownError) {
console.log('offline');
$('.serverStatus').removeClass('ssOnline');
$('.serverStatus').addClass('ssOffline').text('Offline');
}
});
}
});
.ssOffline {
color: red;
}
.ssOnline {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gasparesganga-jquery-loading-overlay#1.5.4/src/loadingoverlay.min.js"></script>
<p>Server status: <label class="serverStatus">-</label></p>

You can use the global which is default true.This option can be use control global handlers like ajaxStart and ajaxStop.This will prevent the full screen loading icon from appearance.
If you want to show any other icon specific to this call you can use beforeSend handler
$(document).ajaxStart(function(event) {
console.log(event)
$.LoadingOverlay("show");
});
$(document).ajaxComplete(function() {
$.LoadingOverlay("hide");
});
$(document).ready(function() {
setInterval(ajaxCall, 3000);
function ajaxCall() {
$.ajax({
url: "action.php",
type: "POST",
data: {
'action': 'checkstatus'
},
dataType: "json",
global: false, // changed here
success: function(data) {
console.log('online');
$('.serverStatus').removeClass('ssOffline');
$('.serverStatus').addClass('ssOnline').text('Online');
},
error: function(xhr, ajaxOptions, thrownError) {
console.log('offline');
$('.serverStatus').removeClass('ssOnline');
$('.serverStatus').addClass('ssOffline').text('Offline');
}
});
}
});
.ssOffline {
color: red;
}
.ssOnline {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gasparesganga-jquery-loading-overlay#1.5.4/src/loadingoverlay.min.js"></script>
<p>Server status: <label class="serverStatus">-</label></p>

You can set a property at jQuery.ajax() settings object, substitute using beforeSend at $.ajaxSetup() for .ajaxStart(), check if the current settings have the property set
function log(message) {
$("pre").text(function(_, text) {
return text + message + "\n"
})
}
// does not provide `settings` or `jqxhr` as argument
// we do not perform logic evaluation of current `$.ajax()` call here
$(document).ajaxStart(function() {
log("ajax start");
});
$(document)
.ajaxComplete(function(e, jqxhr, settings) {
if (!settings.pollRequest) {
log("not poll request complete\n");
// $.LoadingOverlay("hide");
} else {
log("poll request complete\n");
}
});
$.ajaxSetup({
beforeSend: function(jqxhr, settings) {
if (settings.pollRequest) {
log("poll request beforeSend");
// $.LoadingOverlay("show");
} else {
log("not poll request beforeSend");
}
}
});
$(document).ready(function() {
setInterval(ajaxCall, 3000);
function ajaxCall() {
"ajaxCall";
$.ajax({
url: "data:text/plain,",
pollRequest: true
});
}
$("button").on("click", function() {
$.ajax("data:text/plain,")
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button>
click
</button>
<pre></pre>
jsfiddle https://jsfiddle.net/5hfty5mc/

Related

Depending on type of AJAX request show LoadingGif

I have 1 POST ajax and 1 GET ajax, and I have this:
$(document).ready(function () {
$(document).ajaxStart(function () {
$("#div28").show();
});
$(document).ajaxStop(function () {
$("#div28").hide();
});
});
It is for showing the LoadingGif, at this point it is showing for both Ajax requests, so what should I do to make the LoadingGif show only when the POST type ajax is working?
EDIT:
Here are my ajax functions:
$(document).ready(function () {
$.ajax({
contentType: "application/json; charset=utf-8",
type: 'GET',
url: 'api/Appointments/',
dataType: 'json',
success: function (result) {
if ((result.AppTime = "9:00") && (result.AppWithYritys = "Laakkonen")) {
document.getElementById("A9").style.background = "red";
}
else {
alert("error1");
}
},
error: function (error) {
alert("error");
},
});
});
and the POST ajax:
var request = $.ajax({
type: "POST",
data: JSON.stringify(app),
url: "/api/Appointments",
contentType: "application/json",
dataType: "html"
});
request.done(function (data) {
if (data != -1) {
alert("You Have successfully made an appointment");
location.assign("http://tid.fi");
}
else {
alert("There has been an error!");
}
});
request.fail(function (gr) {
location.assign("http://google.com");
});
};
POST ajax is in a custom function which is trigger on a button-click. Just an info.
using ajaxSend and ajaxComplete you can see what the "type" of request is
However, you'll need to keep a count of active requests too - possibly not required for your simple page - but it's good to have
$(document).ready(function () {
var started = 0;
$(document).ajaxSend(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
if(!(started++)) { // only need to show on the first simultaneous POST
$("#div28").show();
}
}
});
$(document).ajaxComplete(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
if(!(--started)) { // only hide once all simultaneous POST have completed
$("#div28").hide();
}
}
});
});
Solution without counters
$(document).ready(function () {
$(document).ajaxSend(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
$("#div28").show();
}
});
$(document).ajaxStop(function () {
$("#div28").hide();
});
});
This will show on POST, and hide once all ajax has stopped - a little less obvious, but it's probably just as valid a solution
I think the easiest option is to create a tiny functions that you can use:
function showLoading(isLoading){
if(isLoading){
$("#div28").show();
}
else{
$("#div28").hide();
}
};
Then use as documented here Ajax events
just use the function either using the global events for your specific post or call the function directly on the beforeSend and complete event hooks.

Change button on clicked and records update in database and vice versa

I have one button called as delete. If any user clicked on delete then delete text will replace by restore and delete action will perform in the database.
Same think I have to set on the restore button. If clicked on restore then replace text by delete and restore action will perform but I need only one button.
Please check my below code. There is delete button and when I clicked on delete button it is displaying restore button and redirecting to perform the delete event.
I know how to delete and restore the records in php. I need script to perform.
Change button I did with the help of Jquery. Without refreshing, I have to display restore button.
$(document).ready(function () {
$("a.btn").click(function () {
if ($(this).hasClass('btn')) {
$(this).html('Restore').toggleClass('btn');
} else {
$(this).html('Delete').toggleClass('btn');
}
});
});
function b_delete(id){
$.ajax({
type: "get",
url: "process.php?function=b_delete&record_id=id",
data: {
record_id:record_id
},
success: function (data){
alert(data);
},
error: function (xhr, ajaxOptions, thrownError){
}
});
return false;
}
a{
text-decoration: none;
}
.btn-center
{
text-align: center;
}
.btn{
background-color: blue;
color: #fff;
padding: 10px 15px;
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="btn-center">
Delete
</div>
Process.php
switch($_GET['function']) {
case 'b_delete':b_delete($conn);break;
default : redirect('index.php');
}
function b_delete($conn)
{
$record_id=$_GET['record_id'];
echo "testing";
}
You are using get method for ajax call,
you can either pass parameters through url or using data.
There is a small error while passing value of parameter "record_id" in data.
It must be data:{record_id:id}
<!-- language: lang-css -->
<style>
a {
text-decoration: none;
}
.btn-center {
text-align: center;
}
.btn {
background-color: blue;
color: #fff;
padding: 10px 15px;
}
</style>
<!-- language: lang-html -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="btn-center">
<a href="javascript:void(0);"
onclick="return b_delete('<?php echo $user_id;?>')" class="btn">Delete</a>
</div>
<!-- end snippet -->
<script type="text/javascript">
$(document).ready(function () {
$("a.btn").click(function () {
if ($(this).hasClass('btn')) {
$(this).html('Restore').toggleClass('btn');
} else {
$(this).html('Delete').toggleClass('btn');
}
});
});
function b_delete(id){
$.ajax({
type: "get",
url: "process.php?function=b_delete&record_id=id",
data: {
record_id:id
},
success: function (data){
alert(data);
},
error: function (xhr, ajaxOptions, thrownError){
}
});
return false;
}
</script>
You can try assigning a data attribute to a.
<a data-action="delete">Delete</a>
Then in your script:
$('a').on('click', function(){
if ($(this).data('action') == 'delete')
{
//Do your ajax for delete
$.ajax({
type: "get",
url: "process.php?function=b_delete",
data: {
'record_id':record_id
},
success: function (data){
alert(data);
},
error: function (xhr, ajaxOptions, thrownError){
}
});
$(this).text('Restore');
$(this).data('action', 'restore');
} else {
//Do your ajax for restore
$(this).text('Delete');
$(this).data('action', 'delete');
}
});
Your attempt at ajax is not so bad, but i could see some minor things that i changed in the following code:
Html
<div class="btn-center">
<button id="delete_restore" onclick="b_delete(this, '<?php echo $user_Id;?>')" class="btn">Delete</a>
</div>
Javascript
function b_delete(element, user_id){
// change text of button
if (element.hasClass('btn')) {
element.html('Restore').toggleClass('btn');
} else {
element.html('Delete').toggleClass('btn');
}
/* where is this coming from? */
var record_id = 9999;
var mode = 'b_delete';
if(!element.hasClass('btn')){
mode = 'b_restore';
}
$.ajax({
type: "post",
url: "process.php",
data: {
user_id: user_id,
mode: mode,
record_id: record_id
},
success: function (data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError){
console.log("ajax request failed", xhr, ajaxOptions, thrownError);
}
});
}
process.php
if(isset($_POST['mode'])){
switch($_POST['mode']) {
case 'b_delete': b_delete($conn);break;
case 'b_restore': b_restore($conn);break;
default : header('Location: index.php'); //maybe use full url, i dont know for sure
}
}
function b_delete($conn)
{
$record_id=$_POST['record_id'];
echo "testing delete";
}
function b_restore($conn)
{
$record_id=$_POST['record_id'];
echo "testing restore";
}

jQuery BlockUI not blocking <select>

I'm trying to have a dropdown menu be blocked while the ajax function populates the list, and then unblocking itself once it's done. Any idea why it's not working?
<script src="/Common/jquery.blockUI.js"></script>
function handleMoreResults (responseObj) {
$("#dimensionId").html(responseObj.DimensionValueListItem.map(function(item) {
return $('<option>').text(item.dimensionValueDisplayName)[0];
}));
}
function getMoreData()
{
jQuery.ajax({
url: GetDimensionValues,
type: "GET",
dataType: "json",
beforeSend: function () {
$.blockUI();
},
success: function (data) {
object = data;
handleMoreResults (data);
},
complete: function () {
$.unblockUI();
}
});
}
try this
$('select').block({
message: '<h1>Processing</h1>',
css: { border: '3px solid #a00' }
});
and place the block and unblock call in the global ajax methods
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
for more info see the docs here http://malsup.com/jquery/block/#element

Redirect from external page after ajax submit

Hello i'm using an ajax script redirecting to a php page where i make the validation. After there are no validation errors i want to redirect to another page but i cant manage to make it work. here is my script:
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$("#imageform").ajaxForm({
target: \'#preview \',
});
});
</script>
and here is the external php were i make the validation
<?php
require_once('../core/dbconfig.php');
mysql_query("SET NAMES utf8");
$fname=$_POST['name'];
$email=$_POST['email'];
$country=$_POST['country'];
$city=$_POST['city'];
$type=$_POST['type'];
$story=$_POST['story'];
$cookie=$_COOKIE['cookie'];
$sizee = $_FILES['img1']['size'];
if (!$fname or !$city or !$email or !$country or (!$story && $sizee==0))
{
if ($sizee==0 && !$story)
{
echo'<p style="color:red;">Please upload a photo or type your story.<p>';
}
if(!$fname)
{
echo'<p style="color:red;">Please enter your name.<p>';
}
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
}
else
{
echo'<p style="color:red">Please enter a valid email.<p>';
}
if(!$country)
{
echo'<p style="color:red">Please select your country.<p>';
}
if(!$city)
{
echo'<p style="color:red">Please enter your city.<p>';
}
}
else
{
....
}
what i want to achiev is that after all the conditions are completed to redirect to a confirmation page. If i use a succes:window.location.href = "example.php" doesnt work as intended.
Thnx in advance.
$(myform).ajaxForm({
beforeSend: function() {
},
error: function() {
},
complete: function(response) {
window.location.href='yourfile.php'
}
});
With ajaxForm you'r can use function complete, according to documentation this function... "A function to be called when the request finishes (after success and error callbacks are executed)".
But you need consider property async, By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
$(myform).ajaxForm({
async: true,
error: function(response) {
//something is wrong
},
complete: function(response) {
window.location.href='yourfile.php'
}
});
OR
$(myform).ajaxForm({
async: false,
error: function(response) {
//something is wrong
},
complete: function(response) {
window.location.href='yourfile.php'
}
});
$.ajax({
type: "POST",
dataType: "json",
url: "friends/get_user_friends",
data:{
action:"action",
type:"type"
},
success: function (response) {
window.location.href = "http://google.com";
},
error: function (response, ajaxOptions, thrownError) {
}
});

Insert HTML using jQuery

I have two pieces of code, first of all I have my code which toggles open a div with an included close button:
http://jsfiddle.net/spadez/uhEgG/27/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle();
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
Then I also have my Ajax code which is designed to fire when the div has been opened:
$(function () {
$('#country_link').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
return false;
});
});
What I am stuck with now is, how do I make the ajax only execute when the div is being opened? Because I am working with a toggle and close button it seems difficult to work out what the click is doing, whether it is opening it or closing it.
I guess my options are to have some kind of flag or alternatively have some "if" code, so if class is equal to .hidden then do not execute. I haven't been able to integrate either of these solutions and I am unsure if either of them is the proper way to achieve this.
Include the check as part of your slide function:
$("#country_slide").slideToggle(function() {
if ($(this).is(":visible")) {
alert("im visible!");
}
});
Demo: http://jsfiddle.net/tymeJV/uhEgG/28/
if($("#country_slide").is(":visible"))
//call ajax
This code adds data to the element, to check if it's already loaded next time you click on it.
Currently I am not able to test it, so it may contain errors.
$(function () {
$('#country_link').on('click', function (e) {
// Prevent from following the link, if there is some sort of error in
// the code before 'return false' it would still follow the link.
e.preventDefault();
// Get $link because 'this' is something else in the ajax request.
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true)
return false;
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
});
});

Categories