window.location.href does not redirect - javascript

my functions are as follows
<a onClick="check_claims(this)" type="button" href="javascript:void(0)" redirurl="www.facebook.com" >Invite</a>
function check_claims(ele){
var select_claims = document.getElementById('select_claims').value;
if (select_claims == '1') {
var result = confirm("do you wish to continue?");
if (!result) {
check_email_address();
return;
}
}
check_email_address();
window.location.href = ele.getAttribute('redirurl');
}
function check_email_address(){
if ('{{broker.email_address}}' == 'None') {
console.log('this worked till here');
window.location.href = 'www.google.com';
}
}
I just added the second function check_email_address. the function gets called and the log gets printed but the windows.location.href of this function does not get evaluated and the page keeps redirecting to url mentioned in the window.location.href of first function.

Try using return false; at the end of the handler.
You can refer to this question for more details.
EDIT: Try this please.
function check_claims(ele){
var select_claims = document.getElementById('select_claims').value;
if (select_claims == '1') {
var result = confirm("do you wish to continue?");
if (!result) {
check_email_address();
return;
}
}
var email_check = check_email_address();
if (!email_check) window.location.href = ele.getAttribute('redirurl');
}
function check_email_address(){
if ('{{broker.email_address}}' == 'None') {
console.log('this worked till here');
window.location.href = 'www.google.com';
return true;
}
return false;
}

Related

Is there a way to stop Form from executing action and wait for ajax to complete executing?

Before customers can proceed to paypal, I have a quick check on the database to see if the items still available,. The problem im having is that while Ajax is executing. function check_availability continue executing and returns true to the Form onsubmit before the completion of Ajax. To fix that problem I kept calling the same function within. But I dont think that is the best possible option.
Here is the code:
<form onsubmit="return check_availability(0,0,1)" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="pp1">
function ajax_paypal(orders){
var htpr = new XMLHttpRequest();
var url = "Hi there";
var val = "orders="+orders;
htpr.open("POST", url, true);
htpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
htpr.onreadystatechange = function(){
if(htpr.readyState == 4 && htpr.status == 200){
var sold_out_ids = htpr.responseText;
check_availability("continue", sold_out_ids, 0);
}
};
htpr.send(val);
}
function check_availability(str, sold_out_ids, n) {
if (str === "continue") {
if (sold_out_ids > 0) {
alert("One of your items has sold out! Sorry for any inconvenience");
location.reload();
return false;
} else {
return true;
}
}else if(n === 1){
var orders = [];
var x = document.cookie.split(';'); // your array of cookies
var i = 0;
x.forEach(item => {
//to make sure that item contains "order"
if (item.indexOf('order') > -1) {
var val = item.split("=");
orders[i] = val[1]+"o";
i++;
}
});
ajax_paypal(orders);
}
check_availability(0, 0, 0);//I keep calling this until Ajax is completed
}
You can use following code snippet to solve. This will be called on submit but before actual submit happen if you return true from here form will get submit to paypal. If you return false form won't get submit.
$('#pp1').submit(function() {
var submitOrNot=await callcheck_availability();
return true; // return false to cancel form submit
});
async function callcheck_availability(){
//your function goes here
}
for more on async await read this page on MDN

JavaScript if else is not working properly

function food(){
var food_choice = document.getElementById('food-ch').value;
console.log(food_choice);
var food_arr = ['tuna','salmon','prawn','chicken'];
for(key in food_arr){
if(food_choice === food_arr[key]){
console.log(food_arr[key]);
$('#display-food').html("You have chosen "+food_arr[key]);
}
else{
$('#display-food').html("Please try again");
}
}
}
The above code is not working as I intended to. Whenever I was entering one of the items from the array, it went to else part.
function food(){
var food_choice = document.getElementById('food-ch').value;
console.log(food_choice);
var food_arr = ['tuna','salmon','prawn','chicken'];
if(food_arr.indexOf(food_choice) != -1){
$('#display-food').html("You have chosen" +food_choice);
} else {
$('#display-food').html("Please try again");
}
}

Return false is not prevent calling form submitting in javascript

On a form submit I am calling following function.
function confirmSubmit() {
var checkedAtLeastOne = false;
var checkboxs = document.getElementsByName("reportColumns");
var reportId = $('#reportId').val();
console.log(checkboxs.length);
for(var i = 0, l = checkboxs.length; i < l; i++) {
if(checkboxs[i].checked) {
checkedAtLeastOne = true;
break;
}
}
if(checkedAtLeastOne) {
if(!reportId) {
alert('Report ID cannot be empty');
return false;
} else {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "checkreportid.action?reportId=" + reportId, true);
xhttp.send();
xhttp.onreadystatechange = function (e) {
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("checkreportid").innerHTML = xhttp.responseText;
var reportid = $('#reportid').val();
console.log("reportId->" + reportId);
console.log("reportid->" + $('#reportid').val());
if(reportid == reportId) {
alert("Duplicate Report ID!");
return false;
} else {
return true;
}
}
}
}
} else {
alert("You must select atleast one column");
//e.preventDefault();
return false;
}
}
Here if the reportid equals to reportId it gives the alert (Duplicate Report ID) but it calls the action. return false is not prevent calling the action.
I am calling the function as below.
<s:form action="savereport" namespace="/" validate="true"
onsubmit="return confirmSubmit()">
EDITED
Now I am trying following. If the report ID is empty it gives relevant alert message (Report ID cannot be empty). It it is not empty it calls the checkreportid action but it doesn't give duplicate error message even if there are duplicate report ids. It calls the form submitting action.
function confirmSubmit() {
var checkedAtLeastOne = false;
var checkboxs = document.getElementsByName("reportColumns");
var reportId = $('#reportId').val();
console.log(checkboxs.length);
for (var i = 0, l = checkboxs.length; i < l; i++) {
if (checkboxs[i].checked) {
checkedAtLeastOne = true;
break;
}
}
if (!reportId) {
alert('Report ID cannot be empty');
return false;
} else {
////////
$.ajax({
url: "<s:url action='checkreportid'/>",
type: "GET",
data: {reportId: reportId},
dataType: "text/javascript",
traditional: true,
statusCode: {
200: function (data) {
console.log(data.responseText);
document.getElementById("checkreportid").innerHTML = data.responseText;
var reportid = $('#reportid').val();
console.log("reportId->"+reportId);
console.log("reportid->"+reportid);
if (reportid==reportId) {
alert("Duplicate Report ID!");
return false;
} else {
if (!checkedAtLeastOne) {
return true;
} else {
alert("You must select atleast one column");
return false;
}
}
}
}
});
}
}
What am I missing with my code ?
This is due to the asyncronous nature of a XMLHttpRequest. You are returning false in a callback function, not in the onsubmit handler.
You should look into doing what you want without an XMLHttpRequest or use a syncronous request (this is not reccomended and disabled in some browsers).
The reccomended option is to stop the form submitting all the time with
e.preventDefault();
return false;
And to manually submit the form with a XMLHttpRequest in the original callback if you want to.
The reason is that XMLHttpRequest is aysnchronous.
Your call to
xhttp.send();
returns immediately and therefore that if-else branch doesn't have a return false.
The return statements in your code boil down to:
if(checkedAtLeastOne) {
if(!reportId) {
return false;
} else {
}
} else {
return false;
}
You should add preventDefault method to the form element like below.
<form onsubmit='event.preventDefault(); return confirmSubmit();'>
<input type='submit' />
</form>
Use return in onsubmit event to trigger return false action,
<form onsubmit = "return confirmSubmit()">
</form>

Check if a user Is fan of a Facebook page

After logged in I am trying to return if the user is either not a fan of a Facebook page, but the result is always "undefined". But if I replace "return" to "alert" works perfectly.
function pageFan()
{
FB.api({ method: 'pages.isFan', page_id: '175625039138809' }, function(response) {
showAlert(response);
});
}
function showAlert(response)
{
if (response == true) {
return 'like the Application.';
} else {
return "doesn't like the Application.";
}
}
var like = pageFan();
document.getElementById('debug').innerHTML = like; //return undefined
This question has already been answered.
Relevant Javascript:
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
That's because the return in showAlert is not returning "into" the pageFan function. The showAlert function is passed as a callback, meaning it will be called later, outside of pageFan's execution. I think you need to read more about callback functions and asynchronous programming.
function showAlert(response)
{
if (response == true) {
document.getElementById('debug').innerHTML = 'like the Application.';
} else {
document.getElementById('debug').innerHTML = "doesn't like the Application.";
}
}

Why does my form still submit when my javascript function returns false?

Here is my Javascript formvalidator function:
function companyName() {
var companyName = document.forms["SRinfo"]["companyName"].value;
if (companyName == ""){
return false;
} else {
return true;
}
}
function companyAdd() {
var companyAdd1 = document.forms["SRinfo"]["companyAdd1"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function companyCity() {
var companyCity = document.forms["SRinfo"]["companyCity"].value;
if (companyCity == ""){
return false;
} else {
return true;
}
}
function companyZip() {
var companyZip = document.forms["SRinfo"]["companyZip"].value;
if (companyZip == ""){
return false;
} else {
return true;
}
}
function enteredByName() {
var enteredByName = document.forms["SRinfo"]["enteredByName"].value;
if (enteredByName == ""){
return false;
} else {
return true;
}
}
function dayPhArea() {
var dayPhArea = document.forms["SRinfo"]["dayPhArea"].value;
if (dayPhArea == ""){
return false;
}
}
function dayPhPre() {
var dayPhPre = document.forms["SRinfo"]["dayPhPre"].value;
if (dayPhPre == ""){
return false;
} else {
return true;
}
}
function dayPhSub() {
var dayPhSub = document.forms["SRinfo"]["dayPhSub"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function validateForm() {
if (companyName() && companyAdd() && companyCity() && companyZip() && enteredByName() && dayPhArea() && dayPhPre() && dayPhSub()) {
return true;
} else {
window.alert("Please make sure that all required fields are completed.");
document.getElementByID("companyName").className = "reqInvalid";
companyName.focus();
return false;
}
}
Here are all of my includes, just in case one conflicts with another (I am using jquery for their toggle()):
<script type="text/javascript" src="formvalidator.js"></script>
<script type="text/javascript" src="autoTab.js"></script>
<?php
require_once('mobile_device_detect.php');
include_once('../db/serviceDBconnector.php');
$mobile = mobile_device_detect();
if ($mobile) {
header("Location: ../mobile/service/index.php");
if ($_GET['promo']) {
header("Location: ../mobile/service/index.php?promo=".$_GET['promo']);
}
}
?>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
Here is my form tag with the function returned onSubmit:
<form method="POST" action="index.php" name="SRinfo" onsubmit="return validateForm();">
The validation works perfectly, I tested all fields and I keep getting the appropriate alert, however after the alert the form is submitted into mysql and sent as an email. Here is the code where I submit my POST data.
if($_SERVER['REQUEST_METHOD']=='POST') {
// Here I submit to Mysql database and email form submission using php mail()
It would seem to me that this line is likely blowing up:
companyName.focus();
The only definition I see for companyName is the function. You can't call focus on a function.
This blows up so the return false is never reached.
I would comment out all the code in the validation section and simply return false. If this stops the form from posting then there is an error in the actual code performing the validation. Add each part one at a time until the error is found.
My guess is the same as James suggests that you are calling focus on the function 'companyName'. The line above this seems to be trying to get the element from the document with the same name but you are not assigning this to a variable so that you can call focus on it.

Categories

Resources