SULTAN
SULTAN

Reputation: 1159

show a div based on a conditional ajax result in php form

I have a PHP form`looks like this

<form>
    <div id="inid">
        National ID: <input type="text" id="individual_nid" oninput="getIndividualName(this.value)" />
    </div>
    <hr />
    name: <div id="individual_name_fetch"></div>
    <hr />
    <div id="other_inputs fields" style="display: none;">
        more inputs fields...
    </div>
</form>

In my PHP form I have an input textbox where the user inserts a number

<input id="individual_nid" oninput="getIndividualName(this.value)" />

this textbox fires on the fly the following ajax function

function getIndividualName(val)
{
    $.ajax({
        type: "POST",
        url:"get_individual_name.php",
        data: 'individual_nid='+val,
        success: function(data){

            $("#individual_name_fetch").html(data);

        }
    });
}

in this function, I pass the user's input to the get_individual_name.php page.

in the get_individual_name.php page, I have a PHP script that searches for the inserted number in the database and gets the corresponding individual name and fetches it to the id="individual_name_fetch" div.

the PHP script in the get_individual_name.php page looks like this:

$q = mysqli_query($link, "SELECT * FROM table WHERE national_id = '".$_POST['individual_nid']."' ");
if(mysqli_num_rows($q) == 1)
{
    while($r = mysqli_fetch_assoc($q))
    {
        echo $individual_name = $r['individual_name'];
    }
}
else
{
    echo $individual_name = 'Not in db';
}

up to here everything is fine

What I need to do now...

If the searched user founded in the db (mysqli_num_rows($q) == 1) then I want to display the other inputs div id="other_inputs fields" in the form. and if not, then the other_inputs fields div hides again

How can I accomplish this?

please be aware that the ajax function and the PHP script run on the fly


NOTE & UPDATE the script's output will be HTML code, for example

  1. if the result found the output will be:

<span style="color: green;"><i class="fa fa-check fa-fw fa-lg"></i> <?=$individual_name;?></span>

OR

  1. in case no result found:

<span style="color: red;"><i class="fa fa-times fa-fw fa-lg"></i> No user found.</span>

What I am thinking about is to assign a variable e.g. $show_extra_fields = true or $show_extra_fields = false and pass it back to the ajax function and from there I check the value of the $show_extra_fields variable and based on the value I show/hide the other fields div.

is this possible?

Upvotes: 0

Views: 1341

Answers (3)

webdevbyjoss
webdevbyjoss

Reputation: 524

The quick fix: Don't produce any output in case there is no data. Just check for empty string in response.

    success: function(data) {
        if (data === "") {
            $('#other_inputs_fields').hide();
            $("#individual_name_fetch").html('No data available');
        } else {
            $('#other_inputs_fields').show();
            $("#individual_name_fetch").html(data);
        }
    }

Long term solution: This code still looks OK for student's assignments work or hobby project. But in all other cases, you better look for some WEB framework, like Symfony https://symfony.com/. Frameworks will help you to build your application in a more structured way, offering the best practices our of the box, including the security issues pointed out in comments.

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34416

To do what you're asking you would add show and hide functions to the AJAX callback:

function getIndividualName(val)
{
    $.ajax({
        type: "POST",
        url:"get_individual_name.php",
        data: 'individual_nid='+val,
        dataType: 'json',
        success: function(data){

            $("#individual_name_fetch").html(data);
            if(data[0] != 'Not in db') {
               $('#other_inputs').show();
            } else {
               $('#other_inputs').hide();
            }
        }
    });
}

Keep in mind that ID's Must Be Unique, specifically because it will cause problems in JavaScript and CSS when you try to interact with those elements. ID's must not have spaces in them.


EDIT: Return JSON with PHP (CAUTION: Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!)

$q = mysqli_query($link, "SELECT * FROM table WHERE national_id = '".$_POST['individual_nid']."' ");
$json = array();
if(mysqli_num_rows($q) == 1)
{
    while($r = mysqli_fetch_assoc($q))
    {
        $json[] = $r['individual_name'];
    }
}
else
{
    $json[] = 'Not in db';
}

echo json_encode($json);

Upvotes: 2

Mohamed Abbas
Mohamed Abbas

Reputation: 2278

You can do that using JavaScript. Check the AJAX response then take an action depending on this response.

Note: Don't use spaces in the id in your html

 success: function(data){

        $("#individual_name_fetch").html(data);
        if (data === 'Not in db') {
            document.getElementById('other_inputs_fields').style.display = 'none';
        } else {
            document.getElementById('other_inputs_fields').style.display = 'block';
        }

    }

Upvotes: 0

Related Questions