-1

I am trying to formulate a URL to use to set the src property of an img control. I first build a file path passing PHP to a javascript variable:

var image_path_name = "<?php $path = VENUE_IMAGES_PATH . DS; echo (string) $path; ?>";

When I look at the page source, this shows up as:

var image_path_name = "http:\\127.0.0.1\where2bwho2c\w2bw2c-admin\public\images\venues\";

This looks correct, but I am getting a "Invalid or unexpected token" error on this line of code.

If I do a console.log with the PHP,

console.log(<?php $path = VENUE_IMAGES_PATH . DS; echo (string) $path; ?>);

I get an "Uncaught SyntaxError: missing ) after argument list" error. How can I build a valid URL without getting these errors?

  • 3
    Your slashes are wrong. You need to escape the string. – SLaks Jan 10 '18 at 16:18
  • 1
    The last backslash character means the closing quote is not taken as the end of the string. The backslashes are all wrong anyway; for URL syntax they need to be forward slashes. – Pointy Jan 10 '18 at 16:18
  • Some servers use the backward slash as a delimiter. The point of the PHP constant DS is that it is set by getting the delimiter being used by the server. In javascript, what do you mean by "escape the string"? Or should I do so in PHP first before passing it to the javascript variable? – Russell Eubanks Jan 10 '18 at 16:23
  • 4
    `http:\\...` is _never_ valid. – SLaks Jan 10 '18 at 16:24
  • 2
    *Some servers use the backward slash as a delimiter.* an URL is **not** a filesystem path - URLs always use `/` – CD001 Jan 10 '18 at 16:25

2 Answers2

1

var image_path_name = "http:\127.0.0.1\where2bwho2c\w2bw2c-admin\public\images\venues\";

The slashes are in-correct here and console log with "< ?php ? >" does not make sense because the php part should be evaluated in the backend, not in the browser.

Arun Selin
  • 603
  • 4
  • 11
-1

Use:

var image_path_name = <?php $path = VENUE_IMAGES_PATH . DS; echo json_encode($path); ?>;

I would create the path before and check that it is valid. If not, you could get garbled JavaScript.

jotaelesalinas
  • 1,387
  • 1
  • 11
  • 24
  • Can somebody tell me, please, why the downvote? I always use `json_encode()` to output values in JS code. It works for strings, integers, arrays, etc. Am I doing it wrong? Is there a better way that I should be aware of? – jotaelesalinas Jan 16 '18 at 10:13