• Hi,

    I’m developing a small wheel of fortune like game with WordPress.

    So far things are going well as I have created a shortcode to show the js wheel and its spins when clicked and calls the php code that determines the RNG (as you don’t want the client to be able to edit their js to come up with that number)

    Now I got the random number from the php function called by the ajax, but to give out a reward, I’d like to know what the multiplier or reward value that was set by the shortcode like [wheel-game bet=100 win=1000]

    So I’d like to know both what the bet and win attributes were from the shortcode of the other function.

    I’ve saw some stack exchange post with similar issues suggesting static variables or having the shortcode write itself to SQL and then the AJAX php ask SQL, but I feel like that will be resource intensive and open to more security issues.

    I also thought maybe the shortcode function could just to see if ajax is post, but I feel like that version of the function being called by AJAX may not have knowledge of what the shortcode attributes were on that page.

    And to complicate things further I suspect this game may have more than one on a page or multiple pages.

    Any general practices with shortcodes and php called by ajax?

    Thanks!

    • This topic was modified 7 years, 5 months ago by Felty.
Viewing 3 replies - 1 through 3 (of 3 total)
  • In the PHP shortcode handler, which outputs the js wheel, call wp_localize_script to put the values from the shortcode into the js.
    https://developer.ww.wp.xz.cn/reference/functions/wp_localize_script/

    Moderator bcworkz

    (@bcworkz)

    Joy’s replies are generally spot on, but in this case, I think she’s a bit off. It’s too late to call wp_localize_script() if it’s called from a shortcode handler. If it weren’t for that, it would be excellent advice.

    What localize script does is output a script block in a page’s head section assigning PHP values to JS variables. What you could do is have your shortcode handler include its own script block in its returned HTML that assigns attribute values to JS variables. Your Ajax call can then pass along these variable’s values as part of the Ajax request. It’s not a very good place for a script block, but it should work. You could instead set the values as data-* attributes in a particular HTML element which your JS can extract and pass along in the Ajax request.

    I think I like the latter option better as it avoids awkward script blocks.

    True that wp_localize_script is called for the head section, but not all scripts have to go into the head section. But I like the data attributes idea too.

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Shortcode code to ajax back back to php question’ is closed to new replies.