How to use `foreach()` in ajax call

I see that you found the error in the comments given to you on the post, and that is good.

However, it should be pointed out that your code contains both an SQL Injection vulnerability, as well as a Reflected XSS vulnerability.

$catId = $_POST['key']; // value from the ajax
...
$result_fromDB = $wpdb->get_results("SELECT * FROM  sub_category where categor_id = '".$catId."'");

This is an SQL Injection. Basically, you are taking input provided by the user, and directly putting it into an SQL statement without any form of sanitization.

You could fix this by properly using $wpdb->prepare() before running the query against the database, or by simply validating that the “key” that you’re getting is of the form that you expect it to be.

$catId = $_POST['key']; // value from the ajax
...
echo "<option value="".$catId."" >".$catId."</option>";

Similarly, this code echoes back input directly to the browser. This is called Reflected XSS because one could simply send it a <script> code, and have that script run in the context of your website. This could be used in numerous ways against you, although most of them would require some form of social engineering, like tricking you into visiting a malicious webpage in your browser.

Always validate inputs. Always sanitize outputs. Always properly prepare SQL statements. No exceptions.