I would like to add the data
parameter only when it has value if not then don’t add data in the parameter string.
Currently, it is throwing unexpected token if
and data values shows undefined
function Data() {
if ($("#data").val().length != 0) {
"&data=" + $("#data").val();
}
}
function check() {
launch += & firstname = " + $("#
first ").val() + " & data = " + Data();
}
Adding the parameter in this way
"&data=" + Data();
2
Answers
You need to return an empty string if there’s no data value.
You need to fix the quoting in
check()
. And it doesn’t need&data=
, because that’s added byData()
.You should call
encodeURIComponent()
to ensure that the values are properly encoded.If you’re using
$.ajax()
, you can avoid all of this by putting the parameters in an object instead of a string. Then you can just conditionally add thedata:
property to the object.📎 – Looks like you’re trying to build a URL-encoded string.
I strongly suggest building up an object of parameters and passing that through URLSearchParams() or jQuery’s $.param(). That way it will be properly encoded