Blake
Blake

Reputation: 571

How to do a cross domain call with JSON in a PHP file?

I was wondering if anyone can give me a hand with cross domain calls with JSON, I know you have to use JSONP or ajax, but not quite to sure how to. I have a PHP file that grabs entries from MySQL database and builds them into a php file like so

api.php

    <?php
    $link = mysql_pconnect("localhost", "root", "") or die("Could not connect");
    mysql_select_db("blakewilson") or die("Could not select database");

    $arr = array();

    $rs = mysql_query("SELECT * FROM products");

    while($obj = mysql_fetch_object($rs)) {
    $arr[] = $obj;
    }
    echo '{"members":'.json_encode($arr).'}';
    ?>

Then i have an html file that grabs the link to the api.php files and displays all of the entries in a list, I just cant get it to work on cross domain.

showjson.html

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>jQuery</title>
    </style>
    </head>
    <body>
    <div id="msg">
    <table id="userdata" border="1">
    <thead>
    <th>Id</th>
    <th>Product</th>
    <th>Price</th>
    </thead>
    <tbody></tbody>
    </table>
    </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
    </script>
    <script type="text/javascript">

    $(document).ready(function(){
    var url="api.php";
    $("#userdata tbody").html("");
    $.getJSON(url,function(data){
    $.each(data.members, function(i,user){
    var tblRow =
    "<tr>"
    +"<td>"+user.postID+"</td>"
    +"<td>"+user.postProduct+"</td>"
    +"<td>$"+user.postDollar+"."+user.postCents+"</td>"
    +"</tr>" ;
    $(tblRow).appendTo("#userdata tbody");
    });
    });
    });

    </script>
    </body>
    </html>

Any help would be greatly appreciated. I apologize for the sloppy wording and code this is my first post on stack overflow :p

Upvotes: 0

Views: 89

Answers (1)

Bj&#246;rn3
Bj&#246;rn3

Reputation: 297

I dont know if i understand your question 100%, but in this type of situation, isnt a good method to generate a php file on the server that runs the javascript to? Just include the remote file with php, call it the same, api.php, and use ajax on that file and pass the parameters on. I have used this method several times.

This is not an actual answer to the question, but i think it is the correct answer in most circumstances.

Upvotes: 1

Related Questions