user1931339
user1931339

Reputation: 27

Using PHP variable and use it in Jquery/Ajax page load request

Let's say I have set up a PHP variable like this:

$phpurl = $_GET["url"] 

where url value will be from GET variable query. The value of "url" will be some sort of html page link with some content like "myContent.html" I want to load.

How can I get this "url" value, which I have assigned to the variable "$phpurl" and use it in the Ajax/Jquery page load request?

$('.content').load('  ** need the value of "$phpurl" to be placed here ** ');

Hope the question is clear. I am pretty new into programming. Thanks.

Upvotes: 3

Views: 841

Answers (3)

maček
maček

Reputation: 77826

You'll want to take precaution to escape the value properly

<script type="text/javascript>
  var url = decodeURIComponent('<?php echo rawurlencode($phpurl) ?>');
</script>

Or you could try something like https://github.com/allmarkedup/jQuery-URL-Parser

// requires no PHP at all!
var url = $.url(window.location).attr('url');
$('.content').load(url);

Upvotes: 3

Bhuvan Rikka
Bhuvan Rikka

Reputation: 2703

EDIT:

$('.content').load('<?php echo json_encode($phpurl); ?>');

will do

Upvotes: 4

Ja͢ck
Ja͢ck

Reputation: 173662

As a generic rule you should properly escape variables when you move them between two realms, in this case from PHP to JavaScript.

This is especially true if you don't have full control over the variable contents, such as those coming from $_GET, $_POST, etc.

This is a safe bet, using json_encode() to form a proper JavaScript value:

$('.content').load(<?php echo json_encode($phpurl); ?>);

Upvotes: 2

Related Questions