0

I have a php script that I'm trying to trigger with Javascript. I'm trying to set the URL dynamically with php using a variable but am not having any luck, does anyone know how I should approach this?

<a href="#" onclick="return getOutput();">Click here</a>

<?php $update_url = 'https://' . $_SERVER['SERVER_NAME'] . '/xyz.php'; ?>

function getOutput() {
  getRequest(
    var str = "<?php echo $update_url ?>", // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
}
5
  • 3
    You have a syntax error. var str = Commented Jul 5, 2016 at 7:47
  • would the url not be a sting? Commented Jul 5, 2016 at 7:47
  • It should be an string, but it looks to me that you're passing 3 arguments to getRequest() function, so you cannot have var str = there. You could define it some where else or directly pass it Commented Jul 5, 2016 at 7:49
  • var is a statement, not an expression. You can't use statements as arguments. Commented Jul 5, 2016 at 7:49
  • just remove 'var str = '. as Adam Azed told. Commented Jul 5, 2016 at 7:50

2 Answers 2

1

Here's what you can do; pass the PHP value as an string.

<?php $update_url = 'https://' . $_SERVER['SERVER_NAME'] . '/xyz.php'; ?>

function getOutput() {
  getRequest(
       "<?php echo $update_url ?>", // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
}

OR

Define as JavaScript value in the global scope (this may not work)

var updateURL = "<?php $update_url = 'https://' . $_SERVER['SERVER_NAME'] . '/xyz.php'; ?>";

function getOutput() {
  getRequest(
       updateURL, // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can't have var str = as a parameter to a function(). You can't write

functionName(var a='a', b); // this will not work

This is a way to solve that:

function getOutput() {
  var str = "<?php echo $update_url ?>"; // URL for the PHP file
  getRequest(
       str,
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
}

and this way is shorter:

function getOutput() {
  getRequest(
       <?php echo $update_url ?>, // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
}

Comments

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.