Neel
Neel

Reputation: 141

Display input fields only if ID exists in database

I am trying to create a PHP form in which I ask for the input of Customer ID. If the ID exists, then I allow the user to fill in further details about the customer such as his phone number, address etc. If the ID does not exist, I throw an alert saying that no such customer ID exists.

I have tried the following code without any fruitful results.

<style>
#hidden {
    display: none;
}
</style>

<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
  <input type="text" name="cust_id">
  <input type="submit" value="Add details" name="check_cust">

  <div id="hidden">
          <input type="tel" name="phone">
  </div>
</form>

<?php
if(isset($_POST['check_cust'])) 
{
    $id = $_POST['cust_id']
    if(idExistsInDatabase($id))
    {
    const obj = document.getElementById('hidden');
    obj.style.display = 'block';
    }
}

When I execute the above code, I get the following error:-

Uncaught TypeError: Cannot read property 'style' of null

I am new to web development and would appreciate any help. Thanks in advance

EDIT: Never mind. I did it using AJAX.

Upvotes: 1

Views: 588

Answers (1)

Kapil Karangeeya
Kapil Karangeeya

Reputation: 310

You're using JS Code inside PHP. You can't use like that.

How you can use is to use script tags inside echo in PHP. For example,

 echo "<script type='text/javascript'>alert('JavaScript code!');</script>";

Now to make your working change you portion of nested if like this below given :

if(idExistsInDatabase($id))
{
    echo "<script type='text/javascript'>document.getElementById('hidden').style.display = 'block';</script>";
}

Above code should do the job for you.

Upvotes: 1

Related Questions