Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an element by ID in an AJAX Response with jQuery

Tags:

I need to post data to a php page and then I'd like to get the text of a certain div that is in the response but I can't seem to set things up correctly. I'm not too good with jQuery but I can usually figure things out fairly quickly... I've been at this for a minute and have tried everything I have found... I think I am just missing the right combination of stuff.

$.post("process.php", data , function (response) {           var w = window.open();             $(w.document.body).html(response);          console.log(typeof response); //  yeilds string         //create jquery object from the response html        // var $data = $(response);   // yeilds Uncaught Error: Syntax error, unrecognized expression: + whole html text          var success =  $($.parseHTML(response)).find("#success");         console.log('success');         console.log(success);        // see screenshot        console.log(success.text()); // yields nothing         console.log(success.val());  // yields undefined         // if (window.focus) {w.focus()};    },'html');   

this is the output of console.log(success); and the red box is what I want from the response...

![this picture seems really tiny... it wasn't that tiny when I made it. I hope it is still readable][1]

and this does that:

var success =  $(response).find("#success");  console.log('success');  console.log(success);        // yeilds Uncaught Error: Syntax error, unrecognized expression: + whole html text in red 

Response is...

<html><head>    <style>        div.totals {           font-family:calibri; font-size:.9em;  display:inline-block;            border-width: 2px;  border-style: solid; border-color: #FFD324;            background-color: #FAF5D7; color: #514721;            width: 500px;            }        div.error_invalid {          font-family:calibri; font-size:.9em;  display:inline-block;           border-width: 2px; border-style: solid; border-color: #9999CC;           background-color: #EEEEFF; color: #7979B8;       }      </style>     </head>     <body>     <div class="totals">Total new rows added: 0 out of 0<br/></div>     <br/><br/>     <div class="totals">Total updated rows: 0 out of 0 <br/></div>      <div id="success">true</div>     </body></html>  

And I have tried removing the style part and I added in the html, head and body tags in hope that it would help.... meaning, I have the same issues if the response only consists of the three divs.

like image 365
gloomy.penguin Avatar asked Apr 26 '13 15:04

gloomy.penguin


Video Answer


2 Answers

Notice how all of the elements are on the same level? You need to use .filter() to narrow down the current selection to a single element in that selection, .find() will instead look at the descendants of the current selection.

var success =  $($.parseHTML(response)).filter("#success");  console.log(success); // div#success 
like image 64
Kevin B Avatar answered Sep 24 '22 10:09

Kevin B


I got a full 'html' page returned by ajax, but I only need partial of its content, which wrapped by a div and also I need to execute the script inside the 'html' page.

 $.ajax ({   type: "POST",   url : "contact.php",   data: $("#formContactUs").serialize(),   success: function(msg){     console.log($(msg)); // this would returned as an array     console.log(msg);    // return whole html page as string '<html><body>...</body></html>'     $('#id').html($(content).closest('.target-class'));     $('#id').append($(content).closest('script')[0]);  // append and execute first script found, when there is more than one script.   } }); 

@kevin answer gave hints to why find() is not working as expected, as it only select its descendant but not the first element under consideration. Besides using filter, $.closest() also works if current element is what you are looking for. Well, probably this post quite similar to @Kevin's answer, it's just to suggest another alternative answer and gave more details which hopefully make thing clearer.

like image 24
ken Avatar answered Sep 23 '22 10:09

ken