aWebDeveloper
aWebDeveloper

Reputation: 38352

Jquery Find if response contains element

How do you find if the response contains the element form

    $.ajax({
        url     : $(this).attr('action'),
        type    : 'POST',
        success : function(response){
            if($(response).find('form').length)
            {
                alert("hii");
            }
        }
    });

Form could be the topmost element of the response or somewhere in middle

Upvotes: 0

Views: 4331

Answers (4)

Andy Jones
Andy Jones

Reputation: 6275

The dataType : 'html' forces jQuery to treat the response as simply html. I'm using the "has" function which will reduce the matched set of elements to only those that contain a form somewhere in them.

 $.ajax({
        url     : $(this).attr('action'),
        type    : 'POST',
        dataType : 'HTML',
        success : function(response){
           $(response).has('form').doMoreWorkHere();
        }
    });

Alternatively, you can write that shorter by

$.post($(this).attr('action'), {}
       function(response){
         $(response).has('form').doMoreWorkHere();
       }, 'html');

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

$.ajax({
        url     : $(this).attr('action'),
        type    : 'POST',
        dataType: 'html', // you should set it 
                          //  if you response send html only
        success : function(response){
            if($(response).filter('form').length)
            {
                alert("hii");
            }
        }
    });

According to update:

        ....
        dataType: 'html',
        success : function(response){
            var container = $('<div/>').append(response);
            if($(container).find('form').length)
            {
                alert("hii");
            }
        }

Upvotes: 2

epascarello
epascarello

Reputation: 207501

$.ajax({
    url     : $(this).attr('action'),
    type    : 'POST',
    success : function(response){
        var hasForm = $("<div></div>").append(response).find("form").length > 0;
        if(hasForm)
        {
            alert("hi");
        }
    }
});

Upvotes: 0

Andrew
Andrew

Reputation: 505

Where does 'response' come from? What format is it?

I send my returned vars in json:

success: function(msg){
    var obj = jQuery.parseJSON( msg ); 
    alert( obj.VARNAMEHERE );
}

Or you could just examine the entire response as opposed to a particular variable. That would give you an idea as to how to traverse the results to find what you're looking for.

Upvotes: -1

Related Questions