Umanda
Umanda

Reputation: 4843

Cross Domain Ajax data

I have a requirement which is getting cross domain json data via Ajax. I need to maintain 2 different server (Server A and Server B).

Server A only contain static contents. ie: JS, Images, Css

Server B only contain dynamic contents ie. php driven scripts

According to above requirement I have set up and successfully configured Nginx + Apache environment in my local pc.

I have a two domain run on my local host.

Server A : http://localhost:9000/ > running on Nginx as a front end for static content

Server B : http://localhost:8888/ > running on Apache as a back end for dynamic content (i.e. php)

Server A contain

index.html jquery and custom Ajax handling java script.

index.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="./js/jquery-1.7.2.min.js" type="application/javascript"></script>
<script src="./js/script.js" type="application/javascript"></script>
<title>Ajax</title>
</head>
<body>
<div id="result"></div>
</body>
</html>

script.js

$(document).ready(function(e) {
    var url = 'http://localhost:8888/drp/application/ajax.php';
        var success = function(data){
        var set = "";
            set += "Name: "+ data['fname']+ " " + data['lname']+"<br>";
            set += "Age: "+ data['age']+"<br>";
            set += "Address: "+ data['address']+"<br>";
            set += "Email: "+ data['email']+"<br>";
            set += "Web: "+ data['web']+"<br>";
            $('#result').html(set);
    };

    var error = function(jqXHR, textStatus, errorThrown){
            //alert(errorThrown);
            alert('errorThrown');
    };

    $.ajax({
          type: 'GET',   
          url: url,
          data:{todo:"jsonp"},
          dataType: "jsonp",
          crossDomain: true,         
          cache:false,
          success: success,
          error: error
    });
});

Server 2 contain ajax.php which is handle the Ajax request

ajax.php

<?php
#header('Content-Type: application/json');
header('Content-Type: application/javascript');



$x = array(

    'fname' => 'Jone',
    'lname' => 'Max',
    'age' => '26',
    'address' => 'London,Uk',
    'email' => '[email protected]',
    'web' => 'http://jonemaxtest.com',

);

print json_encode($x,true);
?>

When I am calling this front end index.html, I can see an error like this

SyntaxError: missing ; before statement 
{"fname":"Jone"...}

I tried so may time but I did nor get correct result. every time I get this kind of error message. also I have tried to change header('Content-Type: application/javascript'); into header('Content-Type: application/json'); but did not work.

where I did my mistake in that code set...?

Please help me.!

Upvotes: 1

Views: 1172

Answers (3)

SarathSprakash
SarathSprakash

Reputation: 4624

There are some mistakes in your code

  • You have to set the dataType="json" instead of "jsonp" in your ajax call since you are passing json

    The corrected code is below

    $(document).ready(function(e) {
        var url = 'http://localhost:8888/drp/application/ajax.php';
            var success = function(data){
            var set = "";
                set += "Name: "+ data['fname']+ " " + data['lname']+"<br>";
                set += "Age: "+ data['age']+"<br>";
                set += "Address: "+ data['address']+"<br>";
                set += "Email: "+ data['email']+"<br>";
                set += "Web: "+ data['web']+"<br>";
                $('#result').html(set);
        };
    
        var error = function(jqXHR, textStatus, errorThrown){
                //alert(errorThrown);
                alert('errorThrown');
        };
    
        $.ajax({
              type: 'GET',   
              url: url,
              data:{todo:"jsonp"},
              dataType: "json", 
              crossDomain: true,       
              cache:false,
              success: success,
              error: error
        });
    }); 
    
    • In your ajax.php you have set header as application/javascript , but your data is json so change it to application/json and you should also add another header to allow cross Domain header('Access-Control-Allow-Origin: *');.

      Here is the corrected code

         <?php
          header('Access-Control-Allow-Origin: *');
          header('Content-Type: application/json');
          $x = array(
      
           'fname' => 'Jone',
           'lname' => 'Max',
           'age' => '26',
           'address' => 'London,Uk',
           'email' => '[email protected]',
            'web' => 'http://jonemaxtest.com',
      
           );
      
             print json_encode($x,true);
            ?>
      

Hope this helps, Thank you

Upvotes: 2

Lee P
Lee P

Reputation: 21

Try returning a string from the server which is like:

$data = json_encode($x);
echo "/**/my_callback($data);";

Where data is your JSON encoded array.

And don't forget to remove the header for the content type.

In your JavaScript in the Ajax request, on success:

function (data) {eval(data);}

Upvotes: 2

Related Questions