Jquery Display Message then Ajax then hide message - javascript

il give an example
document.ready(function() {
$("#Show").bind("click", function()
{
var F = Function2();
if (F)
{
// Do Other Stuff.
}
}
});
function Function2()
{
$("#Message").Show();
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").Hide();
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
}
</script>
<div id="Message" style="display:none;">
<!-- Loading Image In here -->
</div>
<a href="#" id="Show" onclick="return:false;">Show then Hide</false>
</code>
Now what I want to happen is for this messagebox to show however the AJAX for some reason wont show it until the AJAX Request is finished by which point it is too late. I have set async to false which hasent helped either.

I think the root of this issue is a syntax error. JavaScript is case sensitive, so the correct syntax would be lowercase show() and hide()
If you're still having an issue after fixing the syntax errors, try using the ajaxStart event to show the message and hide it on success.
//use the ajaxstart event to display the message
$('#message').ajaxStart(function() {
$(this).show("slow");
});
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").hide("slow"); //hide message on success
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
Delaying the show or hide
$("#message").delay(3000).hide("slow");
Here's a jsFiddle: http://jsfiddle.net/rs83R/

Try hiding the Message div in the click event after getting true or false.
Remove the async:false, I do not think that is anyway relevant to fixing this problem. The purpose of AJAX call is to make an asynchronous call.
Also, there is an error its not $("#Message").Show() its $("#Message").show() with all lowercase, same goes for hide().
Try changing these, I hope it should work.

Related

ajax success function cant change button text

I have a simple but strange question, I am not able to change the value of the button in an ajax post success callback, I am sure the callback gets executed as the alert was shown. Also, those buttons are created statically, I did not create them dynamically using Jquery.
Below is my ajax:
$.ajax({
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "/?handler=Queue",
data: $.param(params),
dataType: "json",
success: function (response) {
$("#btn-queue-lib").val("Cancel Queue");
alert(response.responseText);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
However, if I change the problem line outside of ajax, it works fine:
$("#btn-queue-lib").val("Cancel Queue"); // Either Here
$.ajax({
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "/?handler=Queue",
data: $.param(params),
dataType: "json",
success: function (response) {
alert(response.responseText);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
$("#btn-queue-lib").val("Cancel Queue"); // Or Here
I have found out the problem, I dunno for some reason the server is returning the success message but actually returning a badrequest. Hence I mistaken that the success function should be called. If I put the problem line in the error callback, it works fine. Thanks guys for your efforts !!!
~ (^_^)∠※
document.getElementById('btn-queue-lib').innerText = 'Cancel Queue'
change
$("#btn-queue-lib").val("Cancel Queue");
to
$("#btn-queue-lib").text("Cancel Queue");
and place the statement in ajax success function right before alert.
In Success use
$("#btn-queue-lib").html("Cancel Queue");
Even I have faced the same issue... I managed it as below hope it will help for too
function changeAfterAjax(){
$.ajax({
type: "GET",
url:"https://reqres.in/api/users?page=2",
//data: $.param(params),
dataType: "json",
success: function (response) {
$("#btn-queue-lib").text("Cancel Queue");// this is also works fine
//changeBtnTxt('btn-queue-lib','Cancel Queue');
//alert(response);
},
error: function (xhr) {
console.log(xhr);
}
})
}
function changeBtnTxt(id,txt){
$("#"+id).text(txt);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="changeAfterAjax()" id="btn-queue-lib">Click to chanage after ajax</button>

trigger a javascript function before on any AJAX call

Here, I have a function which needs to be called before any AJAX call present in the .NET project.
Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.
In short, I want to make function behave like an event which will be triggered before any AJAX call
Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...
//check internet availability
function checkConnection() {
//stuff here to check internet then, set return value in the variable
return Retval;
}
//Ajax call
function SaveData() {
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And below is current way to call function:
<form onsubmit="return Save();">
<input type="text" id="txtYears" /><br />
<input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
<script>
function Save() {
if (confirm('Are you sure?')) {
SaveData();
}
else {
return false;
}
}
</script>
</form>
You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.
So, better to call it in actual AJAX and for that you can use beforeSend property of ajaxRequest like following, hence there will be no need to call checkConnection() seperately:
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
beforeSend: function() {
if(!checkConnection())
return false;
},
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
It reduces the call that you have made onsubmit() of form tag!
UPDATE:
to register a global function before every AJAX request use:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});
The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).
jQuery already supports custom publish-subsrcibe
For this specific example just do this:
//Ajax call
function SaveData(element) {
var doAjax = true;
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
if (element === myForm)
{
doAjax = checkConnection();
}
if ( doAjax )
{
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
else
{
// display a message
}
}
Hope i understand correctly what you mean.
UPDATE:
in the if you can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))
If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well
You can use:
$(document)
.ajaxStart(function () {
alert("ajax start");
})
.ajaxComplete(function () {
alert("ajax complete");
})
That's it!!
use
beforeSend: function () {
},
ajax method

MVC - nothing happens on click (Jquery in view)

I want my button to do something onClick(), it has the ID btnSend. But nothing happens when I click the button which is weird and I can't figure out why.
The script is in my view for now within script tags.
$("#btnSend").click(function () {
var messageInfo = {
"Body": $("#Message").val(),
};
$.ajax({
type: "POST",
url: '/Api/Posts',
data: JSON.stringify(messageInfo),
contentType: "application/json;charset=utf-8",
processData: true,
success: function (data, status, xhr) {
alert("The result is : " + status);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
Are you sure your script is running after the page is loaded?
Put your script at the bottom of the page and give it a try.

How to show progress bar when calling AJAX?

I am developing a mobile app using phonegap (JQ + Html ). In my app, consuming REST webservice using AJAX calls.When service invoke, I am showing a progress bar animated GIF image . The problem is, browser freezes when calling AJAX. So the progress bar is not showing.
In ‘beforeSend’ i am showing the progress bar image and after ‘complete’ i am hiding the progress bar image.
I am also trying async: true . But it execute service as asynchronously. In my app, asynchronous execution is not suit. Because asynchronous execution will not wait for ajax executing. My app should wait until the ajax execution complete. In that process time I want show progress bar.
Here is my code.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
accepts: "application/json",
beforeSend: function() {
StartPBar():
},
data: JSON.stringify(RQ),
async: false,
url: URL,
complete: function() {
stopPBar();
},
success: function(res, status, xhr) {
try {
RS = res;
} catch (e) {
alert(e);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Excpetion " + errorThrown + XMLHttpRequest);
}
});
Any suggestion to show the progress bar stay on screen until the process is fully complete? Any help would be appreciated. Thanks
Make sure you verify your javascript code.
Remove this code.
beforeSend: function() {
StartPBar():
},
Replace your jquery mobile with this one jQuery Mobile 1.4.0-rc.1
http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.js
Replace your code with this one.
$.mobile.loading('show');
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
accepts: "application/json",
data: JSON.stringify(RQ),
async: false,
url: URL,
complete: function() {
$.mobile.loading('hide');
},
success: function(res, status, xhr) {
try {
$.mobile.loading('hide');
RS = res;
} catch (e) {
alert(e);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$.mobile.loading('hide');
alert("Excpetion " + errorThrown + XMLHttpRequest);
}
});
Try to set async: true, the async: false will freeze the browser until the request is completed. Also move the async: true before beforeSend method.
The async: true, when supported by browser, basically means: browser will send data asynchronous and will not block or wait other actions from executing. This is the only in my opinion way to show the progress bar indicator. Because (from the documentation):
Note that synchronous requests may temporarily lock the browser,
disabling any actions while the request is active.
If you want to wait until ajax requests done, you can do it also with async:true like;
StartPBar():
$.when(runAjax()).done(function(result) {
// result conatins responseText, status, and jqXHR
stopPBar();
});
function runAjax() {
return $.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
accepts: "application/json",
data: JSON.stringify(RQ),
async: true,
url: URL,
success: function (res, status, xhr) {
try {
RS = res;
}
catch (e) {
alert(e);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Excpetion " + errorThrown + XMLHttpRequest);
}
});
}
In this example, when ajax request completed, progressbar stop function will be called.

How to show error message if no data is found?

Can you help me with this code?
function blub() {
$.ajax({
type: 'GET',
url: 'blups1.php?rid=10',
async: true,
cache: false,
dataType: 'json',
success: function(data){
var name = data[0].name;
alert('ok = '+name);
},
error: alert('nix gefunden')
});
}
In case of success it shows me what I want, but the alert from error always pop up at first. Where do I have to place that error alert so that it will only appear if there is no database?
I'm really not sure why one would just place the alert statement singularly as the callback. Put the alert in a function:
error: function(xhr, status, error) {
alert('nix gefunden');
}

Categories

Resources