MVC2 One Async Call, Multiple Async Updates - model-view-controller

I have an operation on my Page that then requires 3 long (few seconds each) operations to be performed in series. After each operation is performed though, I would like the controller to return a partial view and have the page update with a status (keeps the user informed, I find that if people know that stuff is happening they worry less). Is there a MVC 'way' of doing this, or should I just use jQuery to do it?
Thanks.

You will want to use jQuery to issue three separate calls to three separate control methods and update the three areas of the page upon return separately.
The only way to "bunch" up calls would be to combine it all into one, but you can't get return values fired back to the client upon return of more than one call (almost like streaming, there's nothing listening on the client end after you return your first result set, that connection is closed).

So I have created a slight hack, that seems to work:
On the client side I have:
function onClickHandler() {
updateUI("Beginning Batch...");
setTimeout(klugeyClick, 0);
}
function klugeyClick() {
$.ajax({ type: "GET", dataType: "json", url: "/ControllerName/Action1", success: function(msg) { updateUI(msg) }, async: false, error: function(XMLHttpRequest, textStatus, errorThrown) { updateUI("Action1 Error: " + XMLHttpRequest + " -- " + textStatus + " ---- " + errorThrown); } });
setTimeout(klugeyClick2, 0);
}
function klugeyClick2() {
$.ajax({ type: "GET", dataType: "json", url: "/ControllerName/Action2", success: function(msg) { updateUI(msg) }, async: false, error: function(XMLHttpRequest, textStatus, errorThrown) { updateUI("Action2 Error: " + XMLHttpRequest + " -- " + textStatus + " ---- " + errorThrown); } });
setTimeout(klugeyClick3, 0);
}
function klugeyClick3() {
$.ajax({ type: "GET", dataType: "json", url: "/ControllerName/Action3", success: function(msg) { updateUI(msg) }, async: false, error: function(XMLHttpRequest, textStatus, errorThrown) { updateUI("Action3 Error: " + XMLHttpRequest + " -- " + textStatus + " ---- " + errorThrown); } });
}
function updateUI(result) {
$("#UIelement").text(result);
}
On the server side I have:
Function Action1() As JsonResult
System.Threading.Thread.Sleep(3000)
Return Json("Operation One Complete...")
End Function
Function Action2() As JsonResult
System.Threading.Thread.Sleep(3000)
Return Json("Operation Two Complete...")
End Function
Function Action3() As JsonResult
System.Threading.Thread.Sleep(3000)
Return Json("Operation Three Complete...")
End Function
Now I have two problems. First, I would like to have a follow up message that displays "Batch Complete" but following the same pattern and just adding another 'klugeyClick' with a call to UpdateUI (with or without a seTimeout) causes the last operation message not to be displayed. I think the callback within the jQuery.ajax method makes this kluge work somehow but without an ajax call, I can't put any follow-up messages.
The next problem is that although all my calls are getting to my webservice and are returning json results just fine, I always get an error coming back from the jQuery callback. Any ideas why this might be?
Thanks.

So as far as I can tell, the only way to get a Follow up message to appear the way I want it do (i.e. a few seconds after my last operation) is to have a dummy webservice method that I call that returns the last message after a delay... crumby.
Now my last problem is that all of my calls to my jsonResult actions come back with a textStatus of 'error' to the client. Now according to the docs this means an http error, but how could there be an http error if the method was called on the server side correctly and a Json result was produced (verified by setting a breakpoint on the server)?

For our site we have a big action that requires some time. That action is composed by subactions, we aggregate the results and we build a nice view.
One year ago:
We were doing that in a sequence: action1, then action2, etc.
We had that typical page of: please wait.
Tricks that can help you:
We do parallel requests on the server side.
We wait for results in a results page. The javascript there needs some time to load, so while the server searches, we load the page.
We ask the server every second: have you finished? And we get partial results as the different actions complete.
I don't know if you can apply all of these things to your problem but some of then can be really nice.
We don't use MVC, we use some asmx services with jQuery and ajax.

The reason your "kludgy" solution works is because the setTimeout() method creates an event. Thus your logic is:
Update UI
Setup event for step 1:
Start "ajax" call
Wait for "ajax" to finish
Setup event for step 2
Start "ajax" call
Wait for "ajax" to finish
Setup event for step 3
Start "ajax" call
This is precisely what the callback feature of ajax() is for.
function Step1() {
$.ajax({
type: "GET",
dataType: "json",
url: "/ControllerName/Action1",
success: function(msg) {
updateUI(msg);
Step2(); // call step 2 here!
},
async: true, // don't block the UI
error: function(XMLHttpRequest, textStatus, errorThrown) {
updateUI("Action1 Error: " + XMLHttpRequest + " -- " + textStatus + " ---- " + errorThrown);
}
});
}
function Step2() {
// similar to step one
}

Related

Laravel - ajax post and go to another view with data

I´ve searching but with no luck, i´ve tried implementing many things but nothing lead to success, so this is my scenario:
At certain point the user is in a view where after filling some fields, he has the ability to save or save and create.
The first one it is working ok, i´m posting with ajax to my controller method and returning a json response, but the user stays normally in the same view.
The second one(when he saves and create) i´m sending a variable to say exactly that, and because of that choice, the user must be directed to another view to "create" BUT i need the data that was previously saved to automatically fill some fields on the new form that is suppose to be created...so my code is:
my ajax:
$.ajax({
method: 'POST',
url: '/Cliente/insertEditCliente',
dataType: "json",
data: {"_token": "{{ csrf_token()}}", "mainId":$('#mainId').val(),values,"btnId":this.text},
success: function(response){
if(response.titulo != "Erro!"){
let dados = response['dados'];
window.location = '{{ route("formAngariacao",[null]) }}'+'/?dados='+dados;
}
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
// console.log(JSON.stringify(jqXHR));
// console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
in my controller method, i have that if statment to detect if it was just save or save and create:
if($request->post('btnId') == "Guardar"){
return response()->json(["titulo"=>"Ok!","mensagem"=>"Cliente Alterado com sucesso!","tipo"=>"success"]);
}
else{
return response()->json(["titulo"=>"Ok!","mensagem"=>"Cliente Alterado com sucesso!","tipo"=>"success","dados"=>$request]);
}
But now, in my blade view, i need to read that array "dados" which corresponds to the $request variable and has all the data i need.
How do i do that? and is this the best practice?
thanks for your time reagards.

is there any difference between those AJAX methods?

I have two questions about jQuery AJAX.
1) Is there any difference between $.load() and $.ajax() used with type: 'GET'? They seem to do the same job.
2) This question is related to the code below. What happens, if I don't write the "type: GET" line at all? Does it mean the same thing?
$(document).ready(function() {
$('#update').click(function() {
$.ajax({
type: 'GET',
url: 'hello-ajax.html',
dataType: 'html',
success: function(html, textStatus) {
$('body').append(html);
},
error: function(xhr, textStatus, errorThrown) {
alert('An error occurred! ' + ( errorThrown ? errorThrown :
391
xhr.status );
}
});
});
});
Is it any different from
$(document).ready(function() {
$('#update').click(function() {
$.ajax({
url: 'hello-ajax.html',
dataType: 'html',
success: function(html, textStatus) {
$('body').append(html);
},
error: function(xhr, textStatus, errorThrown) {
alert('An error occurred! ' + ( errorThrown ? errorThrown :
391
xhr.status );
}
});
});
});
This is straight from jQuery Docs (http://api.jquery.com/load/)
The .load() method, unlike $.get(), allows us to specify a portion of
the remote document to be inserted. This is achieved with a special
syntax for the url parameter. If one or more space characters are
included in the string, the portion of the string following the first
space is assumed to be a jQuery selector that determines the content
to be loaded.
Since $.get() is simply the $.ajax() shorthand for "data: 'Get'", it would appear the only major difference is the ability to do the aforementioned (import partial sections of a document).
Edit: To answer your second question, GET is the default data type for the $.ajax() call, POST being your other option. You can read a bit about POST here (http://api.jquery.com/jQuery.post/)
Extracted from jQuery manual .load
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success) except that it is a
method rather than global function and it has an implicit callback
function. When a successful response is detected (i.e. when textStatus
is "success" or "notmodified"), .load() sets the HTML contents of the
matched element to the returned data. This means that most uses of the
method can be quite simple:
$( "#result" ).load( "ajax/test.html" );
If no element is matched by the selector — in this case, if the
document does not contain an element with id="result" — the Ajax
request will not be sent.
I guess the difference is that .load() function allows to target the result into a DOM element. Like so
$( "#target" ).load( "source.html" );
And the ajax() method returns an object (eg. JSON) that can be the manipulated. etc. apart from more attributes.

ajax always going to success

I'm having troubles with ajax. my code runs well, but then, it always goes to success.
dataLogin = 'mail=' + $('#login_mail').val() + '&pass=' + $('#login_password').val() + '&on=' + manter_ligado;
$.ajax({ url: 'modules/login.php?' + dataLogin,
type: 'POST',
//data: dataLogin,
data : {
mail : $('#login_mail').val(),
pass : $('#login_password').val(),
on : manter_ligado
},
success: function(data) {
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
can anyone help me with this?
Also, I'm using sublime to code, and it gives me some errors on the ajax, but I can't seem to correct them, it might help knowing this
Also, I know that the php works, because I can make the login on the website, but the problem I have is when the user/pass is incorrect
Make sure the server is returning an error code of 500.
In the php.ini file, make sure displayErrors is set to Off
To get the ajax to hit the failure function, you may need to throw an error when one occurs in your PHP

how to specify a different function for each statement in JQuery .always() function

According to the official JQuery documentation:
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { });
An alternative construct to the complete callback option, the
.always() method replaces the deprecated .complete()method.
In response to a successful request, the function's arguments are the
same as those of .done(): data, textStatus, and the jqXHR object. For
failed requests the arguments are the same as those of .fail(): the
jqXHR object, textStatus, and errorThrown. Refer to deferred.always()
for implementation details.
And let's say that I have the following ajax script :
$.ajax({
url: 'myPHPScript.php',
type: 'POST',
data: {
param_1: 'value_1',
param_n: 'value_n'…
},
username: 'myLogin',
password: 'myPassword',
beforeSend: function() {
alert('The object was created but not yet initilized');
}
}).done(function(data, textStatus, jqXHR) {
alert('All the request was sent and we received data');
}).fail(function(jqXHR, textStatus, errorThrown) {
alert('Error: the following error was occurred: ' + textStatus + ' Status : ' + jqXHR.Status);
}).always(function() {
// Here is my problem
});
In the .always() function, how can I specify a different function for each statement, I mean when the Deferred is resolved, the always() function gets passed the following params (data, textStatus, jqXHR) however if the deferred is rejected it gets passed (jqXHR, textStatus, errorThrown).
Thanks
The only good solution is not using the arguments in always - if you need code specific to the success/failure of the AJAX call out them in done or fail callbacks. Usually the always callback is a place where you do things such as re-enabling a button, hiding a throbber, etc. All those are things where you do not care about the result of the request.
Besides that, you could check arguments.length for the number of arguments and then access the arguments via arguments[0] etc. But relying on the argument count is a bad idea since it might not be future-proof.

Check status of a jQuery ajax request

It seems that the success, error, and complete callbacks only fire when the ajax request is able to get some response from the server.
So if I shut down the server the following error callback is not executed and the request fails silently.
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});
What's the best way to throw an error when the server can't be reached at all.
Edit - From what I've tried and read it appears that jQuery's built in error handling doesn't work with JSONP, or dataType: "script". So I'm going to try setting a manual timeout.
Edit - Did a little more research and it looks like not only does the ajax error callback not work, but you can't abort an ajax request with dataType script or jsonp, and those requests ignore the timeout setting.
There is an alternative - the jquery-jsonp plugin, but it uses hidden iframes which I'd rather avoid. So I've settled on creating a manual timeout as suggested below. You can't abort the request if it times out, which means the script may still load even after the timeout, but at least something will fire if the server is unavailable.
You can use a setTimeout, and clear it with clearTimeout in the complete handler.
var reqTimeout = setTimeout(function()
{
alert("Request timed out.");
}, 5000);
var xhr = $.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
},
complete: function() {
clearTimeout(reqTimeout);
}
});
jQuery.ajax already has a timeout preference and it should call your error handler should the request time out. Check out the fantastic documentation which says — I’d quote it here, emphasis mine:
timeoutNumber
Set a local timeout (in milliseconds) for the request…
and:
error (XMLHttpRequest, textStatus, errorThrown) Function
A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event.
error: function (jqXHR, textStatus, errorthrown) {
if (jqXHR.readyState == 0) {
//Network error, i.e. server stopped, timeout, connection refused, CORS, etc.
}
else if (jqXHR.readyState == 4) {
//HTTP error, i.e. 404 Not found, Internal Server 500, etc.
}
}
Use readyState of XMLHttpRequest to determine the status of the ajax request.
'readyState' holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
If I remember correctly, jQuery throws exceptions. Thus, you should be able to work with a try { ... } catch() { ... } and handle it there.
You can use Jquery's AjaxSetup to handle your error handling.
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function () {
alert("success");
}, error: function () {
alert("error");
}
//AJAX SETUP "error"//
$.ajaxSetup({
"error": function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + ' ' + textStatus + ' ' + errorThrown); //however you want
}
});
in ie8,can use:
success: function(data, textStatus, XMLHttpRequest) {
if("success"==textStatus&&XMLHttpRequest){
alert("success");
}else{
alert("server down");
}
}
but it's can't work on chrome,firefox...
i tried

Resources