1

I have the following code within the <script> tags, which are within the <head> tags of my HTML file;

function generateUMR($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
} 

Within the <body> tags, I have the following line of code in order to output the randomly generated string;

echo '<script type="text/javascript"> generateUMR(); </script>';

I have been trying for a few hours now but I am receiving no output from this code, yet no errors, could someone please tell me where I am going wrong?

Thanks in advance.

4
  • In javascript string concatenations is done with + operator, not with . like in php. it should be $randomString += .... also consider declaring the variables with var $characters. If you don't do the variables will go to the global scope which could cause troubles in the future. Commented Jun 25, 2014 at 13:07
  • @IgorMalyk: That code block is php. (strlen($characters) and the dollar-sign variables are a big hint) Commented Jun 25, 2014 at 13:09
  • So how do you call a function in PHP from javascript ? Commented Jun 25, 2014 at 13:10
  • possible duplicate of Generate a string of 5 random characters in Javascript Commented Jun 25, 2014 at 14:55

1 Answer 1

5

Your function is treated as a string, you need to concatenate the function call like so.

echo '<script type="text/javascript"> ' . generateUMR() . ' </script>';

In order to see the result in the browser, you will need to view the HTML source because the browser won't show the content of a script tag. It doesn't really make sense to output this into a script tag, because it's just a random string, try some other tag such as <p></p> instead.

If you are trying to call the PHP function from the client side, then that won't work. You'll need to use AJAX to do that.

Sign up to request clarification or add additional context in comments.

8 Comments

I altered my code as you suggested but still no output :(
... and no one noticed that generateUMR is a PHP function... :)
@user3266484 what kind of output are you expecting? your PHP function will just output a random string, no JS logic...
For some reason I can't comment on Reinder Wits comment below, but when I tried his suggestion I got this error - Fatal error: Call to undefined function generateUMR(), any ideas? Thanks for ye're help so far anyway..
I just want it to output the random string so that I can ensure it is working before using in it my furthur code..but it seems the function is outputting nothing?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.