2

I found some portions of codes but I don't know how to complete it. I need to pass some variables via ajax to controller in order to store them in Joomla session. So I have the code:

<input type="text" name="id" value="2" />

$('.add').click(function() {
 $.ajax({
  method: "POST",
  url: "index.php?option=com_mycom&task=add&format=raw",
  data: {id:1},
  dataType: 'json'
 }).done(function() {
   alert("Data Saved");
  });
 return false;
});

and the code in controller:

public function add() {
    $session = JFactory::getSession();
    $value = ???
    $cart = array();
    $cart['item'] = array('id' => $value);
    $session->set('cart', $cart);
}

As you see I don't know how to get data in the controller (and I'm not sure that I send it properly in $.ajax). And do I really need json in my case?

9

You should use Joomla's JInput class https://docs.joomla.org/Retrieving_request_data_using_JInput

e.g.

public function add() {

  // Get Joomla's input object:
  $input = JFactory::getApplication()->input;

  // Get the variable
  $value = $input->get('id');

  $session = JFactory::getSession();
  $cart = array();
  $cart['item'] = array('id' => $value);
  $session->set('cart', $cart);
}
1

Yes you want to use the input.

$input = JFactory::getApplication()->input;    
$value = $input->get('id');
  • Thanks Lodder, I was posting from my phone and didn't get the styling right. – Mathew Lenning Apr 24 '15 at 11:10
-1

Try

$value = $_POST['id'];

That's like the easy approach, might not be best practice any more though. I would recommend this for testing purposes only, it delivers fast results but is not really safe. For that I recommend looking into the JInput class as mentioned by the other answer.

As for the JSON question, I just found this post which has some answers explaining it quite well I guess.

  • Okay... I am willing to delete my answer if somebody could explain me why they keep downvoting me. To my experience, this works, and I just answered the question. Thanks! – elk Apr 18 '15 at 12:07
  • 1
    theres not input filtering - so you are opening yourself up to SQL injection attacks if you then used $value inside a database query. For example someone could post : id = "');delete * from table;". And if you didn't sanitize the input and wrote a query $query->update('table')->set('foo = "' . $value . '"'); your query would be written out as : update table set foo = "');delete * from table;" – Rob Clayburn Apr 23 '15 at 15:46
  • @Rob, yes, I know that - that's why I put "for testing purposes" ;-) thanks for your reply though. – elk Apr 23 '15 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.