i wan't to pass a variable without using get to php, so, i'm using post with jquery, but i can't write the result into the document (refresh all the page)
here is the code:
$.post("/"+$(this).attr("href"),{returnto:$(this).attr("rel")},function(a){$(document).html(a);});return false;});
The document is not the place to write your result as the document is the meta envelope around the html page you see. Rather use the body:
$("BODY").html("MY ANSWER IS: "+a);
Related
I'm doing few exercise using Node.js, Express.js and MongoDB.
At the moment I've a problem trying to push new contents created with jQuery.Ajax.
I have a list of posts in homepage with Jade: (now I will write something simple, but mine is with much more html elements...)
ul
each post in posts
li
h1 title
p post
With a normal form and postback it is ok because the page is refreshed.
Bue using jQuery and Ajax on success I should append the new post without refresh the page...
There is a solution with Jade to do that without writing the entire html in jQuery?
Can you suggest a better way to do this?
Jade is compiled as HTML, so no, there is no way to use jade templates in your jQuery. What you can do, however, is write snippets in jade, compile them, and save them to your webserver (such as post_template.html), then load file with jquery, create a jQuery element from the loaded text, and then change properties and contents of the elements within the new element. Then you append the element to the page.
This approach would allow you to avoid writing html in your jQuery.
//Wrap this in the code that gets updates
$.get( "templates/post.html", function( data ) {
var el = $(data);
//If you want to change specific properties
var title = el.children('h1');
title.text('My new text');
el.appendTo('ul#postList');
});
If you wanted to do this on click, for example, just wrap that function in a click handler for some element on the page that you want to use to trigger new item.
Let's say you're retrieving a complete HTML page using Ajax. You now have a page of HTML in a variable.
Assuming you need to find and extract some data from that page, how do you do it?
Traditionally I've done this using regular expressions, but I'm wondering if there's a way to perform jQuery operations on that retrieved source code instead. It would simplify things tremendously, as jQuery is built for parsing HTML DOM trees.
I'm thinking maybe appending the retrieved source to the current page DOM in hidden form...? Is there a better way?
jQuerys parseHTML might be what you are looking for: http://api.jquery.com/jquery.parsehtml/
If I understand you well, you have the html code of the page loaded through ajax in a variable (let's call it data), and then you want to search through it using jquery operations.
You could create a container in your first html page, and then fill it with the content returned by Ajax. You can then handle it normally with jQuery
So:
<body>
<div id="first_page">
<h3>First page</h3>
<p>This the page that makes the Ajax call</p>
</div>
<div id="ajax_container"></div>
</body>
Now, after you Ajax call, you fill the container with data
$("#container").html(data);
Then, you can use .find(), or simply write an appropriate jquery selector.
var a = $("#container").find("#my_id").html;
var b = $("#container #my_id").html();
Now a and b should contain the content from the element with id my_id from the page loaded with Ajax
PS: I'm not sure if you want to append the data to you current page. You don't have to, if that's not what you are trying to achieve.
It might be a noob questions but I have just started using jquery.
My basic requirement to extract the link which is there in the javascript code present in another html (code is embedded in the html page and not in a seperate file).
The link is also present as a href attribute of <a> tag inside a tag, just to add if it is easier to extract it from there (I am using chrome so I think it considers there are no child nodes of <noscript> tag)
After this I tried doing an ajax request to the html page (using $.ajax) thinking it will run the scripts on the page but got the html code of the page in return :S . I have also heard of something called evalscripts:true but not sure if that will work here or how to use it?
I have also tried to search for the link in html code returned by my html page by using the "contains" operation of jquery.
I am doing all this to create a greasemonkey script. Please suggest
Example Code:
This is a function present inside the html of that page:
function fun() {
obj = new pollingObj('argument', "a link I want to extract comes here");
}
I want to extract the link: "a link I want to extract comes here" and then open it.on my page where I am running my jquery script
This link is also present like this on the html page:
<noscript>
blabla
</noscript>
Also is it possible to run the javascripts present on that page if the link extraction is not possible?
If you're able to get the html code of the page successfully via .ajax, and the data you want is in the HTML code, it's not worth the effort to bother with trying to run the scripts. Just access the URL through the DOM:
// ajax success function
success: function(html) {
var anchorCode = $(html)
// this assumes that noscript is a top-level element
// otherwise, use .find('noscript')
.filter('noscript')
.text(); // get the code for the anchor tag, as a string
var myLink = $(anchorCode).attr('href');
// do something with myLink
}
Edit: It turns out that jQuery is a little funny in the way it deals with noscript tags - inner tags don't appear to be considered part of the DOM, so you need to grab the text content of the tag and then use jQuery to DOM-ify it. See updated code above.
I wrote a script and I want to change the language. I managed to do this using the .ajax() function in jQuery and fetching the new HTML.
Afterwards I want to replace the old HTML with the new HTML.
However, I do not want to exchange the whole HTML, but only part of it.
I know that the HTML returned includes a <div id="myDivId">...</div>, so I only want to get the content of that div from the HTML returned, and replace the content of my current div with the new content.
But, I can't seem to figure out how to fetch only that content from my new HTML. How can I do that? I tried using find, but no success.
$.ajax({
type: "GET",
url: "ajax.php",
data: "action=languagepack&subAction=box&newIso="+newIso+"&country="+country,
success: function(htmlCode){
var box = $(htmlCode).find('#myDivId').html();
alert(box);
}
});
Best regards,
Paul Peelen
Try jQuery.load()
This method is the simplest way to
fetch data from the server. It is
roughly equivalent to $.get(url, data,
success) except that it is a method
rather than global function and it has
an implicit callback function. When a
successful response is detected (i.e.
when textStatus is "success" or
"notmodified"), .load() sets the HTML
contents of the matched element to the
returned data. This means that most
uses of the method can be quite
simple:
$('#result').load('ajax/test.html');
Loading Page Fragments
The .load() method, unlike $.get(), allows us to specify a
portion of the remote document to be
inserted. This is achieved with a
special syntax for the url parameter.
If one or more space characters are
included in the string, the portion of
the string following the first space
is assumed to be a jQuery selector
that determines the content to be
loaded.
We could modify the example above to use only part of the document that
is fetched:
$('#result').load('ajax/test.html #container');
If you need HTML from only one container - then load is recommended way certainly. If you need some additional custom processing - are you sure that #myDivId inside blocks given from server and not one of these blocks? In the 2nd case you need filter inside of find (or wrap all HTML into some div to be sure that all elements will be inside it and won't be top level elements).
Shoot that through a php, run a explode change the contents, recreate the div, replace it where you want.
You can do all this with ajax too, but trigger the php file
try this with returned html:
var d = $("<div/>");
$(d).html(msg.d);
var box = $(d).find("#testDiv").html();
alert(box);
So, I see so many people wondering how to execute JS code returned via ajax. I wish I had that problem. My JS executes, but I don't want it too!
Using jQuery 1.4.2, I'm making a GET request:
$.ajax({
url:'/myurl/',
type:'GET',
success:function(response){
$('body').html(response);
}
});
The response looks something like:
<p>Some content</p>
<script>alert("hi!");</script>
Whenever the success callback fires and the response is injected into the DOM, the alert code fires! I don't want that to happen. What can I do to prevent this?
If you can't modify the response, try to "replace" <script> tags:
"<script>alert('hi');</script>".replace(/<(\/?script)/gi, "<$1");
This should escape the tags, making they appear as plain text instead of executing.
Related links
jQuery: Parse/Manipulate HTML without executing scripts
XSS Cheat Sheet
did you try returning function() snippets like
<script>
function Hello(){
alert('Hello');
}
</script>
This way the your JS doesn't execute right away but can be called later when required. But, again it depends what you actually want to do.
Depends. Do you need the JavaScript, or can you just get rid of it? If you don't need it at all, you could do something like
response = response.replace(/<script.*?<\/script>/gi, "");
However, if you need it, you're going to need to figure out how to kill just the function call(s) that you don't want. Using your example of an alert:
response = response.replace(/alert\(.*?\)/gi, "alert");
By getting rid of the trailing parens, and whatever they contain, you stop the function call from happening. Obviously, what you'll need in your regex will depend on the actual code that's causing the problem.
$('body').html(response.replace(/(<script)[^\>]*/g,'$1 src="emptyfile.js"'));
where emptyfile.js exists but has no content.
The problem you have is that jQuery strips script tags from the html and creates a document fragment.
To elaborate
var e = $("<div>Hello</div><script>alert('hi')</script>")
e.html(); // will not display script tags as script tags are now in a document fragment
$("body").append(e); // will execute the script tags in the fragment
See John Resig's explanation and another forum post on this topic.
So, what you can do is
var e = $("<div>Hello</div><script>alert('hi')</script>")
e.filter("script").each(function(){this.text='';});
That would basically make all the scripts empty and now you can
$("body").append(e);
See this post for the fragment creating routine.