I am stuck on this since yesterday, now I need help. I don't know how to properly 'question' this, but I think this is around the concern of ajax is asynchronous.
I am unable to complete the ajax call from my view when I call an ajax function inside an ajax postback.
$.ajax({
url: '#Url.Action("GetValidateAssignAccountName", "AccountsAssignment")?companyID=' + companyid,
type: request_method,
data: form_data
}).done(function (data) {
if (data == '') {
PromptAssign(data, post_url, request_method, form_data);
}
else {
Assign(post_url, request_method, form_data);
}
});
Assign function doesn't work/complete. I don't know how to call it, but it goes through the controller and calls the stored procedure, returns a success msg, but for some reason, the procedure did not work/save.
My problem is that, when I call PromptAssign - in which case I call a messageDialog and then call the Assign inside, right there the Assign does the job. Here is the PromptAssign function:
$("#messagedialog").dialog({
open: function () {
$(".ui-widget-overlay").css({ background: "#000000", opacity: 0.5 });
$(".ui-dialog-title").css("color", "#228B22");
//$(".message-img").attr("src", "../Content/images/success.png");
$(".message-wrapper").html(msg);
},
modal: true, height: 250, width: 500,
buttons: {
//'Ok': function () { $(this).dialog('close'); },
'Assign': function () {
Assign(post_url, request_method, form_data);
$(this).dialog('close');
},
'Close': function () { $(this).dialog('close'); }
},
create: function () {
$(this).closest(".ui-dialog")
.find(".ui-button").eq(2)
.addClass("btn btn-default");
},
title: "Confirmation",
dialogClass: "noclose"
});
Initially, the code was just the assign function which calls an sp to save a data. But we added the PromptAssign (first code block, then call a msgbox/PromptAssign, then assign) which is a validation if its existing or not, then the user can still Assign after if he still chooses to.
So when the validation returns nothing, I don't need to PromptAssign, so I just call the Assign straight away. This is not working. Anything I am missing on how to use ajax?
Just to answer the comments, there was an earlier problem like this that goes to the ajax, and then to the controller executing the stored procedure but for some reason the data isn't updated. We fixed the issue by making those ajax calls in a separate function.
For this one, I was trying to apply the same thing to no avail, I know there is nothing wrong in my way of using ajax, turns out, it was a data issue. The specific record in which I was testing is not working properly due to database validations. Still, thank you for looking at it.
Related
I need to access a js variable declared in one block of a html page into another block of the same html page just so I can stop a ajax call that is being made, but I don't know how can I access a variable that was declared into another block. I can't merge the two blocks, everything else is on the table.
<script>
$(function() {
var term = new Terminal('#input-line .cmdline', '#container output');
term.init();
});
</script>
<script>
term.ajaxHandler.abort();//but how can I access the variable term from the block above,this will be inside a button later
</script>
Thanks in advance
The way your code example is described, it's not possible to reuse that variable. Because it is not bound to the window object, it's bound to the function that is self-executed. It's an example of a "safe" way of libraries not intervening with your own code.
You can however, since I guess by the syntax it's jQuery, hook into the jQuery ajax handling. Based on your requirements, to stop an ajax call, you need to listen to all ajax requests.
You could take a look at the jQuery ajax hooks, https://api.jquery.com/category/ajax/.
You could end up with something like:
$(document).ajaxSend(function(event, xhr, settings){
if (settings.url === "/your/url/to/abort") {
xhr.abort();
}
});
just declare var term above the function declaration
var term
function test1(){
term = 'hello there'
test2()
}
function test2(){
console.log(term)
}
test1()
ok, I managed to solve, basically I created a function only to abort the ajax request like this:
this.abortAjax = () => {
requestHandler.abort();
}
and then accessing it within terminal.js itself using the term object that was instantiated beforehand. After working around the code I was able to keep everything inside the terminal script and not splitted in the two parts, getting something like this:
function ShowLoadingScreen () {
var customElement = $("<div>", {
"class" : "btn btn-danger btn-lg",
"text" : "Abort",
"onclick": "term.abortAjax()"
});
$.LoadingOverlay("show", {
//image : "/static/loading.gif",
background : "rgba(204, 187, 0, 0.8)",
imageAnimation : "rotate_right",
//imageAutoResize : true,
text : "Loading...",
custom : customElement
});
}
function request (command) {
...
requestHandler = $.ajax({
url: _url,
beforeSend: function () { ShowLoadingScreen(); }, // <Show OverLay
type: 'GET',
dataType: 'json',
success: function (response) {
...
},
complete: function () { HideLoadingScreen(); } //<Hide Overlay
}).fail(function (jqXHR, textStatus, error) {
...
});
ShowLoadingScreen();
}
Thanks, everyone.
I am trying to use the beforeSend and complete functions on all ajaxForms in a project. I would like to do this without adding the exact bit a code all throughout the project.
I've been able to accomplish this with the below code on a per form basis.
beforeSend: function() {
$('.lightbox').append('<div id="page-loader" style="display:block"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
},
complete: function(xhr) {
$('.lightbox#page-loader').remove()
},
I'd like to be able to put that code into one place that executes every time an ajaxForm is submitted. Is this possible?
$(function(){
$.ajaxSetup({
beforeSend: function() {
$('.lightbox').append('<div id="page-loader" style="display:block"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
},
complete: function(xhr) {
$('.lightbox#page-loader').remove()
},
});
});
Please use the function ajaxsetup. When you do it this way it will be valid in all ajax functions.
Referrer : https://api.jquery.com/jQuery.ajaxSetup/
If anyone runs across a similar dilemma, this is what I came up with and it seems to do the trick. I haven't found any problems with this thus far.
// add loading masks on form submits
$( document ).ajaxSend(function() {
$('.lightbox').append('<div id="page-loader" style="display:block; z-index: 999"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
});
$(document).ajaxSuccess(function() {
$('#page-loader').remove()
});
I have an MVC page that contains multiple text entries. The controls on the page are all data driven. What I've done, is tag each of the autocomplete inputs with class="ACBox". They all have their own Ids. I have also added a custom attribute called fname, where fname is the field identifer. fname could be "size", "color", "connectionpoints", etc. (could be lots of these)
What I would like to do, is use one autocomplete function to make an ajax call to my controller with the fname of the control passed back to my function to return the appropriate list of possibles.
However, I do not find a way to get a reference to the calling object for autocomplete to read in the fname attribute. My current solution below, the pfield is Nothing when I examine in GetOptionsFromField.
Is there a way to set pfield? Optionally, I could use this.id to set as pfield.
$(".ACBox").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Action("GetOptionsFromField", "ControllerX")",
dataType: "json",
data: {
pfield: $(this).attr("fname")
},
success: function (data) {
response(data);
}
});
},
minlength: 5,
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
Okay, It looks like I needed to search better. This was answered back in 2014, with this question.
I use
$(this.element).data("colname")
and it works like a charm.
My problems seems basic, yet I have tried a lot of different ways of putting these functions on one html file to no avail. The problem is that, when the 1st function is called, the second also runs, leaving me with the results of the second function all the time. I have no idea what I am doing wrong, please help. Here is the code in question.
<script>
$(document).ready(function () { // Make sure the elements are loaded on the page
// Listen for a click event on the button
$('#buttonON').click(funct);
$('#buttonOFF').click(funct2);
});
// Now define the function
function favfunct(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
$.ajax("carstatusupd.php", {
// Pass our data to the server
data: { "username" : "sibusiso", "caron" : "1", "caroff" : "0"},
// Pass using the appropriate method
method: "POST",
// When the request is completed and successful, run this code.
success: function (response) {
// Successfully added to favorites. JS code goes here for this condition.
}
});
function funct2(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
$.ajax("carstatusupd.php", {
// Pass our data to the server
data: { "username" : "sibusiso", "caron" : "0", "caroff" : "1"},
// Pass using the appropriate method
method: "POST",
// When the request is completed and successful, run this code.
success: function (response) {
// Successfully added to favorites. JS code goes here for this condition.
}
});
}
</script>
You have omitted the closing brace from the function favfunct().
Please use this,
<script>
$(document).ready(function () {
function funOne(){
};
function funTwo(){
};
$('#buttonON').live('click',function(){
funOne();
});
$('#buttonOFF').live('click',function(){
funTwo();
});
});
NOte: initialize function before use and initialize them into document ready.
Hello guys here's my code:
var ajax={
chiamata:function(target,url,opzioni){
if (!tools.array_key_exists('caricamento',opzioni)){
opzioni['caricamento']=1;
}
var dati=url.split('?');
$.ajax({
type: opzioni['type'],
url: url,
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
data: dati[1],
dataType: "html",
success: function(msg){
if (opzioni['caricamento']!=0){
ajax.printLoading();
}
$(target).html(msg);
},
error: function(){
alert("Chiamata fallita!");
}
})
},
printLoading:function(){
var body="#colonnaDX";
$(body).ajaxStart(function(){
$(body).append('<div id="loading"><img src="graphic/IMAGE/spinner.gif"/>Loading...</div>');
})
.ajaxStop(function(){
$('#loading').remove();
});
}
},
//Recursive function
var object={
checkAzione:function(target,url,opzioni,interval){
if (!interval)
interval=60000;
ajax.chiamata(target,url,opzioni);
setTimeout(function() {
this.checkAzione(target,url,opzioni,interval);
}, interval);
}
}
$(document).ready(function(){
object.checkAzione(
'#colonnaDX',
'someactions.php',{
'caricamento':0
},
10000
);
})
I'll try to explain the problem as better as i can, When the document is ready, the function "checkAzione" starts and it makes some stuff like DB calls etc, this kinds of ajax calls don't need any visual loading like spinner etc so in the array "opzioni" i set a flag 'caricamento':0 (same of 'loading':0) just check my ajax object to see what i mean, it works until i make some ajax calls that using 'caricamento':1, from that moment every ajax calls in my recursive function makes the "printLoading"... Any tips????
ajaxStart and ajaxStop are global, you add them to the body. You probably shouldn't use ajaxStart/Stop in this case, just add the functionality to your ajax listeners (success and error).