Jump to content

Calling a controller function from javascript


Go to solution Solved by Daniel F,

Recommended Posts

Posted

Thanks everyone who has helped me so far, I've been making good progress on my project.

Some context:

A phrase is extracted from the database and used in the javascript code - the phraseId is also sent via template parameters.

When the player wins or loses, I want to then call a controller method to set the results of the game they have just played, those parameters are likely to be something like:

{

  phrase_id: 1234,

  result: 1 // 0 = lose, 1= win

}

What is the best way to approach this?  Initially I thought I could use ajax to call the function like so (passing in phraseId and result):

this._ajaxObj = ips.getAjax()( 'index.php?app=game&module=gameplayh&controller=gameplayh&do=endGame ', {
    data: {
        phraseID: 1234,
        result: 1
    }
})
    .done( function (response) {
     
    });

But I am not sure how to return a simple "ok/true/false/whatever" from my php function? I have this code but I am doubtful about it:

public function endGame () {
  if (isset(\IPS\Request::i()->phraseId) && isset(\IPS\Request::i()->result)) {
    # do something with phraseId and result here, write to database etc.
  }
}

I do not have to return a redirect as the user will trigger a new game using a button click (so they can view their results in the meantime).

Thanks for any advice 🙂

  • Solution
Posted

Your approach seems to be fine.
if request::I()->foo ... do something...

 

 

You can also just return a simple "OK" by using

if( \IPS\Request::i()->isAjax() )
			{
				\IPS\Output::i()->json( 'OK' );
			}

If you want to see the full working code, take a look at e.g. applications/core/modules/front/contact/contact.php

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...