Jump to content

Getting an HTTP Response using AJAX


mtorbin

Recommended Posts

Morning folks,

 

I'm trying to transfer my knowledge of php to ajax to accomplish what I believe should be a very easy goal.  I am trying to get the contents of an html page loaded into a variable.  Normally I would have done this with PHP but in this case, I really need to use AJAX or the Prototype.js framework to accomplish this.  Here's what I'd like to do in PHP:

<?php
   $myURL = "http://tinyurl.com/api-create.php?url=http://www.phpfreaks.com/";
   $myContents = file_get_contents($myURL);
?>

 

Can something like this be done in AJAX?  I've been looking for tutorials but they don't quite cover (from what I've read) what I want to do.

 

Thanks,

 

- MT

Link to comment
https://forums.phpfreaks.com/topic/197858-getting-an-http-response-using-ajax/
Share on other sites

I've never used the prototype framework (usually jQuery) but found this within about 10 seconds on there site.

 

new Ajax.Request('/your/url', {
  onSuccess: function(response) {
      // yada yada yada
  }
});

 

Its probably best to at least check the manual of the framework your using before wasting your time waiting for a response on a forum.

I definitely checked that but it didn't seem to do what I wanted it to do.  I was able to get back the responseText and status, but not the HTML of the actual page.  Here is the quick script I tested yesterday:

<script type="text/javascript">
		new Ajax.Request('http://tinyurl.com/api-create.php?url=http://www.phpfreaks.com/', {
			onSuccess: function(response) {
				alert(response.responseText.length);
			}
		});
	</script>

 

response is an object and the attribute that seemed most appropriate was responseText.  As you can see it's returning a length of zero.

 

- MT

In case anyone is wondering, I was able to figure it out using jQuery and an open API (though I'd rather use the tinyurl api instead):

<html>
<head>
	<script type="text/javascript" src="jQuery.js"></script>
</head>
<body>
	<div id="result"></div>
	<script type="text/javascript">
		function TweetThis(bigurl){
			$.getJSON(
				"http://json-tinyurl.appspot.com/?&callback=?",
				{url: bigurl},
				function(data){
					alert(data.tinyurl);
				}
			);
		}
		TweetThis("http://www.phpfreaks.com/");
	</script>
</body>
</html>

 

Now I just need to convert this to prototype.js and I'm most of the way there.

 

- MT

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.