Postback a page based on webmethods result - javascript

How can I post back to a page based on result of WebMethod ?
function AssignmentConditionsSaveAS_Clicked() {
var txtConditionName = $('input[id$="txtConditionName"]').val();
PageMethods.IsExistsSavedCondition(txtConditionName, OnSuccess, OnFailure);
return false;
}
function OnSuccess(result) {
if (result == 'true') {
if (confirm('A saved condition with that name already exists. Do you want to overwrite?')) {
return true;
// I want to post back the clicked button
// Can not use __dopostback, because its a control inside a user control
}
else {
return false;
}
}
else if (result == 'false') {
alert('Not Exist');
}
}
function OnFailure(error) {
alert(error);
}
OR
How can I do somehting like this:
__doPostBack($('input[id$="btnSaveAS"]'), '');

You just have to do this
__doPostBack($('input[id$="btnSaveAS"]').attr('name'), '');

If I understand you correctly, you just need to get the button and call the click() function to do the post back.

Related

How could I stop a form submit in this case?

My intention is to check some conditions before submit is done or stop it and show an alert if the results of that condition are false. I need to ask a function localized in another PHP document using POST.
The next case I'm going to show, the alert is showed correctly when "result != 1", but when I test the opposite case "result == 1", the submit doesnt work:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
}
} else {
alert('error');
return false;
}
});
});
I tried in another way, putting event.preventDefault behind every "Return false" but when "result != 1" it shows the alert but do the submit anyways. It happens in every condition (submit doesnt stop).
$('body').on("submit","#formProyecto",function(event) {
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
event.preventDefault();
}
} else {
alert("error");
event.preventDefault();
return false;
}
});
});
As you can see, my goal is to stop the submit if "result != 1" and show an alert or do the submit if all conditions are ok.
Any idea?
Thanks.
The issue you have is that you cannot return anything from an asynchronous function - which your AJAX request is.
To solve this you need to use preventDefault() to stop the form submit event through jQuery, then raise another native submit event if the AJAX request returns a valid result. This second submit event will not be handled by jQuery and will submit the form as you require. Try this:
$(document).on("submit", "#idForm", function(e) {
e.preventDefault();
var form = this;
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result === 1) {
if (functionNameInSameJSPage()) {
form.submit();
}
} else {
alert('error');
}
});
});
This is assuming that functionNameInSameJSPage() is not an async function. If it is then you'll need to use the callback pattern there too.
This is a bit of a tricky one but you can kind of get it to work by doing:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
$('#idForm').trigger("submit.force"); //Trigger submit again but under a different name
}
} else {
alert('error');
}
});
});
$('body').on("submit.force","#idForm", function () { return true; }); //Passthrough
The idea is to retrigger the event but ensure you don't call the same handler.
There's a proof of concept at https://jsfiddle.net/2kbmcpa4/ (there's no actual ajax happening but the promise simulates that, note this example won't work in IE)
Steps to solve the issue :
On actual form submit just block the event and make the rest call.
Based on response again dynamically resubmit by setting the allowSubmit flag.
Because flag is set on second submit, it doesn't prevent the form from submission. Reset the allowSubmit flag.
(function() {
var allowSubmit = false;
$('body').on("submit", "#idForm", function(event) {
var that = this;
if (!allowSubmit) {
event.preventDefault();
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result == 1) {
if (functionNameInSameJSPage()) {
allowSubmit = true; // set the flag so next submit will not go though this flow
that.submit(); // dynamically trigger submit
}
} else {
alert('error');
}
});
} else {
allowSubmit = false; // reset the flag
}
});
})();

jQuery callback not working properly

I have the following code and the callback doesn't seem to work properly. My understanding is that if the username is undefined or blank then the #username-error div should show and the error class should be added to the get added to the username input. Only once all of that is done should the alert get fired. However, when I look in my browser, the error div does not show, and the alert gets triggered. So clearly the class 'error' is getting added, and therefore it's reasonable to suggest that the #username-error div is having the .show() function called upon it but it sure does't look like it. Any help you can give me getting the alert to fire only once the #username-error div has appeared would be greatly appreciated.
<script type="text/javascript">
$(document).ready(function() {
$("input[name='username']").bind("blur", function() {
validateUsername(myFunction);
});
$("input[type='submit']").bind("click", function() {
validateUsername(myFunction);
});
$("#username-error").hide();
$("#username-success").hide();
});
function myFunction() {
if ($(".error").length > 0) {
alert("errors on page");
return false;
}
}
function validateUsername(callback) {
var $username = $("input[name='username']");
if (typeof $username.val() === "undefined" || $username.val() === "") {
$("#username-error").show();
$("#username-success").hide();
$username.addClass("error");
} else {
$("#username-error").hide();
$("#username-success").show();
$username.removeClass("error");
}
if (callback) {
callback();
}
}
</script>
You need to add a return the button click
$("input[type='submit']").bind("click", function() {
return validateUsername(myFunction);
});
and you should return true
function myFunction() {
if ($(".error").length > 0) {
alert("errors on page");
return false;
}
return true;
}
and add return in the validate method
function validateUsername(callback) {
var $username = $("input[name='username']");
if (typeof $username.val() === "undefined" || $username.val() === "") {
$("#username-error").show();
$("#username-success").hide();
$username.addClass("error");
} else {
$("#username-error").hide();
$("#username-success").show();
$username.removeClass("error");
}
if (callback) {
return callback();
}
}
but the use of the callback in this really does not make much sense.

Disable an input after click and validation occurs

I'm trying to disable an input in a form, but only after validation of fields.
function valJomclAddForm() {
f = document.jomclForm;
document.formvalidator.setHandler('list', function (value) {
return (value != -1);
});
if (document.formvalidator.isValid(f)) {
if(document.getElementById('membership6') === null) {
return false;
}
jQuery('input#submit').val('Publishing...');
jQuery('input#submit').prop('disabled', true);
return true;
} else {
//alert
}
}
but when function gets here:
jQuery('input#submit').prop('disabled', true);
return true;
Function stops, change input value to "Publishing" but doesn't publish, doesn't get the "return true"
Unless I remove jQuery('input#submit').prop('disabled', true);then function return true and publish this...
Why does this not work?
Thanks a lot in advance!

Server click executes before user click on confirmation dialog

I work with ASP.NET
I have some button "Delete" which remove users.
<asp:LinkButton ID="lnkDeleteUser" runat="server" OnClientClick="return ValidateDeleteUser();" OnClick="lnkDeleteUser_Click" CssClass=" btn btn-primary" Text="Delete"></asp:LinkButton>
My ValidateDeleteUser-function looks like :
function ValidateDeleteUser() {
if ($("#hdnNewUserFlag").val() != "Update") {
Dialogs.Alert("Please select user", null, null);
return false;
}
function okCallBack() {
return true;
}
function cancelCallBack() {
return false;
}
if ($("#hdnNewUserFlag").val() == "Update") {
Dialogs.Confirmation("Are you sure you want to Delete this User?", okCallBack, cancelCallBack, null);
}
}
where Dialogs.Confirmation - is my custom confirm-dialog.
var Dialogs = new function() {
var todo = null;
function getConfirmModalDialog(title, textBody) {
// create layout of dialog
return dialog;
};
function getConfirmationtDialog(title, msg, okCallBack, cancelCallBack, callBackObj) {
var ConfirmationDialog = $('#confirm-dialog');
if (ConfirmationDialog.length == 0) {
ConfirmationDialog = getConfirmModalDialog(title, msg);
} else {
$('.modal-title', ConfirmationDialog).html(title);
$('.modal-body', ConfirmationDialog).html(msg);
}
$('.ok-btn', ConfirmationDialog).unbind('click').click(function(e) {
e.preventDefault();
if (typeof okCallBack === "function") {
todo = okCallBack(callBackObj);
}
ConfirmationDialog.modal('hide');
});
$('.cancel-btn', ConfirmationDialog).unbind('click').click(function(e) {
e.preventDefault();
if (typeof cancelCallBack === "function") {
todo = cancelCallBack(callBackObj);
}
ConfirmationDialog.modal('hide');
});
return ConfirmationDialog;
};
this.Confirmation = function (dialogMsg, okCallBack, cancelCallBack, callBackObj) {
var dlg = getConfirmationtDialog('Confirmation', dialogMsg, okCallBack, cancelCallBack, callBackObj);
dlg.modal('show');
};
}
My problem is next : when user clicks on "Delete" Button, confirmation dialog opens and after this server side click executes, before user clicks on confirm-Ok-button.
I guess that what you want to do is make the confirm button on the dialouge dot he postback to the server and not have the link button do the postback to the server.
The problem is that you are not using a return false like this.
if ($("#hdnNewUserFlag").val() == "Update") {
Dialogs.Confirmation("Are you sure you want to Delete this User?", okCallBack, cancelCallBack, null);
return false;
}
On calling Dialogs.Confirmation, the modal gets opened and the buttons get click. But nowhere are you telling your function to wait for the click event. So after executing the JavaScript code, the server-side event will be executed.
Update: You should be returning false to the main function which calls Dialogs.Confirm. That is, ValidateDeleteUser as done above. Otherwise the main function will return true

Checking if an image is present within <ul> tag

I am checking on clicking a button that image is present within an <ul> tag or not. For that I am using this function :
function check_image_exists(){
$('ul#show_uploaded_images').each(function() {
if ($(this).find('img').length) {
return true;
}else{
return false;
}
});
}
Now if I put this thing within the clicking function it is working...
function insert_product(){
$('ul#show_uploaded_images').each(function() {
if ($(this).find('img').length) {
alert("Image found");
}else{
alert("Not found");
}
});
}
But if I separate the two and try to use only the return value to decide my condition then it is not working. :
function check_image_exists(){
$('ul#show_uploaded_images').each(function() {
if ($(this).find('img').length) {
return true;
}else{
return false;
}
});
}
function insert_product(){
var image_exist = check_image_exists();
if(image_exist == false){
alert("not found")
}else{
do the rest.....
}
}
The problem is that you are trying to return a value in an each callback, but that doesn't have any meaning, so the return value just gets swallowed.
There's a much simpler way to do this. Just check whether .find() returns any elements:
var thereAreImages = $('ul#show_uploaded_images').find('img').length !== 0;
Or to package it up in functions:
function check_image_exists() {
return $('ul#show_uploaded_images').find('img').length !== 0;
}
function insert_product() {
if (check_image_exists()) {
// do the rest...
} else {
console.log('not found');
}
}
NOTE: based on you asking 2 function ,
function insert_product() {
var image_exist = check_image_exists();
if (image_exist) {
alert("here")
} else {
alert("not found")
}
}
function check_image_exists() {
return $('ul#show_uploaded_images').has("img").length;
}
insert_product();
NOTE: You can check direcly $('ul#show_uploaded_images').has("img").length

Categories