September 10, 2013

how to get php variable in javascript

User2746093’s Question:

I want to get value of $security_code which is in captchaCode.php file, in captcha.php file through javascript.I can not include this file in captcha.php file . Here is the code of Captcha_code.php and this code not comes inside any function of this file:

$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));

And here is my javascript function, through this function i want to get the value of $security:

function refresh_captcha()
{
    var img = document.getElementById('captcha_img');
    img.src = '<?php echo "/captcha_images.php"?>';
    jQuery("#captcha_img").attr("src",img.src);
    jQuery("#security_code").val("<?php echo $security_code;?>");
}

Actually this code is for getting new encrypted value when captcha is refreshed without refreshing the page.

Send an ajax request to a page to output only the code like:

File: outputcode.php (demo only)

$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));
echo $security_code;
exit;

Next, grab that value using AJAX, like for example in jQuery

$("#refresh_code").on('click', function() {
   $.get("outputcode.php", function(data) {
      //data will now hold the new code
   });
});

Hope this gives you an idea.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!