Prerna
Prerna

Reputation: 1235

how to compare the result of success function of ajax with a string

 $.ajax({
        type:       "post",
        url:        "test.jsp",
        data:           "user="+name.val(),
        success:    function(msg) {

            $('#result').hide();

            $("#result").html(msg)
            .fadeIn("slow"); 
                              if( msg =="available")
                                 {

                                      alert(msg);
                            }


        }
    });

test.jsp
   <h1>
    <%
    String user=request.getParameter("user");
    if(user.equals("prerna"))
    out.print("available");
    else
        out.print("not available");
    %>
   </h1>

i want to compare the value returned by success function to be compared with a string but the above code is not working i also want to add the css class to the "#result" id. the alert box is not comming.

Upvotes: 9

Views: 29316

Answers (7)

prakash
prakash

Reputation: 1

                    success:function(response){

                    if(response=="yes")
                            {
                                    myFunction();
                            }else{

                                myFunctionn();
                            }

                }

Upvotes: 0

Anurag Tiwari
Anurag Tiwari

Reputation: 103

The primary problem in ajax comparison is unwanted space:

var result = $.trim(data);

Upvotes: 2

Ofure Ukpebor
Ofure Ukpebor

Reputation: 31

$.ajax({
    dataType: "text",
    url : 'saveDeviceLike.php',
    success : function(data){
        var reply = data.replace(/\s+/, ""); //remove any trailing white spaces from returned string
        if (reply == 'success')
        $('#pleaseWait').html('Your have successfully registered for this competition.<br/>You will be contacted via mail.');
        if (reply == 'registered')
        $('#pleaseWait').html('You have already been registered for the competition!');
        if (reply == 'failed')
        $('#pleaseWait').html('Your registration cannot be completed now.<br/>Please try again later.');

}

//Make sure you use the replace function to strip of any extra spaces

Upvotes: 3

Adrian Rodriguez
Adrian Rodriguez

Reputation: 453

Something there is a blank space. With $.trim() function you can delete all blank spaces. It works!!!

$.ajax({
type: "GET",
url: url,
success: function(data) {
    var result = $.trim(data);
    if(result==="available"){
        alert("available");
    return false;
    }
    }
});

Upvotes: 19

BalusC
BalusC

Reputation: 1109222

You should not print HTML <h1> element around the ajax response in JSP. Get rid of it. You need to ensure that you have nothing before <% and after %> in JSP, even no whitespace/newlines. JSP would emit them anyway. Actually, a JSP is the wrong tool for the job. A servlet is a better suit for the job.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String user = request.getParameter("user");
    String message = "not available";

    if ("prerna".equals(user)) {
        message = "available";
    }
    
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(message);
}

This will work fine with jQuery dataType: text. Even more, it's not strictly required to set the data type here.

Related questions:

Upvotes: 1

andres descalzo
andres descalzo

Reputation: 14967

You have to set the data type for ajax response, for example:

// text

$.ajax({
   dataType: "text",
    type: "post",
    url: "test.jsp",
    data: "user="+name.val(),
    success: function(msg) {

        $("#result")
            .hide();
            .html(msg)
            .fadeIn("slow"); 

        if(msg == "available") {
            alert("is available");
        }

    }
 });

// json

$.ajax({
   dataType: "text",
    type: "post",
    url: "test.jsp",
    data: "user="+name.val(),
    success: function(data) {

        $("#result")
            .hide();
            .html(data.msg)
            .fadeIn("slow"); 

        if(data.msg == "available") {
            alert("is available");
        }

    }
 });

Specifying the Data Type for AJAX Requests
doc jQuery.Ajax

EDIT

try this options:

// text

$.ajax({
   dataType: "text",
    type: "post",
    url: "test.jsp",
    data: "user="+name.val(),
    success: function(msg) {

        $("#result")
            .hide();
            .html(msg)
            .fadeIn("slow"); 

        if(msg.indexOf("not available") > -1) {
            alert("not available");
        }
        else if(msg.indexOf("available") > -1) {
            alert("available");
        }


    }
 });

// html

$.ajax({
    dataType: "html",
    type: "post",
    url: "test.jsp",
    data: "user="+name.val(),
    success: function(data) {

        $("#result")
            .hide();
            .html(data)
            .fadeIn("slow"); 

        if($(data).filter(":contains(not available)").length > 0) {
            alert("not available");
        }
        else if($(data).filter(":contains(available)").length > 0) {
            alert("available");
        }

    }
 });

Ideally, your file "test.jsp" was as follows:

<%
String user=request.getParameter("user");
if(user.equals("prerna"))
  out.print("available");
else
  out.print("not available");

out.flush(); // Send out whatever hasn't been sent out yet.
out.close(); // Close the stream. Future calls will fail.
return; // Return from the JSP servelet handler.

%>

the end is based on this link

Upvotes: 0

William
William

Reputation: 300

Set the dataType to 'text'. If that doesn't work, then make sure that 'available' really is the only thing being returned, with no line endings or spaces or anything.

Upvotes: 0

Related Questions