Bob Kaz Bob Kaz - 3 years ago 112
Ajax Question

How can I put a deferred.fail message in this script of mine correctly?

I'm trying to output a message if the server AKA the variable call url can not find the file call x so how can I add a deferred.fall successfully in this script I know the syntax is wrong but there isn't a lot of good examples out there for me to better understand this in my code situation. If any one can show me or give me the exact syntax code of this I will really appreciate it, that's how I learn best personally.

code

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var url = "x";
var data = {
name: "John Doe ",
city: "Anywhere "
}
var success = function(response){$("#callback_id").html(response);
}
$("#execute").click(function(){
$.get(url,data,success);
url.fail(function() {
alert( "$.get failed!" );
});
$("#execute").hide();
});
});
</script>
</head>
<body>
<h1>jQuery.get with url,data,success & dataType (Object version)</h1>
<div id="callback_id"></div>
<button id="execute">Click</button>
</body>
</html>

Answer Source

You're concatenating the fail() callback to the url, instead to the promise that $.get returns. You can concatenate the success and fail function...

$(document).ready(function(){

    var url = "x";
    var data = {
        name: "John Doe ",
        city: "Anywhere "
    };

    $("#execute").click(function(){

        $.get(url,data,function(response) {
            $("#callback_id").html(response);
        })
        .fail(function() {
            alert( "$.get failed!" );
        });

        // IMPORTANT!! Check if you want to do this always or only if $.get succeed!!
        $("#execute").hide();
    });
});

If for some reason you don't want to chain functions in the same $.get call, you'll have to save the promise that $.get returns in a variable...

$(document).ready(function(){

    var url = "x";
    var data = {
        name: "John Doe ",
        city: "Anywhere "
    };
    var success = function(response){ $("#callback_id").html(response); }

    $("#execute").click(function(){

        var jqxhr = $.get(url,data,success);

        jqxhr.fail(function() {
            alert("$.get failed!");
        });

        // IMPORTANT!! Check if you want to do this always or only if $.get succeed!!
        $("#execute").hide();
    });
});

... but I'd go with the chain version.

I hope it helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download