Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13699

Load php dynamically from a dynamic javascript

How can I load my php on my domain using my javascript that was loaded dynamically.

my sample code

sample.html(Client-side)

<div onClick = "getThis()"></div>

my.js(Client-side)

function getThis(){
var url = "http://www.sampledomain.com/test.js"
var script = document.createElement('script');
script.src = url;
document.head.appendChild(script); 
}

test.js(Server-side)

$.get("index.php", function(data) {
    alert(data);
});

index.php(Server-side)

<?php 

$_SESSION['user'] = "rob098";

?>

<script>
var data = '<?php echo json_encode($_SESSION['user']) ?>';
</script>

but it doesn't alert any.

Upvotes: 0

Views: 2400

Answers (3)

Rob Apodaca
Rob Apodaca

Reputation: 834

Use ajax and json:

sample.html

<div onClick = "getThis()"></div>

my.js (inside sample.html)

function getThis() {
  $.ajax({
    url: '/test.php',
    dataType: 'json',
    success: function(data){
      alert(data.user); //should alert rob098
    },
  });
}

test.php

header('Content-type: application/json');
echo json_encode(array("user" => "rob098"));

Upvotes: 1

Guilherme David da Costa
Guilherme David da Costa

Reputation: 2368

I think you are using jquery $.get() the wrong way. Well I've never seen used that way at least, so you need to change your index.php to this:

<?php
    $_SESSION['user'] = "rob098";
    echo json_encode($_SESSION['user']);

    header('Content-type: application/json');
?>

Let me know if I helped.

Upvotes: 0

Senad Meškin
Senad Meškin

Reputation: 13756

you have to append your js file to this

$(document).ready(function(){
$.get("index.php", function(data) {
    alert(data);
});

});

so when script file loaded it will execute code inside jQuery ready function

Upvotes: 0

Related Questions