简体   繁体   中英

prevent empty input from returning undefind and instead return an empty string

As the title suggests, i have a registration form, and since i know that javascript can be disabled, i decided to check for empty inputs in my server sided php, but all empty inputs return undefined as the string, instead of just an empty string, is there anyway ( in PHP ) i can prevent it from returning or make sure that the value is known to be empty ? (the user could still pick a name or username that is undefined ) The Javascript Function:

var lnk = 'register.php?n=' + $('#fname').value + '&f=' + $('#pnumb').value + '&m=' + $('#elecm').value + '&l=' + $('#uname').value + '&p=' + $('#pword').value + '&p2=' + $('#pconf').value;
        $.post(lnk, function (data) { //Do something with data }

the PHP:

<?php
//databse info
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phptest";
//Getting values from link
$comname = $_GET['n'];
$phone = $_GET['f'];
$mail = $_GET['m'];
$uname = $_GET['l'];
$pass = $_GET['p'];
$conf = $_GET['p2'];
//Checking if any value is left empty
if (empty($comname)) {
    echo '1';
}
elseif (empty($phone)) {
    echo '2';
}
elseif (empty($mail)) {
    echo '3';
}
elseif (empty($uname)) {
    echo '4';
}
elseif (empty($pass)) {
    echo '5';
}
elseif (empty($conf)) {
    echo '6';
}

First of all, shouldn't it be

$('#fname').val()

when using jQuery? And while we're at it, using jQuery for just selecting an element by ID is throwing away performance for a little bit of lazyness. Why not use

document.getElementById('fname').value

?

It might only be milliseconds, but they add up in larger scripts, so why not use vanilla JS when you can acheive what you need? :)

And to answer your question:

(document.getElementById('fname').value || '')

is what you're looking for.

您可以按照以下示例查看var是否为undefined,如果它是一个空字符串,否则返回变量本身

var string = ( typeof(string ) == 'undefined' ) ? "" :string ;

Prefer this

$("#someID").value || "default value"

It will allow you define the default value if the userInput is falsy (ie empty string, undefined etc)

If the user enters undefined, it will not be undefined but string "undefined"

 var lnk = 'register.php?n=' + ($('#fname').value||"") + '&f=' + ($('#pnumb').value||"") + '&m=' + ($('#elecm').value||"") + '&l=' + ($('#uname').value||) + '&p=' + ($('#pword').value||"") + '&p2=' + ($('#pconf').value||); $.post(lnk, function (data) { //Do something with data } 

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