When I first started working with AJAX in jQuery, one of the most frustrating problems I faced was returning errors from PHP and showing them properly on the front-end. I expected the success()
callback to handle everything, but sometimes it never fired at all. After digging deeper, I realized the issue was not with jQuery it was with what PHP was returning.
Let me walk you through what went wrong in my project, how I fixed it, and what I learned along the way more: marketing internetowy.
The Problem in My First Code
Here’s the first code I wrote:
JavaScript
$.ajax({
type: "POST",
url: "php/verifyName.php",
data: { name: name },
dataType: "json",
success: function(data, status, xhr) {
if (xhr.getResponseHeader("NB_SUCCESS") == 0) {
valid = true;
} else if (xhr.getResponseHeader("NB_SUCCESS") == 2) {
alert("Erreur dans la verification !");
valid = false;
} else if (xhr.getResponseHeader("NB_SUCCESS") == 1) {
alert("Le nom choisi existe déjà, veuillez choisir un autre nom !");
valid = false;
}
},
error: function(xhr) {
alert ("Oops: " + xhr.statusText);
}
});
PHP
header('Content-type: application/json');
if ($nb != 0) {
header("NB_SUCCESS: 1");
} else {
header("NB_SUCCESS: 0");
}
Why This Fail
- I told jQuery:
dataType: "json"
. - But PHP only sent headers, not a JSON body.
- jQuery tried to parse the empty response as JSON → failed → threw a
parsererror
. - The code skipped
success()
and went straight toerror()
.
At that point, I realized: if I promise JSON, I must actually return JSON.
The Fix Always Return JSON
Here’s how I fixed it by making PHP output valid JSON.
PHP (verifyName.php)
<?php
header('Content-Type: application/json; charset=utf-8');
$name = $_POST['name'] ?? '';
$nb = rand(0, 1); // Example: simulate database result
if ($nb != 0) {
echo json_encode([
'ok' => false,
'code' => 'NAME_EXISTS',
'message' => 'Le nom choisi existe déjà, veuillez choisir un autre nom.',
'nb' => $nb
]);
} else {
echo json_encode([
'ok' => true,
'code' => 'OK',
'message' => 'Nom disponible ',
'nb' => $nb
]);
}
exit;
JavaScript
$.ajax({
type: "POST",
url: "php/verifyName.php",
data: { name },
dataType: "json"
})
.done(function (data, status, xhr) {
if (!data.ok) {
alert(data.message || "Erreur dans la vérification !");
$("#result").text(" " + data.message).css("color", "red");
} else {
$("#result").text(" " + data.message).css("color", "green");
}
})
.fail(function (xhr, textStatus, errorThrown) {
console.error('AJAX failed:', textStatus, errorThrown);
console.error('Response:', xhr.responseText);
alert("Oops: " + (xhr.statusText || textStatus));
})
.always(function () {
console.log("AJAX request completed.");
});
This time, the success()
(or .done()
) callback worked exactly as I wanted.
Making It More Practical
Once I got the basics working, I added more functionality to make the project feel professional.
Dynamic Result Display
Instead of spamming alerts, I displayed the results inline:
<input type="text" id="username" placeholder="Enter username">
<button id="checkBtn">Check</button>
<div id="result"></div>
Client-side Validation
Before sending the AJAX request, I validated the input:
$("#checkBtn").on("click", function() {
let name = $("#username").val().trim();
if (!name) {
$("#result").text(" Please enter a name").css("color", "orange");
return;
}
// run the AJAX here
});
Better Error Handling
I used HTTP error codes in PHP to signal real failures:
if ($db_connection_failed) {
http_response_code(500);
echo json_encode(['ok' => false, 'message' => 'Database connection error']);
exit;
}
Multiple Error Codes
I returned different error codes for different issues:
echo json_encode([
'ok' => false,
'code' => 'INVALID_INPUT',
'message' => 'Nom invalide. Seuls les caractères alphanumériques sont autorisés.'
]);
Final Thought
I learned that most AJAX “errors” are not really JavaScript problems they come from how the server responds. Once I understood that jQuery expects proper JSON when I ask for dataType: "json"
, everything became easier.
Now, instead of wasting time chasing parser errors, I structure my PHP responses properly, add error codes, and give users helpful feedback. If you’re stuck with error()
firing instead of success()
, double-check what your server is really sending you might be surprised.