I want to use ajax to toggle a button only if the response equals my condition, i posted both of the code, This part $('#uname_response').html(response);
of the code works fine, my problem is with the if
statement… thank you, I will appreciate if you guys can help me out with this… I have tried many things with no success
$(document).ready(function() {
$("#validationCode").keyup(function() {
var username = $(this).val().trim();
if (username != '') {
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {
username: username
},
success: function(response) {
$('#uname_response').html(response);
if (response == "VALIDATION CODE IS VALID COMPLETE TRANSFER.") {
$("#completebtn").show();
}
}
});
} else {
$("#uname_response").html("");
}
});
});
Ajax File
<?php
include("connection.php");
session_start();
if(isset($_POST['username'])){
$username = $_POST['username'];
$query = "SELECT * FROM users WHERE id = '".$_SESSION['id']."' ";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$verifycode = $row['verification'];
$response = "<span style='color: green;'>VALIDATION CODE IS VALID COMPLETE TRANSFER.</span>";
if($username !== $verifycode){
$response = "<span style='color: red;'>CODE IS NOT VALID REQUEST FOR A NEW CODE.</span>";
}
echo $response;
die;
};
?>
Please if you have any answer please ask.. thanks
3
Answers
if(response == "VALIDATION CODE IS VALID COMPLETE TRANSFER."){
If I understand you correctly, the problem is that the button you want to show with this If-check doesn’t work?
That is because the
response
will contain the HTML tags also, so you would need to change the above to check for:<span style='color: green;'>VALIDATION CODE IS VALID COMPLETE TRANSFER.</span>
You can use
console.log(response)
in your JS-code and the inspector tool in your browser to see what the response actually is.A better soloution will be to apply the HTML with Javascript instead:
Change in your PHP-file:
And change the Javascript to just check for the code:
it’s OK!
on server side(php file) echo json encoded result like:
and
in javascript or js file apply condition like:
Have a nice Day!
the problem resides in comparative statement of if
== will look for strict comparison, which some of the answer may have suggested to include whole tag as well, which is an over kill any ways.
my solution
The includes() method determines whether a string contains the characters of a specified string. it returns true or false.
Keep it simple for your sanity sake.