Reputation: 183
I am trying to do a simple AJAX function to send data from query string, and the append the DIV. .I have tried a variety of different methods, but none that will updat the div. If it updates, it returns NULL, otherwise it just goes to the request.php page. If I move the prevent default function under the click event, it does nothing. Any help would be appreciated!! TIA
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function()
{
$("#link").click(function(e)
{
$.ajax(
{
type : "GET",
url : "request.php",
data : { id: link.attr('id') },
success : function(response)
{
$("#ajaxresponse div").fadeOut("fast", function()
{
$("#ajaxresponse div").remove();
$("#ajaxresponse").append($(response).hide().fadeIn());
});
}
});
e.preventDefault();
});
});
</script>
</head><body>
<h1>
AJAX with PHP
</h1>
<div class="content">
<a href="request.php?id=1" id="link" data-id="1" >Submit Link</a>
</div>
<div id="ajaxresponse">
<div>please submit the form</div>
</div>
The request.php is as follows:
<?php
$username = $_GET['id'];
echo getTemplate($username);
function getTemplate($username)
{
return '<div class="box">
<h1>The ID is</h1>
<div class="meta">username: '.$username.'</div>
</div>';
}
?>
Upvotes: 0
Views: 1426
Reputation: 218702
I guess you are trying to read the id value of the link being clicked in a wrong way. This should work.
$(function()
{
$("#link").click(function(e)
{
var link=$(this);
e.preventDefault();
$.ajax(
{
type : "GET",
url : "request.php",
data : { id: link.attr('id') },
success : function(response)
{
$("#ajaxresponse div").fadeOut("fast", function()
{
$("#ajaxresponse div").html(response).fadeIn();
});
}
});
});
});
You can even use the get
method which is a short version of jQuery ajax call with method type as GET
.
$(function()
{
$("#link").click(function(e)
{
var link=$(this);
e.preventDefault();
$.get("request.php?id="+link.attr('id'),function(response){
$("#ajaxresponse div").fadeOut("fast", function()
{
$("#ajaxresponse div").html(response).fadeIn();
});
});
});
});
Upvotes: 1