jQuery Ajax if variable on submit is ok hide button

I am trying to hide the submit button if the email is the same with the one in the database from action.php. How could I implement this in my following code:

<form onsubmit="return submitdata();">
    <input type="text" id="mail">
    <input type="submit" value="Check">
</form>

<p id="msg"></p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">

function submitdata()
{
    var name=document.getElementById('mail').value;

$.ajax({
    type: 'post',
    url: 'action.php',
    dataType: 'text',
    data: {
        'name':name
    },
    cache:false,
    success: function (data) {
        console.log(data);
        $('#msg').html(data);
    }
});

return false;
}

</script>

action.php:

<?php 
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
    echo "Response: ".$email;
    $hide = 1;
}else{
    echo 'hmmmm';
}
?>

When the email coincide I get the correct message, but how could I call back $hide to determine to hide my submit button?

Answers 1

  • Instead of returning a message, return an indication. (In the JS script write the message accordingly)

    A detailed json string would be a good idea but for simplification see the following.

    PHP:

    <?php 
    require_once 'config.php';
    $email_ck=$_POST['name'];
    if(extract($crud->get_email($email_ck))){
        echo "already_exists";
    }else{
        echo 'not_exists';
    }
    ?>
    

    JS:

    $.ajax({
        type: 'post',
        url: 'action.php',
        dataType: 'text',
        data: {
            'name':name
        },
        cache:false,
        success: function (data) {
            if(data == 'already_exists'){
               $('#buttonId').hide();
            } else if(data == 'not_exists'){
               $('#msg').html('Response: ' +name);
            }
        }
    });
    

Related Articles