0

I am new to this and really confused about it. Forgive me if it sounds stupid. I want to embed content on another domain using script tags. I learnt that the page supplying the content has to be give a json answer. The page supplying the content is a php file which brings it from my database. How do i go abou this?

I tried a simple example of json but it did not work, what am i doing wrong?

test.php

<script type="text/javascript" src="http://example.com/test2.php?WrapperFunction=SomeFuncNameSpecifiedInTheRequest">

test2.php

<script type="text/javascript">
function SomeFuncNameSpecifiedInTheRequest({"data" : "<pre>Some Html</pre>"});
</script>

2 Answers 2

2

The HTTP response for JSON-P should be:

  • JSON-P, not a fragment of HTML with embedded JSON-P
  • Call a function, so it shouldn't use the function keyword which defines one
  • Call a function that exists
  • Have the right content type

So in test.php

<script type="text/javascript">
    function SomeFuncNameSpecifiedInTheRequest(data) {
        // does stuff with the data object
    }
</script>
<script type="text/javascript" src="http://example.com/test2.php?WrapperFunction=SomeFuncNameSpecifiedInTheRequest">

and in test2.php

<?php
    header('Content-Type: application/javascript');
?>
SomeFuncNameSpecifiedInTheRequest({"data" : "<pre>Some Html</pre>"});
Sign up to request clarification or add additional context in comments.

2 Comments

The problem is i want to be able to give people a widget to embed using only the script tag. How do i do it without the top bit?
You stop using JSON-P and just provide them with a dynamically generated script with with embedded data. i.e. You put the top bit (without the script tags) in the main script.
0

The function keyword is used to define a new function. Since JSONP calls an already existing function (called a "callback function"), you don't need this keyword, and it's causing problems because I don't believe that is even valid ECMAScript.

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.