Showing message before page refresh using jQuery - javascript

I want to display ajax result message before page refresh, but something is wrong. My code is like this:
$.ajax({
cache: false,
type: "POST",
url: "#(Url.RouteUrl("DummyRequest"))",
success: function (data) {
if (data.Success) {
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
setInterval(function () {
location.reload();
}, 5000);
}
else {
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
/*setInterval(function () {
location.reload();
}, 5000);*/
}
},
error: function (xhr, ajaxOptions, thrownError) {
$('#dummy-notification').text("Something went wrong.").fadeIn("slow").delay(3000).fadeOut("slow");
}
});
My code is working just fine on else situation. When I tried, message appears, then after 5 secs page reloads itself. But when if situation is on, page reloads itself, however message doesn't show.
How can I solve this problem?

Its depends on response time of server.. so if response from server is late then not working correctly.. so you have to wait for AJAX response then you have to display popup and redirect. so use ajax option async: false in your ajax request. as mentioned below
$.ajax({
cache: false,
async: false,
type: "POST",
url: "#(Url.RouteUrl("DummyRequest"))",
success: function (data) {
if (data.Success) {
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
setInterval(function () {
location.reload();
}, 5000);
}
else {
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
/*setInterval(function () {
location.reload();
}, 5000);*/
}
},
error: function (xhr, ajaxOptions, thrownError) {
$('#dummy-notification').text("Something went wrong.").fadeIn("slow").delay(3000).fadeOut("slow");
}
});

Try something like this:
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow", function () {
setTimeout(function () {
location.reload();
}, 5000);
});
The difference is that the setTimeout() will not be called until after the fadeOut() is finished executing.

Related

Display Ajax response in HTML page

I looked over tens of similar questions but I couldn't find the solution I needed. Sorry in advance if this is a duplicate. I want to show the Ajax response in the page, once the window is loaded.
Code
HTML
<ul class="rate-ul">
<li id="LTL">LTL Freight</li>
</ul>
and the jquery part to change it is:
Javascript/jQuery
if(condition){
$("#LTL").change(UpdateLTLRating);
}
function UpdateLTLRating() {
console.log("update shipping called");
$.ajax({
url: window.location.href,
data: 'call=ajax&method=ltlRateList&'
type: 'POST',
success: function (resp) {
console.log(resp)
$(".rate-ul").html(resp);
},
error: function (xhr, status) {
alert("Sorry, there was a problem!");
}
});
I get the update shipping called in the console, but I don't get resp called on the windows load. When I attach it to a button click event, I get the resp in the console as well. I haven't been able to get resp on the page.
From your sample, it's not clear that you're even calling your function on window load to get the data you want, if this is the case in your original code, here's how you can do it:
if(condition){
$("#LTL").change(UpdateLTLRating);
}
function UpdateLTLRating() {
console.log("update shipping called");
$.ajax({
url: window.location.href,
data: 'call=ajax&method=ltlRateList&'
type: 'POST',
success: function (resp) {
console.log(resp)
$(".rate-ul").html(resp);
},
error: function (xhr, status) {
alert("Sorry, there was a problem!");
}
});
}
$(document).ready(function() {
UpdateLTLRating();
});

Calling beforeSend in ajax success

How to call beforeSend only in success? Right now, my button is also changing text to "Working" when error comes into ajax call.
success: function(data) {
alert("operation successful");
},
beforeSend: function() {
btnSubmit.val("Working...");
},
error: function(response) {
alert("something went wrong");
}
Use "complete" to alter the button text
complete: A function to be called when the request finishes (after success and error callbacks are executed)
success: function(data) {
alert("operation successful");
},
beforeSend: function() {
btnSubmit.val("Working...");
},
error: function(response) {
alert("something went wrong");
},
complete:function() {
btnSubmit.val("Done");
}
}

Javascript/Jquery check my if/else statement?

I'm working with someone else's code trying to get an alert to come up to notify the user if the operation was unsuccessful. I put an "if (true)" statement in front of the function and then an "else" statement after the function, thinking that IF the function ran successfully, it would alert the user with "success" otherwise it would alert "operation failed". Did I do this right? I'm completely new to Javascript.
$("#assignBtn").on("click", function () {if(true){
$.ajax({
type: "GET",
url: $SCRIPT_ROOT + '/_parse_checklist/assign_checklist',
data: {
username: $("#assignChecklistTo").val(),
id: $clientSelect.val()
},
dataType: "json",
beforeSend: function () {
},
complete: function () {
alert("Success!");
}
});}
else {alert("Operation unsuccessful...")}
});
Instead of if/else you can use ajax methods:
success: function(data) {
// success
},
error: function(data) {
// error
}

Hide and Show div in ajax call in external js file

I am using ASP.net MVC, and following is the Html code
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
<div id=waitscreen>
//some code
</div>
Code in external js
function _post(someparameter)
{
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
Also tried adding document ready in above code it is still not working
Above code worked fine and it show and hide as expected, but now I need to repeat ajax call in every page so I decided to move in external JS file now same code is not showing waitscreen.
Things I tried:
Loaded external script in head - Not working
Loaded external script at end of page - Not working
Question: I want to make hide and show work from external JS file
The following code snippet should help you. Tested by including the external JS file in the <head> of the main document and just below the inclusion of jQuery.
// main window
var json = {"key": "value"}
console.log('before calling _post()');
_post(json); // call external JS
// code in external JS say test.js
function _post(someparameter)
{
console.log('external JS called!');
$.ajax({
type: "POST",
url: 'http://www.niketpathak.com',
dataType: 'json',
data: someparameter,
async: true,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
// $("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
//delaying the error callback
setTimeout(function() {
$("#waitscreen").hide();
console.log('after completing the http-request');
}, 500);
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=waitscreen>
Waitscreen....
</div>
Also, note that I have used async: true (which is also the default) since setting it to false is deprecated and not a good idea as it blocks the UI.
My ajax code in External.js file,
function _post()
{
var data = {
Email: "a#a.com",
Password:"1111"
}
$.ajax({
type: "POST",
url: "/Home/hello/",
dataType: 'json',
data: data,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
In my HomeController, I have hello method like this,
[HttpPost]
public ActionResult hello(LoginViewModel data)
{
ViewBag.Message = "Your contact page.";
return Json(data, JsonRequestBehavior.AllowGet);
}
And in my all the views I have the "waitscreen" div.
Now I just reference the External.js file to my _Layout page, I just drag and drop after jquery reference.
<script src="~/Scripts/External.js"></script>
Then in end of the same _Layout page, i just call the method like this,
<script>
_post();
</script>
Everything working properly.
Note: If you have only one parameter in your hello action method and suppose you have written like (int x) then in that case it will through 500 error. Because in your RouteConfig.js its mentioned that, by default the parameter name should be id. So you need to write int id.
Hope its help.

React Ajax setInterval Memory leak

I looked and tried everything in the other questions. Still couldn't solve my memory leak. Here's the code. Essentially it gets a JSON file from a server and updates the table accordingly. It loops the AJAX call every 5 seconds.
Memory leak happens in this AJAX call.
Any help would be great.
LoadDataTable: function(){
$.ajax({
url: "***************************.json",
dataType: 'json',
cache: false,
timeout: 5000,
success: function(data) {
this.setState({temp1:data[2].field3}),
this.setState({temp2:data[2].field5}),
this.setState({temp3:data[2].field25}),
this.setState({temp4:data[2].field26});
if(data[2].field3 > 9 || data[2].field5 >9||data[2].field5>9 ||data[2].field26>9){
document.location.href='#/'
}
else{
//console.log("Stopped playing");
}
setTimeout(this.LoadDataTable, 5000);
}.bind(this),
error: function(request, status, err) {
//request.abort();
console.log(request);
setTimeout(this.LoadDataTable, 5000);
}.bind(this),
})
},
componentDidMount: function() {
this.LoadDataTable();
//this.setInterval(this.LoadDataTable, 100);// Call a method on the mixin
},
Try moving your success and error functions out to a named function like this:
$.ajax({
url: "***************************.json",
dataType: 'json',
cache: false,
timeout: 5000,
success: this.successTimeout,
error: this.errorTimeout,
})
componentDidMount: function() {
this.LoadDataTable();
//this.setInterval(this.LoadDataTable, 100);// Call a method on the mixin
},
successTimeout(data) {
this.setState({temp1:data[2].field3}),
this.setState({temp2:data[2].field5}),
this.setState({temp3:data[2].field25}),
this.setState({temp4:data[2].field26});
if(data[2].field3 > 9 || data[2].field5 >9||data[2].field5>9 ||data[2].field26>9){
document.location.href='#/'
}
else{
//console.log("Stopped playing");
}
setTimeout(this.LoadDataTable, 5000);
}.bind(this),
errorTimeout(request, status, err) {
//request.abort();
console.log(request);
setTimeout(this.LoadDataTable, 5000);
}.bind(this)
Also, you might want to think about using the fetch API. Just be sure to include the polyfill for browser compatibility

Categories

Resources