1

I just started to work on calls to a php file which is present in a different server. I am aware of CORS which is essential for cross domain requests. I have been trying to call this file through ajax methods refering to other websites and tutorials and I have seen discussions to find a solution but they are not working for me. Please help.

here is my calling method:

            $.ajax({
                    type: "GET",
                    url: "http://cs-server.usc.edu:27952/ResponseProg.php?callback=?", //Relative or absolute path to response.php file
                    datatype: "jsonp",
                    data: dataInput,
                    jsonp:'jsoncallback',
                    crossDomain:true,
                    success: function(data) 
                    {
                        JSONObj = jQuery.parseJSON(data);
                        contentProvider("#rtrn");
                        if(JSONObj.ack != "No results found")
                        {
                            var paginate=setPager(0);
                            $("#pgn").html(paginate);
                        }
                    },
                    error: function() {
                        $("#rtrn").html("Data not retrieved successfully");
                    }
                });

Here is my PHP code snippet:

<?php
#code for data processing...
$rsltjson = json_encode($result,JSON_UNESCAPED_SLASHES);
echo $_GET['jsoncallback']."(".$rsltjson.");";
?>

I am trying to accomplish this by using JSONP. Should I have any headers? Are there any errors in my code?....How can I accomplish this? dataInput is the serialized form of form data

  • Have you tried this ? http://stackoverflow.com/a/10143166/3512867 – spenibus Jul 13 '15 at 15:33
  • What error do you actually get ? – spenibus Jul 14 '15 at 15:10
  • @spenibus: The code works but only the error handler function is executed...I did see the link you sent me...I know the I am supposed to put the header but I am not finding the .htaccess file if not that i do not know which directory tag to put in the httpd.conf file – user3426359 Jul 20 '15 at 04:50

1 Answers1

2

The CORS way

You need to put the appropriate header in your php script and output only the JSON:

<?php
    header('Access-Control-Allow-Origin: *');

    // rest of the code

    // output JSON only
    echo $rsltjson;
?>

Then using a XMLHttpRequest/ajax call should retrieve the data just fine as JSON without resorting to JSONP.

Mozilla has plenty to read about it

The JSONP way

Since the whole point of JSONP is to bypass cross-domain restrictions, calling a JSONP resource with XMLHttpRequest/ajax, a method in which cross-domain security is fully applied (presumably), is completely useless.

JSONP works by injecting code directly into your page, calling a function that you defined, which is why a JSONP url takes an argument. Therefore, the correct way to call your JSONP url is this:

<script>
function myDataFunc(data) {
    JSONObj = jQuery.parseJSON(data);
    contentProvider("#rtrn");
    if(JSONObj.ack != "No results found") {
        var paginate=setPager(0);
        $("#pgn").html(paginate);
    }
}
</script>
<script src="http://cs-server.usc.edu:27952/ResponseProg.php?jsoncallback=myDataFunc"></script>

The JSONP url will return something that looks like this:

myDataFunc({"a":"fhsfg","b":"qfdgers","c":"difgij"});

Since it is included as a script, it will be executed directly in your page, calling the function myDataFunc() that you defined earlier.

Also note that your php file use the GET parameter jsoncallback while your javascript calls the url with the parameter callback, which would not work.

Finally, you use jQuery.parseJSON(), which produces this error from your code:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

The reason can be found in the jQuery docs:

jQuery.parseJSON( json )
Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
Passing in a malformed JSON string results in a JavaScript exception being thrown.

Your php script feeds your callback with a JSON object

{"a":"fhsfg","b":"qfdgers","c":"difgij"}

rather than a string representing a JSON object

'{"a":"fhsfg","b":"qfdgers","c":"difgij"}'

Note the surrounding quotes, which makes this data a string. We fix this in php by adding the quotes around the data:

echo $_GET['jsoncallback']."('".$rsltjson."');";

Obviously if your JSON data contains single quotes, you will have to escape them.

spenibus
  • 4,339
  • 11
  • 26
  • 35
  • I used the solution for CORS which you had mentioned but i now get the error as `SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data`...but this does not occur when my php file is in the same location as my html code – user3426359 Jul 20 '15 at 19:14
  • I updated accordingly. The php script needs to output the JSON alone. – spenibus Jul 20 '15 at 19:30
  • Upvoted, this is a nice, detailed and correct answer which provides working solution. @user3426359 you should implement what spenbus wrote, I can confirm it works properly. – N.B. Jul 20 '15 at 19:31
  • My bad, I forgot to mention that I am returning JSON instead of JSONP. Here is the code for returning the json from my php file. `$rsltjson = json_encode($result,JSON_UNESCAPED_SLASHES); echo $rsltjson;` – user3426359 Jul 21 '15 at 04:38
  • Even I agree to what is suggested by spenibus...but even though I am returning json only, I am getting the above mentioned error...if i can resolve that somehow it will work. Is there something else i must change in my php code?...When I execute my local php file i get no such errors – user3426359 Jul 21 '15 at 05:01
  • I get the JSON output when i call my file which is in my own machine but nothing appears when I call my file which is in another server despite having made changes as you suggested – user3426359 Jul 21 '15 at 06:34
  • Well there isn't much more I can do based on what I already know. – spenibus Jul 21 '15 at 06:55
  • Should i make changes to the httpd.conf files in my server which is holding the php code? is it because of having not changed the conf file that it is not working? – user3426359 Jul 21 '15 at 19:16
  • I don't know, this goes beyond the parameters of the question, I don't have the information to answer that. I provided you with working code but I can't magically determine what else is wrong with your setup. A blank page could be a syntax error but i just can't know. – spenibus Jul 21 '15 at 19:48