0

I wasn't 100% how to phrase this question. I have a request to a URL similar to

example.php?miscData=JSON_FILE_NAME

Now JSON_FILE_NAME contains data unique to that file. I've got example.php set-up similar to below

    xmlHttpReq.open('GET', strURL, true);
    xmlHttpReq.onload = function(e) {
        var data = JSON.parse(this.response);
    }
    xmlHttpReq.send();

The request file has a function to handle the success of the call and is set up as below

function(retData, textStatus, xhr) { }

I expected retData would contain the JSON data {"name":"Dominic"} etc... But it doesn't. what am I doing wrong?

DominicEU
  • 3,585
  • 2
  • 21
  • 32
  • What does it return instead of JSON data? – Rey Gonzales Jun 20 '12 at 20:10
  • It responds the source of example.php, which is usually empty, or contains data dependent on how i've tried to set the page up. – DominicEU Jun 20 '12 at 20:11
  • Can you post your php code, since that's the one giving you problems? – Rey Gonzales Jun 20 '12 at 20:12
  • http://pastebin.com/c7h8V9JK is how it stands right this second. – DominicEU Jun 20 '12 at 20:14
  • So...in your code why are you posting to $setType-$gender.json (line 71) – Rey Gonzales Jun 20 '12 at 20:18
  • There is no POST to anything. I've been trying to write this piece of code for a few hours, and originally had it set-up completely wrong. This is more along the right lines. Inside example.php xmlhttpreq.responseText is right. But from request.php xmlhttpreq.responseText contains the source of example.php and I need it to contain the data contained within $setType-$gender.json – DominicEU Jun 20 '12 at 20:21
  • Which file is example.php and which one is request.php? – Rey Gonzales Jun 20 '12 at 20:24
  • That was example.php. Request.php contains the following js http://pastebin.com/VejXM6rm – DominicEU Jun 20 '12 at 20:26

1 Answers1

1

Your server side code from http://pastebin.com/c7h8V9JK is responding with an HTML page, not a JSON response. The code outside of your PHP is nothing but HTML. So naturally, when requesting the page, the server will return the HTML you've put outside of that php script.

Keep in mind, an AJAX request at its most basic is nothing special in terms of sending and receiving data from the server. Imagine that you have another tab open in your favorite tabbed browser, and that tab is navigating to the URL that your AJAX request is navigating to. That's what's going on when you make an AJAX request.

If you're trying to get JSON data from example.php, begin by removing all of the HTML from that file and serialize the data that you're trying to get using a JSON serializer.

encode json using php?

Community
  • 1
  • 1
villecoder
  • 13,323
  • 2
  • 33
  • 52