0

I'm trying to develop something that would allow a site owner to include a script I provide to send back data to my server and return some HTML that gets appended into a div on the requesting site.

For example: Bob's Tires embeds my script in the header (or wherever)...something like this:

<script src="https://example.com/special.js"></script>

I would need data sent back to this script so I can return some HTML. In this case, find the div with a specific class and send me the class name.

<div class="special 123456></div> <!--this would be on Bob's site-->

What I would want back is the "123456". I know how to do this when writing the code to live all on the same page/domain, but how do I say

$(".special").prop("classList") 

for Bob's Site and send this back to my server so I can send something back based on this data (i.e., something specific for "123456")?

jonmrich
  • 4,233
  • 5
  • 42
  • 94
  • Have you considered jsonp? Also see this: https://www.html5rocks.com/en/tutorials/cors/ – Mike Cheel Oct 05 '17 at 15:47
  • Just because your javascript is hosted on a remote server doesn't mean that it isn't running on the page. It makes zero difference except for the fact that you need to send the data cross-domain. – Turnip Oct 05 '17 at 15:53
  • @Turnip Good point. Are there any issues with sending the data cross-domain (assume it's not at all sensitive information) – jonmrich Oct 05 '17 at 15:57
  • Your server would need to allow cross-domain requests. Other than that it should be a straight forward ajax requests. If you are worried about security then that is [a whole other (huge) topic](https://stackoverflow.com/questions/37912937/how-to-send-secure-ajax-requests-with-php-and-jquery). – Turnip Oct 05 '17 at 16:03

1 Answers1

0

Try this example:

In Bob's page:

<script src="//your_site.com/phpjs_test.php?id=123"></script>

In the phpjs_test.php on your site:

if(isset($_GET['id'])) {
  $res = ($_GET['id']==123) ? "abc": 758;
  echo 'document.write("'. $res .'");';
}

Some details and example to this subtitle: Displaying data from PHP with JavaScript, according to a URL, on this page: http://coursesweb.net/javascript/javascript-code-php

CoursesWeb
  • 4,179
  • 3
  • 21
  • 27