I can return a PHP value just fine to AJAX, but when I compare the value within the AJAX function it enters a secondary function even though it should not.
The following code does a post request to another PHP page (ping.php) to check if a url returns valid headers back. That result is returned back to AJAX in a simplified format ("success" or "nope"). I get the correct values in the console, but even with the failed count incremented it still enters the next function. why o' why o' why?
hello.php
<?php
echo "Hello World"; ?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#form_post').on('submit', function(event){
event.preventDefault();
var count_error = 0;
if($('#url').val() == '') {
$('#url_error').text('URL is required');
count_error++;
}
else {
$('#url_error').text('');
}
$.ajax({
url: "ping.php",
method: "POST",
data: $(this).serialize(),
beforeSend: function() {
$('#process').css('display', 'block');
},
success: function(response) {
if ($.trim(response) == "success") {
console.log("success");
}
else {
console.log("failed");
count_error++;
}
}
});
if(count_error == 0) {
console.log("ok");
}
});
});
</script>
</head>
<body>
<html>
<div>
<form method="post" id="form_post">
<input type="text" name="url" id="url" class="my_form"/>
<span id="url_error" class="text-danger"></span>
<div class="form_display" align="left">
<input type="submit" name="form_post" id="form_post" class="my_form" value="form_post"/>
</div>
</form>
</div>
</body>
</html>
ping.php
<?php
if(isset($_POST["url"])) {
// $data = array(':url' => trim($_POST["url"]));
$data = trim($_POST["url"]);
} else {
return;
}
$ping = $data;
$file_headers = @get_headers($ping);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = "false";
} else {
$exists = "true";
}
if ($exists == "true") {
echo "success";
} else {
echo "nope";
}
If you happen to run the code somewhere then you can either put in a valid URL and submit the form (returning "success") or an invalid URL (returning "nope"). "ok" should only appear in the console if "success".