I have this list of things generated from an array, where the array value maps to the array key, which maps to a query in the database. Now the problem I’m facing is that when this list is included in my ajax portion, it only works for one click before the page refreshes. What gives?
I’m using the HTML5 History API method to change the url upon clicks by the href=”” portion of the link.
I’m somewhat new to jQuery, which is odd since I’m a front end developer primarily but I just never got the time to catch up, but my link list breaking this code just doesn’t make sense to me.
$("a[rel='ajax']").click(function(e){
//e.preventDefault();
pageurl = $(this).attr('href');
$.ajax({url:pageurl+'?rel=ajax',success: function(data){
$('#ajax')
.load(pageurl + ' #resultati');
}});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
The links are generated using this function in PHP, I’m using the laravel framework if that makes any difference.
public static function filterlink ($filter, $what)
{
if (URI::segment(2) == 'make')
{
$first = URI::segment(3);
$next = URI::segment(4);
}
else
{
$first = URI::segment(2);
$next = URI::segment(3);
}
// what == 0 is the filter, what == 1 is the +filter. This reffers to the link being created.
switch (substr($first, 0, 1))
{
case ' ': // example.ex/make/[+]current starts with a plus sign.
if($what == 0)
//new no+ filter.
{
return HTML::link('make/'.self::slug($filter.'/'.$first), $filter, array('rel' => 'ajax'));
// example.ex/make/+current => example.ex/make/newfilter/+current
}
elseif($what == 1)
//new +filter
{
return HTML::link('make/+'.self::slug($filter), $filter, array('rel' => 'ajax'));
// example.ex/make/+current+replaced+by+newfilter
}
break;
default:
if($what == 0)
// new no+ filter.
{
if(!empty($next))
{
return HTML::link('make/'.self::slug($filter.'/'.$next), $filter, array('rel' => 'ajax'));
}
else
{
return HTML::link('make/'.self::slug($filter), $filter, array('rel' => 'ajax'));
}
}
elseif($what == 1 && (!empty($first)))
{
return HTML::link('make/'.self::slug($first.'/+'.$filter), $filter, array('rel' => 'ajax'));
}
elseif($what == 1 && (empty($first)))
{
return HTML::link('make/+'.self::slug($filter), $filter, array('rel' => 'ajax'));
}
}
}
I’ve tried putting my link lists outside the ajax field, which keeps the ajax flow going without any boring page refreshes, but my link urls don’t update, obviously, and I’m only able to construct one-ended links, breaking the pages dual filter functionality.
Any help would be great.
If you’re actually loading HTML content with links that you want to be AJAX friendly, then you’ll need to use .on so that the new links also get taken over by your jQuery function.
Working sample here:
http://jsfiddle.net/hansvedo/cJW54/
Just a quick thought, what about placing preventDefault where the pushState function is? Or even just uncommenting it where it is? preventDefault prevents the normal linking action from happening.