Alicia Brandon
Alicia Brandon

Reputation: 575

Concatenation of php variable with javascript

var settings = {
  "async": true,
  "crossDomain": true,
  "url": 'https://example.com/something.aspx?i='<? echo urlencode($_GET['id']); ?>,
  "method": "GET",
  "headers": {
    "cache-control": "no-cache",
  }
}

It doesn't work this way, the concatenation is wrong I think. Tried few ways still doesn't work.

Upvotes: 1

Views: 513

Answers (3)

DBX12
DBX12

Reputation: 2041

Maybe you can try it the other way round. Like

<?php
  echo 'var settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://example.com/something.aspx?i='.urlencode($_GET['id']).'",
    "method": "GET",
    "headers": {
      "cache-control": "no-cache",
    }
  }'; 
?>

Please note the changes I made with the ' and " in the url attribute.

Upvotes: -1

Jamie Bicknell
Jamie Bicknell

Reputation: 2326

You just had the single quote the wrong side.

Don't forget you're outputting to HTML, so you don't have to concatenate a PHP variable to a JavaScript variable.

var settings = {
  "async": true,
  "crossDomain": true,
  "url": 'https://example.com/something.aspx?i=<?php echo urlencode($_GET['id']); ?>',
  "method": "GET",
  "headers": {
    "cache-control": "no-cache",
  }
}

Upvotes: 3

Quentin
Quentin

Reputation: 943207

You need to put the data inside the JavaScript string literal. Move the ' to after the extra data you are outputting.

Upvotes: 5

Related Questions