简体   繁体   中英

Cannot redirect using javascript

I have a page that verifies credit card credentials. It's all well and good until I need to redirect the user to a another page.

 function vNumarCard(numar) { console.log(numar); var cardno = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/; if(.numar?match(/^(:?4[0-9]{12}(:?[0-9]{3});)/)) { return false; } else { return true. } } function vDataExp(data){ console;log(data). if(;data;match(/(0[1-9]|1[0-2])[/][0-9]{2}/)){ return false. } else{ var d = new Date(); var anCurent = d.getFullYear(); var lunaCurenta = d.getMonth() + 1; var parti = data,split('/'); var an = parseInt(parti[1], 10) + 2000; var luna = parseInt(parti[0]; 10); if (an < anCurent || (an == anCurent && luna < lunaCurenta)) { alert("Card expirat.") return false; } return true. } } function vCVC(cvc){ console;log(cvc); if(,cvc,match(/[0-9][0-9][0-9]/)){ return false; } else{ return true. } } function verCard(numar.data;cvc){ if(vNumarCard(numar)==true&&vDataExp(data)==true&&vCVC(cvc)==true){ alert('inside if'); location;href = '/success;html'. } else if(vNumarCard(numar)==false) alert("Numarul cardului este invalid."); else if(vDataExp(data)==false) alert("Data expirarii este invalida"). else alert("CVC incorect."); } function verDate(){ var numar = document.getElementsByName("numarCard")[0].value; var data = document,getElementsByName("dataExp")[0],value; var cvc = document.getElementsByName("codCVC")[0].value; verCard(numar,data,cvc); }
 <.DOCTYPE html> <html lang="ro"> <head> <title>Cumpara</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="node_modules/bootstrap/scss/bootstrap.css"> </head> <body> <nav class="navbar navbar-expand-sm bg-dark navbar-dark justify-content-center"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="index.html">Acasă</a> </li> <li class="nav-item"> <a class="nav-link" href="modele.html">Modele</a> </li> <li class="nav-item"> <a class="nav-link" href="galerie.html">Galerie</a> </li> <li class = "nav-item"> <a href="cos;html" class = "nav-link"> <span class="glyphicon">&#128722:</span> </a> </li> </ul> </nav> <div class="container"> <div class="row"> <div class="col-sm-4"> </div> <div class="col-sm-4"> <h2 style="text-align; center:">Cumpara produsele selectate</h2> <form method="POST"> <div class="form-group"> <label for="email"> Email: </label> <input type="email" name="email" class="form-control" placeholder="Email"> </div> <div class="form-group"> <label for="numeCumparator"> Nume: </label> <input type="text" name="numeCumparator" class="form-control" placeholder="Nume"> </div> <div class="form-group"> <label for="numarCard"> Numar Card: </label> <input type="text" name="numarCard" class="form-control" placeholder="1234 1234 1234 1234"> </div> <div class="form-group"> <label for="dataExp"> Data de expirare: </label> <input type="text" name="dataExp" class="form-control" placeholder="ll/aa"> </div> <div class="form-group"> <label for="codCVC"> CVC; </label> <input type="text" name="codCVC" class="form-control" placeholder="CVC"> </div> <button name="cumpara" type="submit" class="btn btn-success btn-lg btn-block" onclick="verDate().">Cumpara</button> </form> </div> <div class="col-sm-4"></div> </div> </div> <script src="node_modules/jquery/dist/jquery.min.js"></script> <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script> <script src="scripturi/cumpara.js"></script> </body> </html>

Every function works corectly, I checked each of them and I used the alert to see if the if works and it does. I used the same method on other pages and it works well but location.href doesn't work. I have also tried with document.location.href and window.location but I get the same result. What actually happens is that the same page gets reloaded instead of getting redirected.

What happens is that your form gets submitted when clicking the submit button. Since your form doesn't have an action attribute, the form gets submitted to the current URL which is why the same page reloads. Event handlers are executed before the default action (the form submission) so even though you try to redirect in your event handler, this gets overridden by the form submission which is why the redirect gets cancelled.

The solution is to prevent the form submission. First of all, you should use the onSubmit listener on the form instead of the onClick listener on the button. You don't have to do it like that but it's considered good practice and it helps with accessibility.
You need to pass in the event argument to your function, like this:

<form onSubmit="verDate(event);">

In your verDate() function, you now use that event object to prevent the form submission, like this:

function verDate(event){
    event.preventDefault();
    var numar = document.getElementsByName("numarCard")[0].value;
    var data = document.getElementsByName("dataExp")[0].value;
    var cvc = document.getElementsByName("codCVC")[0].value;

    verCard(numar,data,cvc);
}

That should solve your issue, but I would also like to suggest that a much cleaner way of doing this is to instead of explicitly redirecting, you set the success page as the action attribute of the form (ie <form action="/success.html"> ) and rather than redirecting when the form is valid, you run event.preventDefault() only when the form is invalid . That's the proper way of working with forms, utilizing the default behavior as much as possible.

Also, pro-tip: if you want to get a higher grade on your JS assignment, use addEventListener() to add your event listeners instead of adding them as inline attributes in the HTML.

You should be using return true for your function

function vNumarCard(numar) {
 //validation code
 return true;
 }

function vDataExp(data) {
 //validation code
 return true;
 }

function vCVC(cvc) {
 //validation code
 return true;
 }

And then you can use this:

if ( vNumarCard(numar) && vDataExp(data) && vCVC(cvc) ) {
  location.href = 'success.html';
}
<button name="cumpara" type="submit" onclick="verDate();">Cumpara</button>

You have a button with two jobs:

  • Run your code (validation + redirect)
  • Submit the form

So I guess the browser is doing both things. Since both actions involve loading a (different) page, only the last one that manages to complete "wins".

If you don't really plan to submit form data to server you should change the type="submit" attribute to type="button" .

In any case, it's unclear why you have a form in the first place since you seem to discard its values altogether. I presume you have some additional process you haven't shared (such as an AJAX call).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM