Unable to find a specific hidden field from the Ajax response

Viewed 40

I mostly work on the backend and trying to achieve something on the frontend using Jquery.This is what I am trying to accomplish.

  1. Pass an URL from the backend as part of the Ajax response.
  2. Parse the URL from the Ajax response and perform some additional actions.

This is how my response HTML looks like: (I can not change the structure of the HTML)

<html>
<head>
    <title>Test Me</title>
</head>
<body>
<input type="hidden" id="confirmationURL" name="confirmationURL" value ="www.myurl.com"/>
</body>
</html>

This is how I am trying to parse and get the value for the confirmationURL

success: function (res) {
  
    if (xhr.getResponseHeader('RESPONSE') === "true") {
      
        var $response = $(res);
        alert($response.find('#confirmationURL').text());
        //alert($(res).contents().find("#confirmationURL").text());
        var $result = $(res).contents().find('#confirmationURL')
        console.log($result.attr("confirmationURL").html());
        alert($(res).contents().find('#confirmationURL').text())

    }
    // some other stuff
}

I have even tried with the filter option but with everything I am getting empty value or undefined. I am not sure if this is correct as as I tried all these options by going through the different posts an suggestion. Can some one point me to the right direction as what I am doing wrong to get the confirmationURL

1 Answers

The issue is because there is no parent containing element in the body of the HTML you receive. As such you need to use filter() when attempting to retrieve the input from the top level of the resulting DOM.

In addition you need to read its value, not its innerText or innerHTML, so use val():

let res = '<html><head><title>Test Me</title></head><body><input type="hidden" id="confirmationURL" name="confirmationURL" value="www.myurl.com"/></body></html>';

var $response = $(res);
console.log($response.filter('#confirmationURL').val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Also note that you should always use console.log() for debugging JS. alert() is a blocking call and coerces data types so is not reliable at all.

Related