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?

3 Answers 3

10

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); } 
0
1

Yes you want to use the input.

$input = JFactory::getApplication()->input; $value = $input->get('id'); 
1
  • Thanks Lodder, I was posting from my phone and didn't get the styling right. Commented Apr 24, 2015 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.

3
  • 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! Commented Apr 18, 2015 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;" Commented Apr 23, 2015 at 15:46
  • @Rob, yes, I know that - that's why I put "for testing purposes" ;-) thanks for your reply though. Commented Apr 23, 2015 at 16:31

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.