0

I was creating a HTML form in which I was doing both client side and server side validation.I used the below code.

<form action='logic.php' method='post' id='login'>
    <input type='text' placeholder='Enter name' name='name'>
    <input type='submit'>
</form>

// Jquery
$(document).ready(function(){

    function validate_name(input_id,error_id,msg="Name"){
        const x = document.getElementById(input_id).value;
        const y = document.getElementById(error_id);
        const pattern = /^[a-zA-Z]+$/
        if(x!==""){
            if(pattern.test(x) ){
                if(x.length<3 || x.length>10){
                    y.innerHTML = msg+' should be between 3 and 10 characters.'
                    return false;
                }
                else{
                    y.innerHTML = '';
                    return true;
                }
            }
            else{
                y.innerHTML = 'Should contain only alphabets.'
                return false;
            }
        }
        else{
            y.innerHTML = "Please Enter Your "+msg;
            return false;
        }
    }


    $('#login').submit(function(e){
        e.preventDefault();
        let name = validate_name('rollno','rerror');
        let subject_name = validate_select('subject_dropdown','serror');
        if(name === true & subject_name === true){
            window.location = 'controller/indexPage_logic.php';
        }
    })
});

I may able to do client side validation but if the form is properly validated I can't able to access the input value using $_POST['name'] in server side PHP.I think this is due to window.location.Is there any better way to do both side validation?

Vijay
  • 116
  • 1
  • 7

3 Answers3

1

Set the correct file in your action parameter in the form.

And inside the if condition, write e.currentTarget.submit();

if(name === true & subject_name === true){
    e.currentTarget.submit();
}
mustafaj
  • 305
  • 1
  • 12
0

Your location change does a GET when you need a POST

Change to

$('#login').submit(function(e){
    e.preventDefault();
    let name = validate_name('rollno','rerror');
    let subject_name = validate_select('subject_dropdown','serror');
    if(name === true & subject_name === true){
        $.post('controller/indexPage_logic.php', {name:rollno}, function(response) { console.log(response)}); // do what you need to do when valid on the server too
    }
})
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You have to send your data to the server, the probleme was window.location didn't sent any request to the server to be able to accomplice that use

$.post('url to the server', { data1 : "Your data", data2 : yourvar }, function(res) {
   console.log(res)
});
medmik
  • 1