简体   繁体   中英

Passing location variable from Javascript to PHP function

I'm using HTML5 geolocation and Javascript to do a reverse geolocation lookup with Google's API to get the town of the user. This all works fine, and I have the city/town stored in a JavaScript variable named city.short_name .

Now, I'm using wordpress and I'm trying to modify part of the content of my site using:

document.getElementById('contenttochange').innerHTML = <? echo do_shortcode('[<code here>]'); ?>;

Now if the content was just the same all the time, ie

<? echo do_shortcode('[just_do_this]'); ?>

it would be fine, but unfortunately I need to add the town as a parameter called search . Eg

<? echo do_shortcode('[just_do_this search="thetownofuser"]'); ?>

So, essentially, once I've found out the town and have it as a variable, is there any easy way for me to execute the PHP shortcode with that town as a parameter to replace the content I wish to?

PHP is a Server-side Hypertext Preprocessor (actually the roots of the acronym "PHP"). You cannot execute PHP from javascript, because PHP is not "active", to put it in one word.

You send data to the server running PHP as a request , it gets processed through PHP, and out comes XHTML. All those <??> are rendered to their outputs before they are even sent to the client.

The client ONLY deals with XHTML and Javascript (among other things, but for simplicity's sake)

You can echo variables into your javascript, sure, because it is rendered to the document that is sent out the the client. Once it reaches the client, PHP can no longer be used.

To send a variable to your PHP script, you will need to make an AJAX call and send the location variable as a part of your request.

Alternatively, you could create a PHP script that has it's header's content-type set to text/javascript that takes in the variable in $_GET , and include it like so:

<script type="text/javascript" src="setLocation.php?loc=<?= do_shortcode(/* Whatever */) ?>">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM