Use jQuery to update the database through Joomla MVC component

I am developing a new version of my TOMTV component for Joomla. I am trying to set up a rating system using the jQuery stars plugin. I have a problem with the noconflict jQuery problem, but I'm a bit confused about how to send a voice safely to a helper class that updates the database with a voice value.

This is usually done through an external script, which is available only for each ajax request. I would like to do this so that it is included in my component and so that the Joomla std variables are available for the helper class, for example. getDBO () and database link #__ table_name.

Any comments on how to achieve this would be greatly appreciated. Thank.

+3
source share
1 answer

This is pretty straight forward.

First you need to create a controller with a specific task that processes your rating update. To ensure security, confirm the token! The token will arrive with an AJAX request.

Consider this example

function rate() {
    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    //  Get ID of item
    //  update rating, etc...
}

Second, create your AJAX request in a view explicitly called by some action. Be sure to send your request as a POST, because you are going to write data ... You can either have a script in an external document receive values ​​from an html document (id, token, url, etc., which are in hidden inputs), or you can generate javascript with PHP and include it in your head (as in the example below).

<?php
//
$url = JRoute::_('index.php?option=my_component&controller=my_controller');
$token = JUtility::getToken();  //  <-  Session token
$id = 101;  //  <-  YOUR ID

//  This will add the request to the head of the document, instead of somewhere in the document
JFactory::getDocument()->addScriptDeclaration("
    .ajax({
        type: 'POST',
        url: $url,
        data: {
            '$token': '1', // <-- THIS IS IMPORTANT
            'task': 'rate',
            'id':  $id
        },
        success: youSuccessFunction
    }); 
");
?>

, AJAX MVC.

. JRequest::checkToken('get'), URL-. AJAX, .

+4

Source: https://habr.com/ru/post/1770719/


All Articles