Tim C. Tim C. -3 years ago 139
Ajax Question

How do I get value from Ajax function for jquery onclick function?

I have a button that when I click on it , it will get data from my database , and display it on my text area based on the id.

JQuery

$('#verifyBtn').on("click", function() {
var exeOutput = checkOutput();
$("outputArea").html(exeOutput);
});

function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}

function getOutput(dataStr, flag) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
return data;
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}


Through my servlet for getting from my database.

Servlet

exercisesModel outputModel = null;
try {
DBConnection db = new DBConnection();
outputModel = db.getExerciseById(request.getParameter("exNo"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.getWriter().append(outputModel.getExpOutput());


EDIT: Upon clicking, i think there is data but my text area is not displaying it.

Answer Source

Since you're making an Asynchronous call you can't return an immediate response using return data;, but instead you could pass the selector then assign the result to your output element when the success callback is called:

<script>
    $('#verifyBtn').on("click", function() {
        checkOutput("outputArea");
    });

    function checkOutput(output_selector){
        var exNo = parseInt($('#selectExercise').val());
        dataString = "exNo=" + exNo;
        $("#result").empty();

        getOutput(dataString, true, output_selector);
    }

    function getOutput(dataStr, flag, output_selector) {
        $.ajax({
            url: "/FYP/WebExerciseByOutput",
            data: dataStr,
            success: function (data) {
                $(output_selector).html( data );
            },
            error : function (xhr,textStatus,errorThrown){
                console.log("Something is wrong with ajax call."+ xhr);
            }
        });
    }
</script>

NOTE : The passed flag parameter isn't used.

Hope this helps.

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