I have a series of buttons that execute different functions when clicked. The function checks whether the user is logged in, and if so proceeds, if not it displays an overlay with ability to log in/create account.
What I want to do is re-execute the button click after log-in, without the user having to reclick it.
I have it working at the moment, but I'm pretty sure that what I'm doing isn't best practice, so looking for advice on how I can improve...
Here's what I'm doing: setting a global variable "pending_request" that stores the function to be re-run and in the success part of the log-in ajax request calling "eval(pending_request)"
Example of one of the buttons:
jQuery('#maybe_button').click(function() {
pending_request = "jQuery('#maybe_button').click()"
var loggedin = get_login_status();
if (loggedin == true) {
rec_status("maybe");
}
});
.
success: function(data) {
if(data === "User not found"){
alert("Email or Password incorrect, please try again");
}else{
document.getElementById('loginscreen').style.display = 'none';
document.getElementById('locationover').style.display = 'none';
eval(pending_request);
pending_request = "";
}
}
Register a function to handle the click and then invoke that func directly without eval().
jQuery('#maybe_button').on('click', myFunction)
This executes myFunction when the button is clicked. Now you can "re-run" the function code every time you need it with myFunction().
And btw since you are using jQuery you can do $('#loginscreen').hide() where $ is an alias for jQuery that's auto defined.
EDIT
Please, take a look at the following code:
var pressedButton = null;
$('button1').on('click', function() {
if (!isLoggedIn()) {
pressedButton = $(this);
return;
}
// ...
});
And, in your success handler:
success: function() {
// ...
if (pressedButton) pressedButton.trigger('click');
// ...
}
Related
I have the following code. There is a button in the UI that when clicked executes the if statement. I pass in a URL from a database and compare it to the current URL the user is on. If they match I want to run the code below, else I want to open the correct tab then run the code below.
With this code below I mean everything below starting from $('#sceanrioDropdownList').change(function () {...}. The code then checks a drop down and gets the selected Id from which an AJAX call is made to my web API that uses that Id in a stored procedure to return the results. The returned data is then iterated over and stored in variables which I am using to append to specific inputs, buttons and drop downs.
This is what I have so far and I think I have developed this correctly. The issue that I am currently having is that the UI wants everything from ... to be run if the if statement is true. I have tried CTRL+C and CTRL+V to copy the code into the if statement. I have also tried putting it in a new function and referencing that function n the if statement. Both do not work and I was using console.log to inspect the returned data.
It does however when I attempt to call it from inside i statement it doesn't return any data or error. It just doesn't seem to fire.
Is there a way in which I can achieve the functionality I desire? Do you have any suggestions as to if I have done something wrong. Thanks in advance.
$('#automate').click(automateButton);
function automateButton() {
if (webpageUrl == activeTabUrl) {
// do nothing
} else {
// Window opens
window.open(webpageUrl);
}
}
$('#scenarioDropdownList').change(function() {
var scenarioId = $('#scenarioDropdownList option:selected').prop('id');
getData(scenarioId);
});
function getData(scenarioId) {
$.ajax({
type: "GET",
url: 'http://localhost:54442/api/scenariodatas/GetScenarioData',
data: {
scenarioId: scenarioId
},
dataType: 'JSON',
success: scenarioData,
error: function() {
console.log("There has been an error retrieving the data");
}
});
}
function scenarioData(response) {
$.each(response, function(key, val) {
var fieldType = val.fieldType;
var fieldName = val.fieldName;
var fieldValue = val.fieldValue;
var field = $(fieldName);
if (field != undefined) {
switch (fieldType) {
case "Input":
$(field).val(fieldValue);
break;
case "Button":
$(field).click();
break;
case "Select":
$(field).val(fieldValue);
break;
}
}
})
}
onChange don´t work well with buttons because onChange detect a change in the value of your component, because of this, it´s highly recommended to use onClick when you use a button.
$('#scenarioDropdownList').click(function() {
var scenarioId = $('#scenarioDropdownList option:selected').prop('id');
getData(scenarioId);
});
I recommend you to put alerts when you are trying to test this sort of JS
EJM:
$('#scenarioDropdownList').change(function() {
alert('button active');
var scenarioId = $('#scenarioDropdownList option:selected').prop('id');
getData(scenarioId);
});
this alert allow you to know if the code is firing or not
EDIT: Found an un-elegant solution here:
How do I close a modal window after AJAX success
using location.reload(), though I have to say that I think there is a bug in the modal handling in jquery. I do not think my code below was wrong yet it doesn't work. :(
When a user clicks a button it calls a method :
onClick(GroupInformationDialog(true)) ... etc
So that calls a method to see if we should hide or open a modal first based on what is passed and second based on what the result of another method that does an ajax call has:
function GroupInformationDialog(open) {
if (open) {
if (GetProviderInfo() == true) {
$("#groupinfo-dialog").modal("show");
} else {
// we got no real data so let's not show the modal at all
$("#groupinfo-dialog").modal("hide");
}
} else {
$("groupinfo-dialog").modal("hide");
}
return false;
}
and the ajax call:
function GetProviderInfo() {
event.preventDefault();
gid = $('#group_info option:selected').val()
pid = $("#provider_id").val()
$.ajax({
url: '{% url 'ipaswdb: get_group_info_data' %}',
data: "group_id=" + gid + "&prov_id=" + pid,
success: function (resp) {
if (resp['response'] == 'NOGROUP') {
alert("You must first select a group");
$("groupinfo-dialog").modal('hide'); //arg this doesn't work either
return false;
}
else if (resp['response'] == 'OK') {
//fill out form with data.
$("#gi_date_joined_group").val(resp['date_joined_group']);// = resp['credentialing_contact'];
$("#gi_provider_contact").val(resp['provider_contact']);
$("#gi_credentialing_contact").val(resp['credentialing_contact']);
return true;
}
else {
$("#gi_date_joined_group").val('');// = resp['credentialing_contact'];
$("#gi_provider_contact").val('');
$("#gi_credentialing_contact").val('');
return true;
}
}
});
}
The problem is, the return true, or false in GetProviderInfo() is ignored, it is like GroupInformationDialog is evaluated all the way before GetProviderInfo is, so the result is a modal dialog that always pops up.
I even tried to have the
$("#groupinfo-dialog").modal('hide');
in the if(resp['response']=='NOGROUP') code section, with no dice.
It is almost like I need a wait function, I thought success was a call back function was going to take care of it, but alas it did not.
You're mixing synchronous and async code here; you can't synchronously use if (GetProviderInfo() == true) since what you want to return from that function depends on an asynchronous ajax call.
The return statements you currenty have will go to the success handler they're contained within; they will not set the return value for getProviderInfo itself. By the time that success handler runs, getProviderInfo has already returned.
You could have that function return a promise (using return $.ajax({...})) and have the caller handle the results asynchronously -- but it looks like in this case it might be simpler to just hide / show the modal from within the ajax call's success handler. (It looks like the sole reason that isn't working currently is just a typo: there are a couple spots where you have $("groupinfo-dialog") when you mean $("#groupinfo-dialog")
Here's the problem. I'm making a callback to the server that receives an MVC partial page. It's been working great, it calls the success function and all that. However, I'm calling a function after which iterates through specific elements:
$(".tool-fields.in div.collapse, .common-fields div.collapse").each(...)
Inside this, I'm checking for a specific attribute (custom one using data-) which is also working great; however; the iterator never finishes. No error messages are given, the program doesn't hold up. It just quits.
Here's the function with the iterator
function HideShow() {
$(".tool-fields.in div.collapse, .common-fields div.collapse").each(function () {
if (IsDataYesNoHide(this)) {
$(this).collapse("show");
}
else
$(this).collapse("hide");
});
alert("test");
}
Here's the function called in that, "IsDataYesNoHide":
function IsDataYesNoHide(element) {
var $element = $(element);
var datayesnohide = $element.attr("data-yes-no-hide");
if (datayesnohide !== undefined) {
var array = datayesnohide.split(";");
var returnAnswer = true;
for (var i in array) {
var answer = array[i].split("=")[1];
returnAnswer = returnAnswer && (answer.toLowerCase() === "true");
}
return returnAnswer;
}
else {
return false;
}
}
This is the way the attribute appears
data-yes-no-hide="pKanban_Val=true;pTwoBoxSystem_Val=true;"
EDIT: Per request, here is the jquery $.post
$.post(path + conPath + '/GrabDetails', $.param({ data: dataArr }, true), function (data) {
ToggleLoader(false); //Page load finished so the spinner should stop
if (data !== "") { //if we got anything back of if there wasn't a ghost record
$container.find(".container").first().append(data); //add the content
var $changes = $("#Changes"); //grab the changes
var $details = $("#details"); //grab the current
SplitPage($container, $details, $changes); //Just CSS changes
MoveApproveReject($changes); //Moves buttons to the left of the screen
MarkAsDifferent($changes, $details) //Adds the data- attribute and colors differences
}
else {
$(".Details .modal-content").removeClass("extra-wide"); //Normal page
$(".Details input[type=radio]").each(function () {
CheckOptionalFields(this);
});
}
HideShow(); //Hide or show fields by business logic
});
For a while, I thought the jquery collapse was breaking, but putting the simple alert('test') showed me what was happening. It just was never finishing.
Are there specific lengths of time a callback function can be called from a jquery postback? I'm loading everything in modal views which would indicate "oh maybe jquery is included twice", but I've already had that problem for other things and have made sure that it only ever includes once. As in the include is only once in the entire app and the layout is only applied to the main page.
I'm open to any possibilities.
Thanks!
~Brandon
Found the problem. I had a variable that was sometimes being set as undefined cause it to silently crash. I have no idea why there was no error message.
I have a jQuery form-submission routine that has an input integrity check in ERROR_CHECK.PHP that relies on GET variables passed to it for inspection. If the values passed to it are malformed, then an alert box appears that explains the error and how the form data should be remedied. This alert box will need to pop up until the form data is no longer malformed, at which point that data is used for repopulating data on the page.
Thus, in the jQuery routine I'm at the mercy of our friend preventDefault(), and I have found a solution that does work, but not elegantly. The variable allowSubmit is initialized as FALSE and remains that way—with preventDefault() also in effect—until the form data passes the integrity check, at which point allowSubmit switches to TRUE...but that only happens with the submission of the correctly-formed input data. This means the user must submit the form a SECOND TIME in order for the form data to be used to replace data on the page...and that, of course, is not a solution (press the submit button twice?)
However, by dynamically submitting the form (here, with the $('#my_form').submit() statement) immediately after resetting allowSubmit to TRUE, I've submitted the form again, thereby allowing the user to submit correctly-formatted data ONCE, as it should be from the get-go.
This is obviously a band-aid solution and not elegant. Can anyone see a more elegant way to structure this? (I'm working with jQuery fashioned by another developer, and this occurs in the midst of a longer self-calling JQuery function, and I have to work with it on its own terms, lest I have to refashion all other parts of the larger function in which it occurs.
Here's a distillation of the code (with self-describing variables, etc.), which works as described, although not as elegantly as I'd like:
var allowSubmit = false;
$('#my_form').on('submit', function(e) {
if (!allowSubmit) {
e.preventDefault();
// Check to see if input data is malformed:
$.get('error_check.php', { new_element_name: $('#new_element_name').val() }, function(data) {
if (data != 0) {
alert("An Error Message that explains what's wrong with the form data");
} else {
allowSubmit = true;
// The line below--an auto-submit--is needed so we don't have to press the submit button TWICE.
// The variable allowSubmit is set to TRUE whenever the submitted form data is good,
// but the code suppressed by e.preventDefault() won't execute until the form is
// submitted a second time...hence the need for this programmatic form submission here.
// This allows the user to correct the errant form data, press the submit button ONCE and continue.
$('#my_form').submit();
}
});
}
$('#element_name').val($('#new_element_name').val());
});
What you are doing is okay, your other options might be to write a click handler for a generic button and submit the form through that event after validation, then you wont need to preventDefault as you won't be preventing any kind of submit action. Another solution might be to re-trigger the event after validation.
$("button").click(function() {
$("#my_form").submit();
});
...
allowSubmit = true;
// alternatively
jQuery( "body" ).trigger( e );
...
The callback solution you have doesn't seem unreasonable. I agree with #scott-g that a generic button click event handler would probably be your best bet. A more testable way to write what you have here may be:
var formView = {
$el: $('#my_form'),
$field: $('#element_name'),
$newField: $('#new_element_name'),
$submitBtn: $('#btn-submit')
}
var handleSubmit = function() {
var formData = formView.$field.val();
remoteVerify(formData)
.done(formView.$el.submit)
.done(updateForm)
.fail(handleVerificationError);
};
var remoteVerify = function(formData) {
var deferred = $.Deferred();
var url = 'error_check.php';
var data = { new_element_name: formData };
$.get(url, data)
.done(handleRequest(deferred))
.fail(handleRequestErr);
return deferred;
};
var handleRequest = function(deferred) {
return function (data, jqxhr) {
if (data != 0) {
deferred.reject(jqxhr, "An Error Message that explains what's wrong with the form data");
} else {
deferred.resolve(data);
}
}
};
var handleRequestErr = function() {
// error handling
}
var updateForm = function () {
formView.$field.val(formView.$newField.val());
}
var handleVerificationError = function (jqxhr, errMsg){
alert(errMsg);
}
formView.$submitBtn.on('click', handleSubmit)
You could try using an async: false setting using $.ajax (I don't know what your php is returning, so I am just "pretending" it's a json array/string like so echo json_encode(array("response"=>$trueorfalse));):
<script>
$('#my_form').on('submit', function(e) {
var valid_is = true;
// Check to see if input data is malformed:
$.ajax({
async: false,
url: 'error_check.php',
type: 'get',
data: { new_element_name: $('#new_element_name').val() },
success: function(response) {
var Valid = JSON.parse(response);
if(Valid.response != true) {
alert("An Error Message that explains what's wrong with the form data");
valid_is = false;
}
}
});
if(!valid_is)
e.preventDefault();
$('#element_name').val($('#new_element_name').val());
});
</script>
If you use async: false it runs the script in order and waits to execute the rest of the script until after it receives a response. Scott G. says you can do it with what you have with some slight modifications so I would try that first.
I have an ajax call in my javascript that returns and loads a partial view into a div. This function used to work but then all the sudden it stopped. I do not think I changed any code or anything that would cause issue but obviously something is going on. The Ajax call will work on the first time when you click on the button in which it is called but never again until you reload the page. I have tried adding more parameters and moving the javascript around but it still did not work. Is there any reason why this could happen?
I have tried moving the javascript out of the onOpen event and the same thing still happens. I have also put an alert call to make sure it is getting to the success call and the alert is called. I have also installed fiddler to check the call and the call is never made except on the first click of the button. This is a very frustrating error and all help is much appreciated.
Here is my Javascript:
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#assets-button").on("click", function ()
{
$('#assets-container').bPopup(
{
modal: true,
onOpen: function () {
$.ajax({
type: 'GET',
url: '#Url.Action("EmployeeAssets", "Employee",new { id = Model.ID, empNo = Model.EmployeeNumber, username = Model.UserName })',
success: function (data) {
$('#assets-container').html(data);
}
});
},
onClose: function () {
var f = $('#assets-container').children('form');
var serializedForm = f.serialize();
var action = '#Url.Action("EmployeeAssets","Employee",new {empNo = Model.EmployeeNumber})';
$.post(action, serializedForm);
}
});
});
});
</script>
}
Here is the action that I am trying to call:
[HttpGet]
public ActionResult EmployeeAssets(int id, int empNo, string username = null)
{
var assets = _employeeDb.EmployeeAssets.FirstOrDefault(e => e.EmpNo == empNo);
if (assets == null)
{
var firstOrDefault = _employeeDb.EmployeeMasters.FirstOrDefault(e => e.EmployeeNumber == empNo);
if (firstOrDefault != null)
{
username = firstOrDefault.UserName;
}
var newasset = new EmployeeAsset()
{
EmpNo = empNo,
UserName = username
};
_employeeDb.EmployeeAssets.Add(newasset);
_employeeDb.SaveChanges();
assets = newasset;
}
return PartialView(assets);
}
You may try using the cache property of the settings object you are passing to the AJAX call. According to the jQuery documentation for .ajax the default for cache is set to true, so I wonder whether your browser is accessing a cached copy of the result after the first request. Looks like you could also set the dataType, and that will default the cache back to false.
Also, I would suggest putting your alert inside of the onOpen event handler in addition to the success handler just to be sure that's also being called. So that may help you debug a bit further.