2 Replies - 1706 Views - Last Post: 30 October 2011 - 02:58 AM

#1 56KBs  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 17-January 11

Click anchor to load AJAX

Posted 29 October 2011 - 04:28 PM

Hey D.I.C,

I've been learning AJAX for the past hour or so, trying to get this code to work but it doesn't seem to want to know.

<script type="text/javascript">
	$('a.fire').click(call_ajax);
	function call_ajax() {
		$.ajax({
			type: "GET",
			url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
			dataType: "html",
			success: function(html){
				$("#holder").append(html);
			}
		});
	}
</script>


Other methods I have tried seem to call the ajax function I create before the anchor is clicked (All the ajax must be working as it would load before I wanted it to!)

I have put an alert just at the start of the function, and it is calling it, just my ajax section isn't working correctly, or at least not returning anything.

Is This A Good Question/Topic? 0
  • +

Replies To: Click anchor to load AJAX

#2 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: Click anchor to load AJAX

Posted 29 October 2011 - 05:53 PM

Hi,

You could just wrap the AJAX call into an anonymous function that gets called on the click event of your element. You can supply a function to handle a a failed AJAX call as well:
<script type="text/javascript">
	$('a.fire').click(function(){
		$.ajax({
			type: "GET",
			url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
			dataType: "html",
			success: function(html){
				$("#holder").append(html);
			},
			error:function(xhr, text, error){
				alert("Error: " + text);
			}
		});
	});
</script>



I also suggest you get Firebug or something like it. The console can be very useful in troubleshooting AJAX calls. Hope this helps :)
Was This Post Helpful? 0
  • +
  • -

#3 56KBs  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 17-January 11

Re: Click anchor to load AJAX

Posted 30 October 2011 - 02:58 AM

I have now got the same code as you, on click I now get the alert "Error: error", I am unsure if this is because of my URL being incorrect. I've tried a direct URL and just get the same thing, the same happens with relative URL's


EDIT: I have now got it to work! For some reason my anchor had a href of "", which would cause it to reload the page and removing my GET from the page

This post has been edited by 56KBs: 30 October 2011 - 03:05 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1