Reputation: 1681
I am trying to create an ajax function with all the data inside the following variable inside the following function: $item
public function onK2AfterDisplayContent(&$item,&$params,$limitstart)
{
$view = JRequest::getVar('view');
if($view === 'item'){
$db = JFactory::getDbo();
$query = 'SELECT name FROM #__k2_categories WHERE id='.$item->catid;
$db->setQuery($query);
$resultado = $db->loadResult();
echo '<input class=subscribete type=button id='.$resultado.'-'.$item->id.' value="Subscribete" />';
}
}
Im not sure if instead of using a <button>
I should use an html link. The variable $item
is an object with a lot of information which I want to take to my AJAX for later treating this data...
Upvotes: 2
Views: 2087
Reputation: 5727
You can use either the anchor or the button element, it depends on your requirement. User always expect web page will direct to another page or popup something after click anchor and trigger a action (form submit, show/hide content...etc) after click a button. Please note you should call event.preventDefault() in click event handler in order to avoid appending unnecessary "#" to url when you're using anchor element as a AJAX caller.
Then you need to store the AJAX call required data to DOM by using custom data attribute in PHP. (Assume that you only need the ID of $item)
public function onK2AfterDisplayContent(&$item,&$params,$limitstart)
{
$view = JRequest::getVar('view');
if($view === 'item'){
$db = JFactory::getDbo();
$query = 'SELECT name FROM #__k2_categories WHERE id='.$item->catid;
$db->setQuery($query);
$resultado = $db->loadResult();
//add required data to DOM
echo '<input class="subscribete" type="button" id="'.$resultado.'-'.$item->id.'" value="Subscribete" data-id="'.$item->id.'"/>';
}
}
Final step, register the click event handler of DOM which will trigger a AJAX call.
$(function(){
$(".subscribete").click(function(e){
if(this.tagName==="A"){
e.preventDefault();
}
//$(this).data("key") will return the value at the named data which is set by HTML5 data-* attribute
$.ajax({
url: "http://path.to.ur/url",
type: "POST",
data: {id:$(this).data("id")},
success: function(response){
alert(response);
},
error: function(jqXhr,status,error){
alert(error);
}
});
});
});
Upvotes: 1
Reputation: 906
Yes you can use the link in the following way: - on your link you can write
<a href="#" onclick="function()">...</a>
Upvotes: 0