Terminating or halting based on value from ajax - javascript

I have a php script with a an image that when you click on it you are redirected to another page.
I also have an ajax / jquery check to see if you are logged in or not.
So, when someone clicks on the link, ajax finds out if they are logged in, and if not they get an alert box.
My link has the id='newlisting'
$("#newlisting").click( function() {
$.post("ajaxqueries.php", {"checkloggedin": ''}, function(data) {
var loggedin = data;
if ( loggedin == 0 ) {
alert('Please login or register to use this feature');
}
});
});
The problem is that when they click on on the alert box, it continues to the screen as if you were logged in.
I need the php script to exit if they get the alert box and hit ok.
Any help would be appreciated.

You need to prevent the redirect.
$("#newlisting").click( function( event ) {
event.preventDefault();
$.post("ajaxqueries.php", {"checkloggedin": ''}, function(data) {
var loggedin = data;
if ( loggedin == 0 ) {
alert('Please login or register to use this feature');
}else{
// Redirect code goes here.
}
});
});

Related

jQueryUI Autocomplete Returning AJAX Error 0 when user hits enter

I have a search box which is using the jqueryUI .autocomplete to get data via AJAX to give suggestions. The problem is that when a user hits enter before the autocomplete AJAX call to the source is done an error pops up in an alert box. "AJAX Error 0"
I assume when the user hits "Enter" when in the search box the browser is automatically stopping the AJAX call which resulting in a bad AJAX response which is triggering jqueryui to pop an error. Is there anyway to make this not happen? Here is some of the sample code of the autocomplete:
$("#searchBar_searchAll").on("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active ) {
event.preventDefault();
}
}).autocomplete({
source: function(request, response) {
$.getJSON('<?php echo CController::createUrl("inventory/searchAutocomplete"); ?>', {
searchString: extractLast(request.term),
searchScopeRecord: $("#searchScope_recordScope option:selected").val(),
searchScopeActive: $("#searchScope_activeScope option:selected").val(),
searchOptions: $("#searchBar_searchoption_searchAll option:selected").val()
}, response);
},
search: function() {
var searchString = extractLast(this.value);
if (searchString.length < 3)
return false;
},
focus: function() {
return false;
},
select: function(event, ui) {
window.location.href = '<?php echo CController::createUrl("inventory/update"); ?>' + '&id=' + ui.item.value;
return false;
}
});
Edit: The problem only happens sometimes upon further testing and it seems to happen almost every time on a slower machine. It seems related to how fast the machine executes the Javascript.
It seems that the AJAX error 0 occurs because when the user submits the search it cancels the AJAX request. It seems like when this is cancelled jquery-ui's .autocomplete is likely triggering an error pop-up due to getting no data. Is there anyway I could cleanly cancel the AJAX request then when someone hits enter or the submit button so that such an AJAX error does not occur?
Hi I think you are looking for enter search functionality.
you just need this property
$("#searchBar_searchAll").autocomplete({ autoFocus: true });
I didn't have your php api code so i put a sample array source for my autocomplete.
here is working example
another example with ajax source. but its already mentioned atleast we need to wait while ajax request should complete and return with results.
here is another example with ajax source.
The browser submits the form by default if you hit enter. While the ajax-request needs time (if not delivered from browser-cache), the browser-form-submit fires immediately and breaks your running ajax-request. As result you see those ajax error.
Maybe you can set a helper-variable if you press Enter and skip the JSON-function, if this var is true.
var bEnterPressed = false;
$("#searchBar_searchAll").on("keydown", function(event) {
var iKey = event.keyCode || event.which; // event.which is for old IE compatibility
bEnterPressed = false;
if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active ) {
event.preventDefault();
}
// Detect Enter = key 37
if( iKey === 37 ) {
bEnterPressed = true;
}
}).autocomplete({
source: function(request, response) {
if( bEnterPressed ) { return false; } // skip ajax-request, if Enter was pressed
try {
$.getJSON('<?php echo CController::createUrl("inventory/searchAutocomplete"); ?>', {
searchString: extractLast(request.term),
searchScopeRecord: $("#searchScope_recordScope option:selected").val(),
searchScopeActive: $("#searchScope_activeScope option:selected").val(),
searchOptions: $("#searchBar_searchoption_searchAll option:selected").val()
}, response);
} catch(e) {
// ignore ajax-errors
}
},
// ...
});

On using "confirm('message')" in JavaScript, making the browser navigation buttons disabled

I have a situation where in, when the user clicks the "back" button, I have to prompt for a "confirm" on a page using JavaScript. The result would decide whether to stay on the page or not.
I have used, the following:
window.onbeforeunload = function () {
var answer = return confirm("Please note by clicking the back button will reset your selection")
if (!answer) {
event.preventDefault();
}
else{
// do something
}
};
Now, even if this prompts a popup on the page, the back button can still be clicked taking the user to the previous page.
On the other hand, by using the following.
window.onbeforeunload = () => {return '';}
I get the message "Changes you made may not be saved.", with the prevention of "back", "forward", "refresh" and all such buttons on the page.
I want this same thing (the prevention of these buttons), to happen on "confirm('message')".
function Confirm_something() {
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
return confirm("Text you want?");
}
if(Confirm_something){
console.log('user say yes'); //then call your save edit or delete functions.
}
else{
console.log('user say no');
}

Jquery submit form then redirect not working

I have found so many posts about this but I can't get this to work for the life of me. On submit of the form, I need the code to 1) submit the form and 2) redirect to one of the locations inside the case statements. I can get the form to submit without the cases and I can get the form to redirect, but I can't get it to do both. Please tell me I am on the right track but just have code in the wrong spot, I have been staring at this way too long and have hit a roadblock.
$("#submitBtn").click(function (event) {
event.preventDefault();
var validator = $(this).closest("form").kendoValidator({
messages: {
required: function (input) { return getRequiredValidationMessage(input) },
custom: function (input) { return getInvalidValidationMessage(input) },
},
rules: {
custom: function (input) {
var minlength = $(input).attr('data-minlength');
var required = $(input).attr('required');
if (typeof minlength !== typeof undefined && minlength !== false && ((typeof required !== typeof undefined && required !== false) || $(input).val().length > 0)) {
var minlength = $(input).data('minlength');
return $(input).val().length >= minlength;
} else {
return true;
}
}
}
}).data("kendoValidator");
if (validator !== undefined) {
if (validator.validate()) {
$("aspnetForm").submit();
if ($("aspnetForm").submit()){
switch(document.getElementById('interests').value){
case "stair-lifts":
window.location.href="/Catalog/Online-Catalog-Category/15522/Stair-Lifts";
break;
case "wheelchair-ramps":
window.location.href="/Catalog/Online-Catalog-Category/15521/Ramps";
break;
case "roll-in-barrier-free-showers":
window.location.href="/Catalog/Online-Catalog-Category/15529/Bathroom-Safety";
break;
case "walk-in-tubs":
window.location.href="/Catalog/Online-Catalog-Category/15529/Bathroom-Safety";
break;
case "patient-lifts-ceiling-lifts":
window.location.href="/Catalog/Online-Catalog-Category/15523/Patient-Lift";
break;
case "wheelchair-lifts":
window.location.href="/Catalog/Online-Catalog-Category/15525/Wheelchair--Scooter-Lifts";
break;
default:
window.location.href="/"; // if no selection matches then redirected to home page
break;
}// end of switch
}
} else {
$('.k-invalid:first').focus();
$('.k-invalid').blur(function () { if (this.checkValidity()) { $('.k-invalid:first').focus(); } });
}
} else {
$(this).closest("form").submit();
}
});
});
You shouldn't be using .submit() for this. Since you're using JQuery, you should use an AJAX request, formatted something like this:
$("#submitBtn").click(function (event) {
$.ajax({
url : "/your/url", // Whatever URL you're submitting to goes here
type : "post",
data : yourData, // Whatever data you're sending goes here
success : function(data) {
// Whatever you want to do on success goes here
}
});
});
You make the switch in URL part of the function the AJAX query executes on success.
The form submission and the page redirect are clashing because in a basic web page, only one of these can occur. When the form submits, it will send the form data via the desired method to the server - typically a GET or a POST.
Conversely, when that redirect switch statement runs, it will tell the browser to change the page url.
Both of these events will trigger a page change within the browser, but only one can truly happen.
What would help you the most is to submit the form data via an AJAX request and then on completion call the redirect code.
As it looks like you are already using jQuery, check out the post method here.

alert box disappear without clicking on ok button in asp.net

I am making in which I want to display alert box and then redirect it to some other page in asp.net
My code is
var s = Convert.ToInt32(Session["id"].ToString());
var q = (from p in db.students
where p.userid == s
select p.sid).SingleOrDefault();
if (q == 0)
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "reg();", true);
}
this is my reg() function
function reg() {
var con = alert('Please Register Your Self Fisrt ..!! Thank you');
window.location = "reg.aspx";
}
My code is working fine but alert box gets disappear after some second without clicking on it because of that user is unable to read alert message
I want to redirect it to reg.aspx but after clicking OK on alert box ..
please help
Firing a confirm box instead of alert will do what you are trying to achieve. You will have the option to redirect conditionally or unconditionally
function reg(){
var con=confirm("You need to register first before proceeding. Redirect to Registration Page");
if(con==true){
window.location = "reg.aspx";
}
else{
//if redirect unconditionally
window.location = "reg.aspx";
}
}

Alternative for keyup function

am working in a popup when we click login a popup opens with fields !!! i want to check username and password with database before login button fired.. used ajax with keyup function for password field!
but keyup is firing for every character typed in password field... but the requirement is after typing password field ajax should be called and result should be displayed... is there any alternative for keyup?
now am getting as "wrong password for every character typed" and after entring correct password it will login,... but i want to show error as wrong password when user completely enters password (if password is wrong)
<script type="text/javascript">
$(document).ready(function() {
$("#upwd").change(function()
//$('#upwd').on('input', function()
//$('#upwd').keyup(_.debounce(doSomething , 500), function() {
var upwd = $("#upwd").val();
var uemail = $("#uemail").val();
var msgbox = $("#status");
//alert(uemail);
//alert(upwd);
//setTimeout(function() {
//if($('#upwd').val() == upwd){
$.ajax({
type: "POST",
url: "checkl_login.php",
data: "uemail="+ uemail,
success: function(msg){
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK') {
msgbox.html(msg);
//return false;
} else {
msgbox.html(msg);
}
});
}
});
return false;
});
});
</script>
error displayed in status id in span......
checkl_login.php code is aalso perfect.....
Try using .focusout() event as shown :-
$("#upwd").on("focusout",function(){
//..your code..
});
and in addition of these events ,use a login button also and check validations on the click of the button.
Use the change event instead of keyup.
IMHO it's better:
to use keyup (it allows to handle any keyboard changes. For example, removing the symbol by backspace)
to handle 'paste' (because user may copy/paste password but not type it)
to validate password if user does not press a key during some period of time (for example, within 1 second) - setTimeout and clearTimeout should help
to abort ajax request if user starts to type when ajax request is in progress
I.e. you may try something like the following:
$(document).ready( function() {
var ajax_h;
var delayMilliseconds = 1000; // i.e. = 1 second
var timeoutId;
function checkAuth() {
if (ajax_h) {
ajax_h.abort();
}
ajax_h = $.ajax(
// PUT YOUR CODE HERE
);
}
$("#upwd").on('keyup paste', function () {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(checkAuth, delayMilliseconds);
});
});

Categories

Resources