Reputation: 183
I am trying to get my data from a query string, but use it with Ajax. I cant seem to get the data passed correctly and I am wondering where my syntax is wrong:
$(function()
{
$("#link").click(function(event)
{
event.preventDefault();
$.get("request.php",{id:+link.attr('id')},function(response){
$("#ajaxresponse div").fadeOut("fast", function()
{
$("#ajaxresponse div").remove();
$("#ajaxresponse").append($(response).hide().fadeIn());
});
}
});
return false;
});
});
The html page code:
<div class="content">
<a href="request.php?id=1" id="link">
</div>
Am I not structuring the data to the ajax call correctly??
Thanks in advance
I can get it to return properly, but not in Ajax fashion, it is still loading the .php page instead of appending it, here is the request.php side of things:
$username = $_GET['id'];
echo getTemplate($username);
function getTemplate($username)
{
return '<div class="box">
<h1>ID is</h1>
<div class="meta">username: '.$username.'</div>
</div>';
}
Upvotes: 1
Views: 755
Reputation: 15338
add this function outside any other function :
function getUrlVars(url){
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
then use :
getUrlVars($(this).attr("href"))["id"]
instead of
link.attr('id')
demo : http://jsfiddle.net/zY9s2/
Upvotes: 0
Reputation: 13461
You can use a utility function like this
function getParameterByName(name,url) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(url);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
and then use it in your code use it like
$("#link").click(function(event)
{
event.preventDefault();
var id = getParameterByName('id',$(this).attr('href'));
$.get("request.php",{id:id},function(response){
Demo: http://jsfiddle.net/joycse06/dPX2h/
Upvotes: 1