how to load all elements on my page with javascript? - javascript

I have a dynamic page with different elements in each generates, and I want to load all of their lines to an alert for example or a page with JavaScript. Is this possible?
For example, if I had this line to my page:
<marquee> This is for test </marquee>
I want to show all of it to an alert or a page, somethings like that :
Pseudo-code:
<script>
alert(getAllData) | write(getAllData)
</script>
Output: (in alert)
<marquee> This is for test </marquee>

You can use Ajax. Here's an example that alerts the contents of the page test.aspx, for example:
var rq;
// Initialize the request:
if(window.XMLHttpRequest) {
rq = new XMLHttpRequest(); // Standards-compliant way, compatible with every browser except IE6 and under
} else {
rq = new ActiveXObject('Msxml2.XMLHTTP'); // IE6-compatible.
}
// Open the request:
rq.open('GET', 'test.aspx', true); // GET is the method (you're probably familiar with this), test.aspx is the URL, and true means send asynchronously.
// Set up the state-change handler:
rq.onreadystatechange = function() {
if(rq.readyState === 4) { // Request complete
alert(rq.responseText); // The response is in the responseText property.
}
};
// Finally, send the request:
rq.send(null);
For more information, Google "Ajax." There are plenty of good tutorials.

Related

Will an ajax call finish even after a page redirect?

I am trying to create a temporary image url for a local image and send it to Google to do a Search by Image. I don't want the image url to be permanent so I want to delete it right after I use it. I have the code below:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(); // asynchronous call to server to delete the URL
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ xml.responseText; // the image url
}
}
xml.open("GET", "REST_ENDPOINT", true);
xml.send();
}
The function above calls the server, and when it finishes, will delete the url and redirect the page. The function "deleteImageURL()" is another ajax call done asynchronously. Currently, this loads the google page fine as the image URL is not done deleting the url by the time that the redirect happens.
My question is this: Will deleteImageURL() finish deleting the image URL even after the page redirects or will it stop (and thus, never delete the URL)?
EDIT: So I was thinking about what you guys were saying about race conditions and tried the following code instead:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(xml.responseText);
}
}
xml.open("GET", "REST_ENDPOINT"
+ id + "/public_url", true);
xml.send();
}
// Deletes the url for the image.
function deleteImageURL(imageURL) {
var xml = new XMLHttpRequest();
xml.open("GET", "REST_ENDPOINT_FOR_DELETE", true);
xml.send();
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ imageURL;
}
This code works every time that I run it. I think that there still may be a race condition, but it seems to be working fine so far.
Thanks again.
The "deleteImageURL()" will finish deleting the image URL even after the page redirects..
Refer : Should I wait for ajax to complete to redirect a page?
The server won't stop processing the request (initiated by deleteImageUrl), but you will not be able to handle a callback if the current page unloads in the browser before the operation is completed.
If deleteImageURL(); contains an async call you should do the redirect when the call is completed. Your code will work when the call is synchronious. We don't see the source of deleteImageURL(); and can be more concrete, but you should do the same thing as you've done for getImageURL().

XmlHttpRequest - send() with post seems to not work

I am trying the following :
<html>
<script src ="myscript.js" type = "text/javascript">
// in this file i have the foo functions defined...
</script>
<!--- here the page is defined -->
<form action = "some.php" method = "post">
<input type = "submit" name ="exec" value = "EX" style="width:40px" id = "EX" onClick="foo();">
</html>
Now, in myscript.js :
function foo() {
var req;
req = new XMLHttpRequest();
req.open("POST", "mydomain.name/hello.php", false);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// ldt is a successfully defined string,
// i am not showing the complete function, but an alert here
// showes that ldt is successfully defined
req.send(ldt);
alert("sent");
alert(req.status);
if(req.status == 200)
{
var lddata = req.responseText;
alert(lddata);
}
}
Not that in my javascript, I have called hello.php, while the form in the initial htmp goes to a different file : some.php.
The file hello.php just spits "hello world" , and nothing else - at this moment, nothing is doe with the post variables.
Now, I would expect that until req.send() recieves a response, it javascript wont execute any futher, and before some.php is loaded, i will at least be alerted about the state of req.
However, in firefox (all files are being excuted from a local apache server, besides for hello.php, which is in mydomain.name. I have CORS enabled by default.), before I get to know the status of req via an alert, the next page, some.php is loaded.
What is wrong?
PS: there are some questions in the similar topic in SO, but i did not seem to have made any progress with them.
EDIT: as mentioned in the comment : this is the plan
Click on the "EX" button, in the html file at the begining, causes the onClick function foo() to get activated.
foo() does the XmlHttpRequest() to load a response from hello.php somewhere else (mydomain.name)
Then foo() alos sets the value of an hidden input element
Then since EX is a submit button, the form submits everything (including the newly set hidden element) to some.php, which is in the same server.
Edit 2: Also tried with
req.open("POST", "http://mydomain.name/hello.php", false);
as mentioned in a comment, did not work either.

HTML Collapsibility doesn't persist through PHP load

Basically, I'm creating a website where I'm using jQuery Collapse to format some elements. These elements, however, are being generated by a PHP script and loaded through Javascript (see below). For some reason, the loaded elements don't have the desired collapsibility.
I've confirmed that just placing the generated elements in as static HTML fixes the problem, but I would like for the HTML code to be generated at run-time.
Why is this? Is there anything I can do to fix it?
Thanks! Below is a code example of what I'm trying to do
index.html
...
<body onload="test()">
<div id="content"> </div>
</body>
...
javascript
function test(){
// Create the request object
var httpReq = (window.XMLHttpRequest) ? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
// When it loads,
httpReq.onload = function() {
// Convert the result back into JSON
var result = httpReq.responseText;
document.getElementById("content").innerHTML = result;
};
// Request the page
try {
httpReq.open("GET", "parser.php?", true);
httpReq.send(null);
} catch (e) {
console.log(e);
}
}
parser.php
echo '<div data-collapse="accordion"><h1>Test title</h1><div>Collapsed content</div></div>';
The script is probably looking at the page at load-time so elements added after will not be affected by the script.
You will likely have to re-run the script after loading new content (which may or may not work), or find a better script that uses real-time DOM event handlers.
You will have to call jQuery Collapse after loading the content:
httpReq.onload = function() {
// Convert the result back into JSON
var result = httpReq.responseText;
document.getElementById("content").innerHTML = result;
$("#content").collapse();
};

XMLHttpRequest to the MongoDB simple rest interface

I am a beginner in both Ajax and MongoDB. I was hoping to visualize some of the data in my MongoDB using a web browser (which, for the moment, is running on the same host). For this, I thought it might be possible to get the data using XMLHttpRequests. I am running MongoDB with the --rest option and I checked that when I load hxxp://localhost:28017/test_db/ss_test/
on Firefox, I get the proper reply (a JSON document with the data in the ss_test collection of the test_db database). So far, so good.
I then wrote the following JavaScript function which I connected to the "onclick" of a button:
function makeRequest()
{
var myrequest = new XMLHttpRequest();
myrequest.onreadystatechange = function()
{
alert("status=" + myrequest.status + " readyState=" + myrequest.readyState)
if (myrequest.status == 200 && myrequest.readyState == 4)
{
// ...do something with the response
}
}
myrequest.open("GET", "http://localhost:28017/test_db/ss_test/", true);
myrequest.send();
}
So, when I load the html file on Firefox, open the console and click on my button, I see that the http request is indeed made, the status code is "HTTP/1.0 200 OK" and a response with Content-Length: 219257 is delivered, which looks great. However, the XMLHttpRequest object does not report the status=200. The alerts that pop up report a constant status of 0 as the readyState progressively becomes 1, 2 and 4 and my if statement is never true.
Could anyone please tell me what I am doing wrong? In the beginning I thought it was because my html was loaded on the browser by the file protocol or that I was seeing some same-origin policy related issue, but then I put the html file on a web server on localhost and loaded it from there and nothing changed. Thank you very much for any replies!
you need to create a function to handle the request.
http://www.ibm.com/developerworks/web/library/wa-ajaxintro2/
http://www.ibm.com/developerworks/library/wa-ajaxintro3/
function makeRequest()
{
var myrequest = new XMLHttpRequest();
myrequest.onreadystatechange = create_this_function()
{
}
myrequest.open("GET", "http://localhost:28017/test_db/ss_test/", true);
myrequest.send();
}
#
function create_this_function()
{
alert("status=" + myrequest.status + " readyState=" + myrequest.readyState)
if (myrequest.status == 200 && myrequest.readyState == 4)
{
// ...do something with the response
}
}

problem in refreshing the page after making two ajax calls

Problem I am making ajax call to server1 i.e. csce and once I got the response I am sending the response as contents to server2 i.e.yahoo server after getting response from there I want to refresh the page or atleast redirect it to the same page. Both ajax calls are working fine. The contents I am sending are also saved the only problem is that I have to manually refresh the page to see the changes. I want to refresh the page once the contents are saved on yahoo. I tried reload and redirect commands in success function of yahoo. But nothing works. I can see the both ajax calls in the HTTPfox but not the redirect.
The url from which i am making calls is different from the url where contents are saved thats why I need to refresh the page to see the changes. i.e. I am saving in yahoo/save while sending contents and seeing changes at yahoo/edit.
I am not sure where I am going wrong. Here is my code I am using. Can anyone suggest where I am going wrong. If my problem is not clear kindly do ask me to clarify more. Thanks.
This code is the code:
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
var substring=xmlHttp.responseText;
alert(substring);// I am able to see the text which is returned by the server1 i.e csce
var handleSuccess = function(o)
{
if(o.responseText !== undefined)
{
console.log(o.responseText);
**window.location.reload()** // also I tried to redirect it to the same site but that also not works
}
};
var callback ={ success:handleSuccess, failure: function(x) {
console.error(x) }, argument: ['foo','bar']};
var request = YAHOO.util.Connect.asyncRequest('POST','http://yahoo.com******', callback, substring);
}
}
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://cse*****id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
Do you just want to display the content in your page? Why don't you try something along the lines of document.getElementById('divID').innerHTML = xmlHttp.responseText;?
With divID being the id of a div that you want to fill the content with.
try following in the handleRequestStateChange function
window.location.href = window.location.href;

Categories