简体   繁体   中英

How can I use jQuery variable inside PHP tag

country value from jQuery variable need to insert into URL with PHP encrypt function, how can I use jQuery value into PHP

$("#country_select").change(function(){
    var country = $("#country_select").val();

$(".price_content a").attr("href","signup.php?pack=<?php echo encrypt(2,$key);?>&country="<?php echo encrypt(country,$key);?>);

});

need to add var country into encrypt function...

How can i use?

Your PHP code will only be executed once on the server side when the page is requested. It will not be called again in the change event.

Possible solutions:

  • Do an ajax call to encrypt the value, in the change event
  • Encrypt all values of the select and store them in a data-encrypted attribute in each option
  • Encrypt the values and store them as a Javascript array for lookup later

there is no way you can do this directly. It's because PHP is processed before JQuery. PHP on server side, JQuery on client side.

You can use encodeURIComponent as proposed here .

However, if you still insist on processing parameter via PHP, you can still make ajax call to PHP script with input parameter - your desired string to be encoded and PHP will output you encoded string.

Here is your solution:

<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

<script type="text/javascript">
// extend jQuery Ajax and change it
$.extend({
    getValues: function(url, qs) {
        var result = null;
        $.ajax({
            url: url,
            type: 'post', 
            data: qs,           
            async: false,
            success: function(data) {
                result = data;
            }
        });
        return result;
    }
});
$(function(){
    $("#country_select").change(function(){
        var country = $("#country_select").val();
        $(".price_content a").attr("href","signup.php?pack="+$.getValues("encrypt.php",{q:'2'})+"&country="+$.getValues("encrypt.php",{q:country}));
    });
})

</script>
<select name="country_select" id="country_select">
    <option value="">Select country</option>
    <option value="IND">India</option>
    <option value="SL">Sri Lanka</option>
    <option value="PAK">Pakistan</option>
</select>

<div class="price_content"><a href="">Click</a></div>

Well, PHP is a server-side language, and Javascript is client side, which means, you can't pass variables to php without a post. You can use an AJAX post, if you don't want to refresh the page. On the other hand, it is fairly easy to use PHP variables in jQuery, so if that is reasonable for your work, you should consider that.

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