MVC & jQuery & Ajax: Wait for JavaScript to be loaded - javascript

I am using ASP.NET MVC and jQuery and I am loading a PartialView via Ajax. A seperate JavaSriptFile belongs to this PartialView. On success, the return html is inserted in the DOM. In the JavaScript, some stuff is done and that together might take a little moment. The loaded content is then displayed in a dialog.
Simplified Code:
1 $.ajax({
2 url: /user/edit,
3 dataType: 'html',
4 data: { id: 1 },
5 success: function (htmlCode) {
6 $('#dialogEditUser').html(htmlCode);
7 $('#dialogEditUser').dialog('open');
8 });
9 };
This code works and sometimes not, depending on how fast the PartialView's JavaScript is executed. So sometimes, the dialog does not open. So i changed line number 7 to;:
7 setTimeout(function() { $j('#dialogEditUser').dialog('open') }, 250);
Now everything works fine. But this "hack" is not very suitable. How can I check if the PartialView's JavaScript has been executed on the loaded content? Is there maybe any way to return a fully rendered PartialView (so the JavaScript has already been executed where I get the return of the AjaxCall?

By default ajax will not wait for the request to finish.
Try setting async option to false:
$.ajax({
url: /user/edit,
dataType: 'html',
async: false,
data: { id: 1 },
success: function (htmlCode) {
$('#dialogEditUser').html(htmlCode);
$('#dialogEditUser').dialog('open');
});
};
More details in docs

Why not make the $('#dialogEditUser').dialog('open'); in the js you are loading? That way when the call is made you know the corresponding js is loaded already

Try wrapping that code in a ready block:
$(document).ready(function(){
$.ajax({
url: /user/edit,
dataType: 'html',
data: { id: 1 },
success: function (htmlCode) {
$('#dialogEditUser').html(htmlCode);
$('#dialogEditUser').dialog('open');
});
};
});
'#dialogEditUser' might to be loaded yet when the success callback gets called.

If, at the end of your partial view, you have got an element with an specific id like #finishLoad. Why not try this?
var waitToOpenDialog = function(){
var jFinish = $('#finishLoad');
if(jFinish.length<=0){
setTimeout(waitToOpenDialog, 10);
}else{
$('#dialogEditUser').dialog('open');
}
}
$.ajax({
url: /user/edit,
dataType: 'html',
data: { id: 1 },
success: function (htmlCode) {
$('#dialogEditUser').html(htmlCode);
waitToOpenDialog();
});
};
Well if you cant modify your DOM or don't have any id like #finishLoad you cant try (keeping async=true) with (more or less) this:
var waitToOpenDialog = function(){
var jDialogUser= $('#dialogEditUser');
if(jDialogUser.html().length<=0){
setTimeout(waitToOpenDialog, 10);
}else{
jDialogUser.dialog('open');
}
}
$.ajax({
url: /user/edit,
dataType: 'html',
data: { id: 1 },
success: function (htmlCode) {
$('#dialogEditUser').html(htmlCode);
waitToOpenDialog();
});
};
Or you can try with complete:
$.ajax({
url: /user/edit,
dataType: 'html',
data: { id: 1 },
success: function (htmlCode) {
$('#dialogEditUser').html(htmlCode);
},
complete: function(){
$('#dialogEditUser').dialog('open');
}
)};

Related

AJAX trigger remote script then check for success-response

I've been searching my brains out but I can't seem to wrap my head around the little help I find.
I'm running a database that is being fed by data from another DB. The csv transport is handled by a third party server providing executable "flows" which compile and deliver the data.
I have a php script to handle the request (can't be done directly via Javascript because of the missing 'Access-Control-Allow-Origin' header). But this runs nicely. I can trigger the flow.
This is not the problem though.
What I want to do: trigger the flow #onClick of a button with something like this:
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
console.log(jsonResult.runID);
}
});
}
With the flowID and the resulting runID I want to check back like every second or so.
function check_status(flowID, runID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){...}
});
}
This will return the status / progress of the flow.
It will start for a few seconds with status==null, then go on to status=='running' and finally status=='success'.
I have gotten check_status() to run for i.e. 15 times with a setTimeout in a for loop within the success-function of trigger_func() and it works fine too.
But I cannot for the life of me figure out how I would link this stuff together to have it checking until status is 'success' and then stop checking, update page content and so on...
I have also fiddled with something like
trigger_func(id).done(function(result){
console.log(result);
});
This works too but still I can't think my way further to the checking every second until 'success'. I guess it comes down to getting the variable 'status' back into my loop so I can break it.
Maybe someone knows of a comprehensible example somewhere online...
You could do this:
function periodically_check_status_until_success(flowID, runID) {
setTimeout(function() {
$.ajax({
url: './ajaxPHP_handler.php',
data: { flowid: flowID, action: status, runId: runID },
dataType: 'json',
success: function(result){
if (result != 'success') {
periodically_check_status_until_success(flowID, runID);
}
}
});
}, 5000); // Five seconds
}
Note: You can use an object for the data option, rather than concatenate the string yourself.
So just keep calling it
var flowID, runID;
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
runID= jsonResult.runID;
check_status();
}
});
}
function check_status() {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){
if (result is not what you want) {
setTimeout(check_status,1000);
}
}
});
}
ajax are async so you have to manage by this via some 3rd party variable
Like Init with value 0
var _status = 0
than change it on your first call set it 1
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
console.log(jsonResult.runID);
check_status(flowID, runID);
}
});
}
function check_status(flowID, runID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){
//at end status=='success'.
if(status=='success'){
// end part
}else{// running
check_status(flowID, runID);
}
// clear timeout will stop that time interval after success
}
});
}

Ajax redirect on error

I'm calling php file through ajax call and if it returns nothing i want to redirect user to another page (It's for error reports, if it doesn't return anything it means that user logged in). Tried to add error section but it doesn't work. Any suggestions will help. Thanks! Btw, I have small jQuery function at the top of the ajax function, why it breaks my whole ajax call?
ajax.js
function loginAjax() {
//$("#email_errors").empty(); //This function doesnt work and kills whole ajax call. Here is loginAjax function call line - <button type = "submit" id = "push_button" onclick = "loginAjax(); return false">PushMe</button>
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
}
});
}
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
},
error: function(){
window.location.replace("http://stackoverflow.com");
}
});
}
To redirect using javascript all you need to do is override the location.href attribute.
function loginAjax() {
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
// the success method is deprecated in favor of done.
done: function(data) {
$("#login_error").html(data.login_message);
},
fail: function(data) {
location.href="path/to/error/page";
}
});
}

IE 9, 10, 11 - Ajax calls not returning

I am having an issue with IE related to jQuery and ajax. Chrome and Firefox work just fine, but my ajax calls are disappearing in IE.
After making the ajax call, neither the success nor the fail functions are being called. I can see the response in the IE console, and I know my controller action is being hit.
$.ajax({
url: controllerUrl
type: 'POST',
dataType: 'json',
cache: false,
data: {
id: customerId
},
success: function () {
alert('success!');
},
error: function () {
alert('failed!');
}
});
Has anyone else seen this issue?
fail: function () {
alert('failed!');
}
fail is not a valid jQuery ajax setting. I believe you are looking for error.
Also, cache: false, does nothing with POST requests.
Note, jQuery does not append the time stamp with POST requests.
The source code clearly demonstrates this. (summarized from https://github.com/jquery/jquery/blob/master/src/ajax.js)
var rnoContent = /^(?:GET|HEAD)$/;
s.hasContent = !rnoContent.test( s.type );
if ( !s.hasContent ) {
/* code to append time stamp */
}
You are missing a comma , after your URL parameter:
$.ajax({
url: controllerUrl, // <--- you were missing this comma!
type: 'POST',
dataType: 'json',
cache: false,
data: {
id: customerId
},
success: function () {
alert('success!');
},
error: function () {
alert('failed!');
}
});

Show a loading bar using jQuery while making multiple AJAX request

I have function making multiple AJAX request with jQuery like:
function() {
$.ajax({
url: "/url",
data: {
params: json_params,
output: 'json'
},
async: false,
success: function(res) {
data1 = res
}
});
$.ajax({
url: "/url",
data: {
params: json_params,
output: 'json'
},
async: false,
success: function(res) {
data2 = res;
}
return data1 + data2;
});
}
While this function is running and data is loading I want to display a loading image without blocking it.
I have tried showing the loading icon using ajaxSend ajaxComplete, but does not work, since I have multiple ajax calls.
I also tried showing the loading at the beginning of the function and hiding at the end of the function, but failed.
How to do this?
How exactly did you try loading? Using the ajaxStart/ajaxStop events on the elements is one way to accomplish what you want. It could look like this:
$('#loadingContainer')
.hide() // at first, just hide it
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
Maybe this helps you, I often used this before and it works like a charm..
I think the answer is really a combination of several of these. I would begin with ajax start to show the loading image at 0 (or whereever you want the start to be). Then I would use a callback function to increment the loading bar and repaint it.
For example
//when ajax starts, show loading div
$('#loading').hide().on('ajaxStart', function(){
$(this).show();
});
//when ajax ends, hide div
$('#loading').on('ajaxEnd', function(){
$(this).hide();
});
function ajax_increment(value) {
//this is a function for incrementing the loading bar
$('#loading bar').css('width', value);
}
//do ajax request
$.ajax({
url:"", //url here
data: {params:json_params,output:'json'},
async: false,
success: function (res) {
data1=res
ajax_increment(20); //increment the loading bar width by 20
}
});
$.ajax({
url:"", //url here
data: {params:json_params,output:'json'},
async: false,
success: function (res) {
data1=res
ajax_increment($('loading bar').css('width') + 10); // a little more dynamic than above, just adds 10 to the current width of the bar.
}
});
You could try something like this: Define a callback with a counter, and the callback hides the image after it's been called the required number of times.
showLoadingImage();
var callbackCount = 0;
function ajaxCallback() {
++callbackCount;
if(callbackCount >= 2) {
hideImage();
}
}
$.ajax({
url:"/url",
data: {params:json_params,output:'json'},
async: false,
success: function (res) {
data1=res
ajaxCallback();
}
});
$.ajax({
url:"/url",
data: {params:json_params,output:'json'},
async: false,
success: function (res) {
data2=res;
ajaxCallback();
}
});
That's only necessary for asynchronous calls, though. The way you're doing it (all your AJAX calls are synchronous), you should be able to just call hideImage() before returning at the end of your outer function.
You should be able to bind to the start and then end with the following:
$('#loading-image').bind('ajaxStart', function() {
$(this).show();
}).bind('ajaxStop', function() {
$(this).hide();
});
Or you could use beforeSend and on Complete
$.ajax({
url: uri,
cache: false,
beforeSend: function() {
$('#image').show();
},
complete: function() {
$('#image').hide();
},
success: function(html) {
$('.info').append(html);
}
});

jQuery Ajax Function

I am trying to write a jQuery Ajax function, to reduce the amount of code in the page because the script is called a few times in the page. I can't seem to get it to work. Here is the code i have:
var loadURL = $(this).attr('href');
function load(){
$.ajax({
url: loadURL,
type: 'GET',
cache: true,
data: {
delay: 4
},
success: function(data) {
$('#load').html(data)
}
});
return false;}
$('#one').click(function(){ load(); });
$('#two').click(function(){ load(); });
$('#three').click(function(){ load(); });
Two
Two
Two
can anyone guide me here please?
i think the way you are getting href is wrong
function load(item){
var loadURL = $(item).attr('href');
$.ajax({
url: loadURL,
type: 'GET',
cache: true,
data: {
delay: 4
},
success: function(data) {
$('#load').html(data)
}
});
return false;}
$('#one').click(function()
{
load($(this));
return false; //you should mention return false here
});
It is worth noting that you can define your own jQuery functions if you wish..

Categories