0

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.

3 Answers 3

1

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"));
0

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

1
  • Tnx for the tip, gonna keep that on my head. But still it didn't work. Commented Dec 9, 2011 at 17:37
0

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.

1
  • Still no luck, tsk. It seems it does not load my php file Commented Dec 9, 2011 at 17:36

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.