I implemented a system on my ASP.NET Web Forms site for passing notifications to the client. The notifications can be validation messages, success messages, warnings, errors etc. These messages are generated by code on the server side and then retrieved from the server via script on the client side and displayed.
On each page of my site I have embedded a JavaScript function that calls a web service (on the server side) via jQuery AJAX and requests the latest notifications. If there are notifications, they are displayed using Noty. On the server side, messages that have been sent to the client are removed from the queue.
This works pretty well. However, let's say I'm on a page called NewEmployee.aspx and they create a new employee by filling out a new form, and this generates some kind of notification such as "New Employee Created With ID 58478" and also takes them to the ViewEmployee.aspx page. If the postback happens slowly enough, the message will start to display while the user is still on NewEmployee.aspx but before the user arrives at ViewEmployee.aspx. The end result is that the notification is only displayed for a split second and the user never sees it.
I need a way in JavaScript on the client side to detect if the page is performing a postback. If I have that, I can prevent it from calling the webservice during a postback and have it wait until it completes. I want it to look something like this.
setInterval(oneSecondFunction, 1000); //check for messages every 1 second
function oneSecondFunction()
{
var IsPostingBackRightNow=GetIsPostingBackStatus(); //I need your help writing this function
if(!IsPostingBackRightNow)
{
$.ajax({
type: 'POST',
url: 'myurl/MessageService.asmx/GetCurrentMessage',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ sessionid: sessionid, locale: 'en-US' }),
dataType: 'xml',
success: function (msg)
{
//show message via noty if there's a message
}
});
}
}
The post back is passing from the form, so you capture the onsubmit event on the form, and there you open your flag.
Here is how... add that on code behind
Page.Form.Attributes["onsubmit"] = "return GoForPostBack();";
to have this attribute also rendered on your form...
<form ... onsubmit="return GoForPostBack();">
and the javascript
var IsPostingBackRightNow = false;
function GoForPostBack()
{
IsPostingBackRightNow = true;
return true;
}
setInterval(oneSecondFunction, 1000); //check for messages every 1 second
function oneSecondFunction()
{
if(!IsPostingBackRightNow)
{
$.ajax({
type: 'POST',
url: 'myurl/MessageService.asmx/GetCurrentMessage',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ sessionid: sessionid, locale: 'en-US' }),
dataType: 'xml',
success: function (msg)
{
//show message via noty if there's a message
}
});
}
}
Related
I'm making a MVC C# Web App, and I began wondering whether you could open other pages that need parameters to function, without actually sending them through the URL, which is unsafe, and can lead to some user messing up another registry of the database.
My issue is though, I've never done such a thing, and I cannot find any example of code that does such a thing. The project is run with C# and JS, and the main things I've tried include:
-Doing so with Ajax:
First of all I have a button that calls for a function:
Link Text|
function openHorario(id, id_schedule, id_tool) {
alert(oid, id_schedule, id_tool);
$.ajax({
type: 'POST',
url: '/Schedules/actionEditStuff',
data: {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
},
async: 'false',
success: function (data) {
//???
}
});
}
I know there's a way to go to a new page with the success Ajax return, but... That also requires for you to send the parameters through URL.
Obviously, that didn't work, because what the action does in the controller is to return a view, not a page. So... I realized that my idea was not very smart, and moved onto somewhere else: Link, but those always end up having to send the parameters visibly through URL.
Is there any way at all to do this in a proper, clean manner?
Thank you!
#Layan - just to illustrate my comment above, - you could implement something along these lines:
your client side invokes via ajax
...
var data = {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
};
$.ajax({
url: '/Schedules/actionEditStuff',
type: "POST",
data: data,
contentType: 'application/json; charset=utf-8',
success: function (view) {
//load returned data into div? or popup?
}
, error: function (xhr, status, error) {
...
}
});
...
and your controller action
public ActionResult actionEditStuff(....parameters...)
{
...
...do your magic ...
return PartialView("~/Views/_PartialViewThatShowsSomething.cshtml", ...pass model...);
}
I have a website that basically makes API calls and displays the data in a table; the API is on a different server from the website.
If the API server is down what is the best way to alert the user client-side (JavaScript) that the server is unavailable?
Could/Should I put the alert in the API call error handling (See code for example)? What is the best practice for this type of situation.
function apiCall(query, product){
var p = product;
var urlr='https://myFakeAPIUrl/api/'+query+'/'+ product;
$.ajax({
contentType: 'application/json',
crossDomain: true,
url: urlr,
type: "GET",
success: function (result){
alert("Yay, the API server is up.");
},
error: function(error){
console.log(error);
alert("Sorry, the server is down.");
}
});
}
var productData = apiCall("Produce", "112233");
I would ask myself what a user would like to see in this situation.
What I always do is putting a timeout on the Ajax request, whenever that timeout of e.g. 9999ms runs out, the user should get notified (with a toast, a heading, etc..) that something went wrong and that they should try it again later.
I have an application that is written on the top of ASP.NET MVC 5 framework. For one page, I am using this awesome jQuery-QueryBuilder plugin to let the user create filters to narrow down the results of the dataset.
When the user submits the form "by clicking the submit button" I want to call a function builder.queryBuilder('getRules') provided by jQuery-QueryBuilder which returns and object that needs to be sent to the server. I don't want the request to be sent as string. Also I don't want to sent it as ajax request.
Here is what I have done. The following code is not working. When the server receives the request the rules are always null.
$('#submit-form').click(function (event) {
event.preventDefault();
var btn = $(this);
var rules = builder.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
$('#QueryBuilder_Rules').val(rules);
btn.closest('form').submit();
}
});
I tried to use AJAX to send the post request to the server like the code below shows. The code below worked fine. However, I don't want to use AJAX, I want to do the same thing using regular form post request
$('#submit-form').click(function (event) {
event.preventDefault();
var btn = $(this);
var rules = builder.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
$.ajax({
type: "POST",
url: url,
data: {Rules: rules}
});
}
});
How can I correctly send the rules object as an object not a string to the server using standard post request?
What is the problem in using Ajax?
You may consider doing the following:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({Rules: rules}),
dataType: "json",
contentType: "application/json",
success: function (json) {
}
[HTTPPost]
public void Rules(YourClass[] array){...}
I'm trying to catch data from the AJAX POST, which I've sent via jQuery to controller endpoint of ASP.NET MVC, like this:
$("form#auth").submit(function() {
var login = $('input[id=login]').val();
var password = $('input[id=password]').val();
$.ajax({
url: "/Home/Auth",
type: "POST",
data: "Login=" + login + "&Password=" + password,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
success: function() {
}
});
I've tested the controller understads what I'm sending to him, but the main problem is with the returning the result for my jQuery function.
I'm returning the result from Controller like this:
http://ideone.com/hNkF3Z
But I don't understand why the server is returning a file for download:
If to open the file, the result is valid: {"Result":"failed"}
I know, that I didn't write a code in a success function in JavaScript, but I think server must not return a file download and also the debugger must stop at the breakpoint, which was defined on last scope } of success function.
What you're seeing is the default form submission. Because you don't prevent the default browser action, the form is still being posted as if the event handler wasn't even there.
Update your JavaScript to prevent the default browser behavior with e.preventDefault()
$("form#auth").submit(function(e) {
e.preventDefault();
/* rest of your code here. */
}
I am trying to use .ajax to test a login page we have on an internal app (basic auth) and view the http status code. However, the modal window still pops up prompting for login credentials. Why is this? I am trying to get this to take place behind the scene.
Code:
$(document).ready(function() {
$.ajax({
url:"./testurl.aspx",
type: "POST",
data:{
username: "Test",
password: "Password"
},
complete: function(xhr){
alert(xhr.status);
}
});
});
But still I get this:
And then of course the alert(xhr.status) will display, but I need this to without manually entering the username/pw.
HTTP Basic Authentication is either passed as an HTTP header or in the URL, not in the POST body.
Example putting it in the URL:
$.ajax({
url:"//Test:Password#" + location.host + "/path/to/testurl.aspx",
type: "POST",
complete: function(xhr){
alert(xhr.status);
}
});
You can also use the ajax method's headers property to try and add the header, but that requires Base64 encoding the password.