So there are several ways to solve your problem. I will show you 2 possible solutions. Which one you choose is up to you.
First solution:
Change your PHP code to this:
if ($_POST['username']==""){
$userErrMsg = "enter your username"; //echo 1
}
if ($_POST['password']==""){
$passErrMsg = "enter your password"; //echo 2
}
echo $userErrMsg .'|'. $passErrMsg;
?>
Next, change your jQuery ajax function to this:
$.ajax({
url: $url,
type: json,
data :formData,
cache: false,
contentType: false,
processData: false,
success: function(response){
var splitResponse = response.split('|');
$('.username-error').html(splitResponse[0]);
$('.password-error').html(splitResponse[1]);
}
});
In this solution you are returning both strings in a single string. In javascript, you are splitting that string up using the pipe character that was added in PHP. That way you have both strings available to you in javascript and you can add each to their own div element.
There are a few downsides to this solution. It assumes those error messages will be returned. If no error is returned, this solution will cause problems.
Second solution:
Change your PHP code to this:
$userErrMsg = '';
$passErrMsg = '';
if ($_POST['username']==""){
$userErrMsg = "enter your username"; //echo 1
}
if ($_POST['password']==""){
$passErrMsg = "enter your password"; //echo 2
}
echo json_encode(['userErrMsg' => $userErrMsg, 'passErrMsg' => $passErrMsg]);
?>
Next, change your jQuery ajax function to this:
$.ajax({
url: $url,
type: $type,
data :formData,
cache: false,
contentType: false,
processData: false,
success: function(response){
$('.username-error').html(response.userErrMsg);
$('.password-error').html(response.passErrMsg);
}
});
In this solution you are returning both strings encoded in JSON. In javascript, you can easily access the JSON string and get the information you need out of it. The advantage of this solution is that you don't have to use it. You can further enhance the JSON encoded string in PHP and return success messages just as well. So your Ajax function won't get into trouble if no errors are returned.
Last note:
Shayllis Alves de Sousa came up with this solution before I did. Therefor you should accept his answer and not mine. I simply provided you with my answer because it makes it easier for you to work with your code.