stevengreen22 Posted August 10, 2013 Share Posted August 10, 2013 Hi all, This problem is killing me. I hope / pray someone can help. Essentially I need to pass a JS variable to a PHP variable without refresh/form submission or redirecting. I'm new to Ajax so please be patient The owner of this site generally lives in 3 countries lucky ******. When he logs in he wants the contact page updated with his current number. I have a form with hidden fields that return the address location using an ajax call to ipinfo.io - this works fine. <script> $(function() { var admin = <?php echo json_encode($admin->isAdmin($user['username'])); ?>; var phone=""; if(admin == true){ $.ajax({ url:"http://ipinfo.io", dataType:'jsonp' }) .success(function(response){ $("#address").val(response.country); $("input[id=address]").val(response.country); var testLoc = $('#address').val(); if(testLoc == "GB"){ phone = "<?php echo $gb?>"; $("#phone").append(phone); }else if(testLoc == "GABON"){ phone = "<?php echo $gabon?>"; $("#phone").append(phone); }else if(testLoc == "THAILAND"){ phone = "<?php echo $thai?>"; $("#phone").append(phone); } }); var time = new Date(); $("#localTime").append(time); }else{ //alert("Not Admin"); $("#phone").append(phone); } }); </script> The above essentuially checks to see that he is THE admin, if it is it then sets the hidden field value to be the country, that is then placed in the testLoc variable and depending on what it is, it spits out the number. This all works well unless of course you visit the site and you're not the admin. All you see is an empty string. I need to get that phone variable or location variable, either of them really from the js into a php variable. That way when a normal joey visits the page I can just echo out that variable instead. phone or location var in js script to php variable? Quote Link to comment https://forums.phpfreaks.com/topic/281026-pass-js-variable-to-php-variable-please-save-me/ Share on other sites More sharing options...
kicken Posted August 10, 2013 Share Posted August 10, 2013 Rather than complicate this process with JS and AJAX, just do the lookup to ipinfo.io using PHP before the page loads. If fopen wrappers are on, a simple file_get_contents call will suffice. Otherwise you can use CURL <?php $phones = array( 'GB' => 'blah , 'GABON' => 'foo' , 'THAILAND' => 'bar' ); $url = 'http://ipinfo.io/'.$_SERVER['REMOTE_ADDR'].'/country'; $country = file_get_contents($url); var_dump($country, $phones[$country]); Quote Link to comment https://forums.phpfreaks.com/topic/281026-pass-js-variable-to-php-variable-please-save-me/#findComment-1444334 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.