Note: With the help of some comments it seems like this is most likely not possible
I'm using a jQuery ajax call to send an e-mail address, in the called PHP file I return an error or success message depending on the outcome.
Now I want to alert this outcome after my jQuery $.post is successful, the problem is that the called PHP file includes a config file that also has a Javascript file, so my data will look like this:
<script type="text/javascript" src="x.js"></script>Message
So I tried the following:
Data
<script type="text/javascript"> src="x.js"></script><p>Message</p>
And I tried two different things within my $.post:
Post
$.post('ajax.php',function(data){
alert($(data).find('p'));
// this returns [object Object]
alert($(data).find('p').html());
// this returns null?
}
The fact that alert($(data).find('p')); returns [object Object] leads me to think it is working, but then I don't understand why .html() returns null. If I check data through firebug it shows exactly what I typed above.
Some extra information
console.log(data)
returns
<script type="text/javascript"> src="x.js"></script><p>Message</p>
console.log($(data).find('p')) returns a jQuery object.
console.log($(data).find('p').length); returns 0
$('html').append(data);
console.log($('p').html());`
returns Message as expected.
Final edit
I didn't think about the fact that the $ in $(data).find('p') is probably why it's returning [object Object].
Now that I think about it, it seems quite obvious it's impossible to do what I am asking because I am trying to use jQuery's selector engine on a string. I'll change my document structure to remove the JS reference from my config file instead.
To use selectors you first need that string to be part of the DOM tree. $(data) does not do it automatically, you need to append it to an element (like body) or to replace an existing one.
onComplete: function(content) {
content.find("#whatever"); // won't work
$("#existingElement").html(content);
$("#existingElement").find("#whatever"); // works
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With