NYCPHP Meetup

NYPHP.org

[nycphp-talk] Can Javascript call a PHP program and read the results?

John Campbell jcampbell1 at gmail.com
Tue May 31 10:15:46 EDT 2011


I really doubt google's ip-> location database is broken that badly,
but if you do want to do this, I recommend something like the
following:

javascript:

<script>
$.getJSON('http://myserver.com/getlocation.php?callback=foobar',function(location)
{
   if(location.country == 'US')
      // do something with `location`
});
</script>

php:

<?php

$location = getLocation($_SERVER['REMOTE_ADDR']);

echo $_GET['callback'] . '(' . json_encode($location) . ');';



The code I wrote above uses JSONP to get around cross-domain issues.

Regards,
John Campbell

On Mon, May 30, 2011 at 2:42 AM, David Roth <davidalanroth at gmail.com> wrote:
> I'm using Tumblr.com for a blog platform for a new website. It has a lot of
> benefits as a blog, but it also has the restriction of not being able to
> embed PHP code in the HTML theme template. (Yes, I know, my feelings
> exactly! :-) )
>
> But Tumblr does support Javascript. What I'm trying to do is get the county
> code of the user so that different links can be presented to them that
> matches their country. Serving up different links based on the country code
> would be handled by Javascript.
>
> There is a Javascript Google library jsapi, but it doesn't work properly for
> county code. For example,  I'm in the New York City metro area and it says
> I'm in Canada, not the US. I don't recalling having this kind of problem
> with PHP scripts, so I'd like to use a PHP script. But I don't know of a way
> in JavaScript to be able to call a PHP script and make the result accessible
> with the Javascript so it can serve up the correct country links.
>
> I admit I've not done much Javascript programming compared to PHP, so I'm
> not sure if I'm overlooking something. Maybe this is a AJAX and jQuery task?
> I'd appreciate it if someone could offer a workable solution.
>
> Thanks in advance!
>
> David Roth
>
> _______________________________________________
> New York PHP Users Group Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> http://www.nyphp.org/Show-Participation
>



More information about the talk mailing list