This is rather an odd question, but, I want to make $.ajax fail to check my fail trigger in it, I have this jQuery code:
$(document).ready(function () {
$("#trigger").on("click", function () {
$.ajax({
url: "text.php",
success: function (data) {
$(".log").html(data.slice(0, 1000));
//alert("Load has been performed");
},
fail: function () {
$(".msg").html("Something went wrong...");
}
});
});
});
And am calling this PHP code:
<?php
function foo()
{
return "bar";
}
print foo();
return false;
?>
and want to make sure that the fail: ...
is working. How do I do this?
EDIT
I have amended the text.php to be this:
<?php
throw new LogicException("Failed");
Also:
<?php
header("HTTP://this.does.not.exist");
But this still shows in the $(".log")
area even though it has failed.
Noticed I was using the fail function wrong, now amended my jQuery to:
$(document).ready(function () {
$("#trigger").on("click", function () {
$.ajax({
url: "text.php"
}).done(function (data) {
$(".log").html(data.slice(0, 1000));
}).fail(function () {
$(".msg").html("Something went wrong...");
}).always(function () {
alert("One way or another, we did it!");
});
});
});
Also if it helps, I am using these scripts for jQuery libraries:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
We can use the fail() callback function as well on the JavaScript promise object( the jqXHR object return by the $. ajax() function) to run the specific function on the ajax request fail. function(event, xhr, options) – This is not an optional parameter.
Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.
The done() function is given a function as parameter. The callback function passed as parameter to the done() function is executed if the AJAX request succeeds. The callback function gets three parameters: data , textStatus and jqXHR . The data parameter is the data returned by the server.
Since XML HTTP requests function by using the same protocol as all else on the web (HTTP), technically speaking, AJAX-based web applications are vulnerable to the same hacking methodologies as 'normal' applications.
You could send a header returning an error.
For example:
header("HTTP/1.0 404 Not Found");
Or of course have your script generate a fatal error ;-)
Two suggestions:
Change the .fail
callback call to .error
and
Try it by returning an error status code from your server like jeroen suggested,
header("not-real.php", true, 404);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With